提交 71a2a50d 编写于 作者: L lanyi 提交者: Gitee

Merge branch 'master' of gitee.com:openharmony/docs into lanyi_card

Signed-off-by: Nlanyi <lanyi3@huawei.com>
...@@ -155,10 +155,10 @@ zh-cn/application-dev/media/avsession-guidelines.md @zengyawen @liuyuehua1 @saga ...@@ -155,10 +155,10 @@ zh-cn/application-dev/media/avsession-guidelines.md @zengyawen @liuyuehua1 @saga
zh-cn/application-dev/media/image.md @zengyawen @zhangqiang183 @wind_zj @zxg-gitee zh-cn/application-dev/media/image.md @zengyawen @zhangqiang183 @wind_zj @zxg-gitee
zh-cn/application-dev/media/camera.md @zengyawen @liuyuehua1 @saga2020 @currydavids zh-cn/application-dev/media/camera.md @zengyawen @liuyuehua1 @saga2020 @currydavids
zh-cn/application-dev/media/remote-camera.md @zengyawen @liuyuehua1 @saga2020 @currydavids zh-cn/application-dev/media/remote-camera.md @zengyawen @liuyuehua1 @saga2020 @currydavids
zh-cn/application-dev/security/accesstoken-overview.md @zengyawen @nianCode @nianCode @jinhaihw zh-cn/application-dev/security/accesstoken-overview.md @zengyawen @nianCode @shuqinglin2 @jinhaihw
zh-cn/application-dev/security/accesstoken-guidelines.md @zengyawen @nianCode @nianCode @jinhaihw zh-cn/application-dev/security/accesstoken-guidelines.md @zengyawen @nianCode @shuqinglin2 @jinhaihw
zh-cn/application-dev/security/permission-verify-guidelines.md @zengyawen @nianCode @nianCode @jinhaihw zh-cn/application-dev/security/permission-verify-guidelines.md @zengyawen @nianCode @shuqinglin2 @jinhaihw
zh-cn/application-dev/security/permission-list.md @zengyawen @zengyawen @nianCode @nianCode @jinhaihw zh-cn/application-dev/security/permission-list.md @zengyawen @shuqinglin2
zh-cn/application-dev/security/userauth-overview.md @zengyawen @gaoyong @niejiteng @jumozhanjiang zh-cn/application-dev/security/userauth-overview.md @zengyawen @gaoyong @niejiteng @jumozhanjiang
zh-cn/application-dev/security/userauth-guidelines.md @zengyawen @gaoyong @niejiteng @jumozhanjiang zh-cn/application-dev/security/userauth-guidelines.md @zengyawen @gaoyong @niejiteng @jumozhanjiang
zh-cn/application-dev/security/huks-overview.md @zengyawen @gaoyong @niejiteng @jumozhanjiang zh-cn/application-dev/security/huks-overview.md @zengyawen @gaoyong @niejiteng @jumozhanjiang
...@@ -280,7 +280,7 @@ zh-cn/application-dev/reference/apis/js-apis-inner-application-windowExtensionCo ...@@ -280,7 +280,7 @@ zh-cn/application-dev/reference/apis/js-apis-inner-application-windowExtensionCo
zh-cn/application-dev/reference/apis/js-apis-appmanager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-appmanager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-arraylist.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-arraylist.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-audio.md @liuyuehua1 @zengyawen @magekkkk @currydavids zh-cn/application-dev/reference/apis/js-apis-audio.md @liuyuehua1 @zengyawen @magekkkk @currydavids
zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-battery-info.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-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-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125
zh-cn/application-dev/reference/apis/js-apis-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208
...@@ -334,7 +334,7 @@ zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @shuaytao ...@@ -334,7 +334,7 @@ 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-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-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-distributed-data.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-document.md @panqinxu @zengyawen @bubble_mao @jinhaihw 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-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-emitter.md @jayleehw @RayShih @li-weifeng2 @currydavids
...@@ -368,18 +368,18 @@ zh-cn/application-dev/reference/apis/js-apis-http.md @zhang-hai-feng @zengyawen ...@@ -368,18 +368,18 @@ zh-cn/application-dev/reference/apis/js-apis-http.md @zhang-hai-feng @zengyawen
zh-cn/application-dev/reference/apis/js-apis-huks.md @gaoyong @zengyawen @niejiteng @jumozhanjiang 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 @ningningW @mengjingzhimo @yangqing3 zh-cn/application-dev/reference/apis/js-apis-i18n.md @Buda-Liu @ningningW @mengjingzhimo @yangqing3
zh-cn/application-dev/reference/apis/js-apis-image.md @zhangqiang183 @zengyawen @chenyuheng @zxg-gitee 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 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @yuanxinying @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-inputdevice.md @yuanxinying @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-inputevent.md @yuanxinying @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-inputeventclient.md @yuanxinying @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-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-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-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-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-inputmonitor.md @yuanxinying @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-intl.md @Buda-Liu @ningningW @mengjingzhimo @yangqing3 zh-cn/application-dev/reference/apis/js-apis-intl.md @Buda-Liu @ningningW @mengjingzhimo @yangqing3
zh-cn/application-dev/reference/apis/js-apis-keycode.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-keycode.md @yuanxinying @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-keyevent.md @yuanxinying @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-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-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-linkedlist.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
...@@ -389,7 +389,7 @@ zh-cn/application-dev/reference/apis/js-apis-media.md @liuyuehua1 @zengyawen @xx ...@@ -389,7 +389,7 @@ zh-cn/application-dev/reference/apis/js-apis-media.md @liuyuehua1 @zengyawen @xx
zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @panqinxu @zengyawen @bubble_mao @jinhaihw 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-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-missionManager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-mouseevent.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-mouseevent.md @yuanxinying @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-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-nfcController.md @cheng_guohong @RayShih @cheng_guohong @quanli125
zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @cheng_guohong @RayShih @cheng_guohong @quanli125
...@@ -400,7 +400,7 @@ zh-cn/application-dev/reference/apis/js-apis-particleAbility.md @littlejerry1 @R ...@@ -400,7 +400,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-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-permissionrequestresult.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-plainarray.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-plainarray.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-pointer.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-pointer.md @yuanxinying @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-power.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-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-privacyManager.md @nianCode @zengyawen @shuqinglin2 @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-process.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-process.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
...@@ -482,8 +482,8 @@ zh-cn/application-dev/reference/apis/js-apis-window.md @zhangqiang183 @ge-yafan ...@@ -482,8 +482,8 @@ zh-cn/application-dev/reference/apis/js-apis-window.md @zhangqiang183 @ge-yafan
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-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-worker.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-taskpool.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-taskpool.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-workScheduler.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-workScheduler.md @chenmingJay @ningningW @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @chenmingJay @ningningW @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-xml.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-xml.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-zlib.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-zlib.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-webview.md @bigpumpkin @HelloCrease @litao33 @zhang-xinyue15 zh-cn/application-dev/reference/apis/js-apis-webview.md @bigpumpkin @HelloCrease @litao33 @zhang-xinyue15
...@@ -521,7 +521,7 @@ zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md @shuaytao @RayShih ...@@ -521,7 +521,7 @@ zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md @shuaytao @RayShih
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-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-commonEventManager.md @jayleehw @RayShih @li-weifeng2 @currydavids
zh-cn/application-dev/reference/apis/js-apis-configPolicy.md @Buda-Liu @ningningW @budda-wang @yangqing3 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-cooperate.md @yuanxinying @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-cryptoFramework.md @gaoyong @zengyawen @niejiteng @jumozhanjiang
zh-cn/application-dev/reference/apis/js-apis-cert.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-cert.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-curve.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy
...@@ -543,10 +543,10 @@ zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md @zhang-hai-feng @ze ...@@ -543,10 +543,10 @@ 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-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-nfctech.md @cheng_guohong @RayShih @cheng_guohong @quanli125
zh-cn/application-dev/reference/apis/js-apis-promptAction.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-promptAction.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @chenmingJay @ningningW @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @chenmingJay @ningningW @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-stationary.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-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-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-system-parameterV9.md @mupceet @zengyawen @handyohos @nan-xiansen
......
...@@ -18,7 +18,7 @@ This repository stores device and application development documents provided by ...@@ -18,7 +18,7 @@ This repository stores device and application development documents provided by
- master: the latest version. - master: the latest version.
- OpenHarmony 3.2 Beta3. [Learn more](en/release-notes/OpenHarmony-v3.2-beta3.md) - OpenHarmony 3.2 Beta5. [Learn more](en/release-notes/OpenHarmony-v3.2-beta5.md)
- OpenHarmony 3.1 Release. [Learn more](en/release-notes/OpenHarmony-v3.1-release.md) - OpenHarmony 3.1 Release. [Learn more](en/release-notes/OpenHarmony-v3.1-release.md)
...@@ -34,7 +34,7 @@ This repository stores device and application development documents provided by ...@@ -34,7 +34,7 @@ This repository stores device and application development documents provided by
### Historical Stable Versions ### Historical Stable Versions
OpenHarmony_v1.x_release: OpenHarmony v1.1.5 LTS. [Learn more](en/release-notes/OpenHarmony-v1.1.5-LTS.md) OpenHarmony_v1.x_release: OpenHarmony 1.1.5 LTS. [Learn more](en/release-notes/OpenHarmony-v1.1.5-LTS.md)
[More versions](en/release-notes/) [More versions](en/release-notes/)
...@@ -51,6 +51,6 @@ You can evaluate available documents, make simple modifications, provide feedbac ...@@ -51,6 +51,6 @@ You can evaluate available documents, make simple modifications, provide feedbac
Excellent contributors will be awarded and the contributions will be publicized in the developer community. Excellent contributors will be awarded and the contributions will be publicized in the developer community.
- Mail list: docs@openharmony.io - Mailing list: docs@openharmony.io
- Zulip group: documentation_sig - Zulip group: documentation_sig
\ No newline at end of file
...@@ -183,7 +183,7 @@ For details about how to obtain the source code of OpenHarmony, see [Source Code ...@@ -183,7 +183,7 @@ For details about how to obtain the source code of OpenHarmony, see [Source Code
## Hands-On Tutorials ## Hands-On Tutorials
[Samples](https://gitee.com/openharmony/app_samples) [Samples](https://gitee.com/openharmony/applications_app_samples)
[Codelabs](https://gitee.com/openharmony/codelabs) [Codelabs](https://gitee.com/openharmony/codelabs)
......
...@@ -24,7 +24,7 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O ...@@ -24,7 +24,7 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O
All applications should be developed on top of these frameworks. All applications should be developed on top of these frameworks.
Then, equip yourself for developing the key features, with the following guidelines: Then, equip yourself for developing the key features, with the following guidelines:
- [Common Event and Notification](notification/notification-brief.md) - [Common Event and Notification](notification/notification-overview.md)
- [Window Manager](windowmanager/window-overview.md) - [Window Manager](windowmanager/window-overview.md)
- [WebGL](webgl/webgl-overview.md) - [WebGL](webgl/webgl-overview.md)
- [Media](media/audio-overview.md) - [Media](media/audio-overview.md)
......
...@@ -19,6 +19,7 @@ ...@@ -19,6 +19,7 @@
- [ServiceExtensionAbility](serviceextensionability.md) - [ServiceExtensionAbility](serviceextensionability.md)
- [DataShareExtensionAbility](datashareextensionability.md) - [DataShareExtensionAbility](datashareextensionability.md)
- [FormExtensionAbility (Widget)](widget-development-stage.md) - [FormExtensionAbility (Widget)](widget-development-stage.md)
- [StaticSubscriberExtensionAbility](static-subscriber-extension-ability.md)
- [AbilityStage Component Container](abilitystage.md) - [AbilityStage Component Container](abilitystage.md)
- [Context](application-context-stage.md) - [Context](application-context-stage.md)
- Want - Want
......
# AccessibilityExtensionAbility Development
The **AccessibilityExtensionAbility** module provides accessibility extension capabilities based on the **ExtensionAbility** framework. You can develop your accessibility applications by applying the **AccessibilityExtensionAbility** template to enhance usability.
> **Environment Requirements**
>
> IDE: DevEco Studio 3.0 Beta3 (3.0.0.900) or later
>
> SDK: API version 9 or later
>
> Model: stage
This document is organized as follows:
- [Creating an AccessibilityExtAbility File](#creating-an-accessibility-extension-service)
- [Processing an Accessibility Event](#processing-an-accessibility-event)
- [Declaring Capabilities of Accessibility Extension Services](#declaring-capabilities-of-accessibility-extension-services)
- [Enabling a Custom Accessibility Extension Service](#enabling-a-custom-accessibility-extension-service)
## Creating an Accessibility Extension Service
You can create an accessibility extension service by creating a project from scratch or adding the service to an existing project.
### Creating a Project
Perform the following steps in DevEco Studio:
1. From the upper left corner of DevEco Studio, choose **File** > **New** > **Create Project**.
2. By following the project creation wizard, click the **OpenHarmony** tab, select the **Empty Ability** template, and then click **Next**.
3. Set **Project type** to **Application**, **Compile API** (or **Compile SDK**, depending on the version used) to **9**, and **Model** to **Stage**, and then click **Finish**.
### Creating an AccessibilityExtAbility File
To add an accessibility extension service to a project, create the **AccessibilityExtAbility** folder in the **ets** folder of the project, create the **AccessibilityExtAbility.ts** file in the new folder, and add the following code to the new file:
```typescript
import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility';
class AccessibilityExtAbility extends AccessibilityExtensionAbility {
onConnect() {
console.log('AccessibilityExtAbility onConnect');
}
onDisconnect() {
console.log('AccessibilityExtAbility onDisconnect');
}
onAccessibilityEvent(accessibilityEvent) {
console.log('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent));
}
}
export default AccessibilityExtAbility;
```
The APIs defined in the file are as follows.
| API| Description|
| ---- | ---- |
| onConnect(): void | Called when a connection with the extension service is set up.|
| onDisconnect(): void | Called when the connection with the extension service is severed.|
| onAccessibilityEvent(event: AccessibilityEvent): void | Called when an accessibility event occurs|
## Processing an Accessibility Event
You can process the service logic for accessibility events in the **onAccessibilityEvent()** API. For details about the events, see [AccessibilityEvent](../reference/apis/js-apis-application-accessibilityExtensionAbility.md#accessibilityevent). The following code snippet uses the **pageStateUpdate** event as an example.
```typescript
onAccessibilityEvent(accessibilityEvent) {
console.log('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent));
if (accessibilityEvent.eventType === 'pageStateUpdate') {
console.log('AccessibilityExtAbility onAccessibilityEvent: pageStateUpdate');
// TODO: Develop custom logic.
}
}
```
For an accessibility event, you can use the APIs of the [AccessibilityExtensionContext](../reference/apis/js-apis-inner-application-accessibilityExtensionContext.md) module to configure the concerned information, obtain root information, and inject gestures.
You can also process physical key events in the accessibility extension service. For details, see [onKeyEvent](../reference/apis/js-apis-application-accessibilityExtensionAbility.md#accessibilityextensionabilityonkeyevent).
## Declaring Capabilities of Accessibility Extension Services
After developing the custom logic for an accessibility extension service, you must add the configuration information of the service to the corresponding module-level **module.json5** file in the project directory. In the file, the **srcEntrance** tag indicates the path to the accessibility extension service. Make sure the value of the **type** tag is fixed at **accessibility**. Otherwise, the connection to the service will fail.
```json
"extensionAbilities": [
{
"name": "AccessibilityExtAbility",
"srcEntrance": "./ets/AccessibilityExtAbility/AccessibilityExtAbility.ts",
"label": "$string:MainAbility_label",
"description": "$string:MainAbility_desc",
"type": "accessibility",
"metadata": [
{
"name": "ohos.accessibleability",
"resource": "$profile:accessibility_config"
}
]
}
]
```
**accessibility_config** is the specific configuration of the accessibility extension service. You need to create the **accessibility_config.json** file in **resources/base/profile/** and declare the [capabilities](../reference/apis/js-apis-accessibility.md#capability) of the service in the file.
```json
{
"accessibilityCapabilities": [
"retrieve",
"gesture"
]
}
```
## Enabling a Custom Accessibility Extension Service
To enable or disable an accessibility extension service, run the following command:
- To enable the service: **accessibility enable -a AccessibilityExtAbility -b com.example.demo -c rg**
- To disable the service: **accessibility disable -a AccessibilityExtAbility -b com.example.demo**
In the preceding commands, **AccessibilityExtAbility** indicates the name of the accessibility extension service, **com.example.demo** indicates the bundle name, and **rg** indicates the capabilities (**r** is short for retrieve).
If the service is enabled or disabled successfully, the message "enable ability successfully" or "disable ability successfully" is displayed.
# Common action and entities Values # Common action and entities Values
The [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) field specifies the common operation (such as viewing, sharing, and application details) to be performed by the caller. 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, for example, viewing URI data. For example, if the URI is a website and the action is **ohos.want.action.viewData**, the ability that supports website viewing is matched. Declaring the **action** field in Want indicates that the invoked application should support the declared operation. The **actions** field under **skills** in the configuration file indicates the operations supported by the application. **action**: Action to take, such as viewing, sharing, and application details, by the caller. 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, for example, viewing URI data. For example, if the URI is a website and the action is **ohos.want.action.viewData**, the ability that supports website viewing is matched. Declaring the **action** field in Want indicates that the invoked application should support the declared operation. The **actions** field under **skills** in the configuration file indicates the operations supported by the application.
**Common action Values** **Common action Values**
...@@ -14,7 +14,7 @@ The [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantactio ...@@ -14,7 +14,7 @@ The [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantactio
- **ACTION_VIEW_MULTIPLE_DATA**: action of launching the UI for sending multiple data records. - **ACTION_VIEW_MULTIPLE_DATA**: action of launching the UI for sending multiple data records.
The [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) field specifies the additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want. You can define this field to filter application categories, for example, browser. Declaring the **entities** field in Want indicates that the invoked application should belong to the declared category. The **entities** field under **skills** in the configuration file indicates the categories supported by the application. **entities**: Category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want. You can define this field to filter application categories, for example, browser. Declaring the **entities** field in Want indicates that the invoked application should belong to the declared category. The **entities** field under **skills** in the configuration file indicates the categories supported by the application.
**Common entities Values** **Common entities Values**
......
...@@ -3,7 +3,8 @@ ...@@ -3,7 +3,8 @@
When developing an application, you may need to configure certain tags to identify the application, such as the bundle name and application icon. This topic describes key tags that need to be configured during application development. Icons and labels are usually configured together. There is the application icon, application label, entry icon, and entry label, which correspond to the **icon** and **label** fields in the [app.json5 file](../quick-start/app-configuration-file.md) and [module.json5 file](../quick-start/module-configuration-file.md). The application icon and label are used in **Settings**. For example, they are displayed in the application list in **Settings**. The entry icon is displayed on the device's home screen after the application is installed. The entry icon maps to a [UIAbility](uiability-overview.md) component. Therefore, an application can have multiple entry icons and labels. When you touch one of them, the corresponding UIAbility page is displayed. When developing an application, you may need to configure certain tags to identify the application, such as the bundle name and application icon. This topic describes key tags that need to be configured during application development. Icons and labels are usually configured together. There is the application icon, application label, entry icon, and entry label, which correspond to the **icon** and **label** fields in the [app.json5 file](../quick-start/app-configuration-file.md) and [module.json5 file](../quick-start/module-configuration-file.md). The application icon and label are used in **Settings**. For example, they are displayed in the application list in **Settings**. The entry icon is displayed on the device's home screen after the application is installed. The entry icon maps to a [UIAbility](uiability-overview.md) component. Therefore, an application can have multiple entry icons and labels. When you touch one of them, the corresponding UIAbility page is displayed.
**Figure 1** Icons and labels
**Figure 1** Icons and labels
![application-component-configuration-stage](figures/application-component-configuration-stage.png) ![application-component-configuration-stage](figures/application-component-configuration-stage.png)
...@@ -14,11 +15,11 @@ When developing an application, you may need to configure certain tags to identi ...@@ -14,11 +15,11 @@ When developing an application, you may need to configure certain tags to identi
- **Configuring the application icon and label** - **Configuring the application icon and label**
The application icon is specified by the **icon** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory of the project. The **icon** field must be set to the index of an image so that the image is displayed as the application icon. The application icon is usually displayed in an application list, for example, the application list in **Settings**. You must configure an icon and label for an application on the stage model.
The application label is specified by the **label** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** module of the project. The **label** field specifies the application name displayed to users. It must be set to the index of a string resource. The application icon is specified by the **icon** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory of the project. The **icon** field must be set to the index of an image so that the image is displayed as the application icon.
The **icon** and **label** fields in the **app.json5** file are under **app**, as follows: The application label is specified by the **label** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** module of the project. The **label** field specifies the application name displayed to users. It must be set to the index of a string resource.
```json ```json
{ {
...@@ -32,7 +33,9 @@ When developing an application, you may need to configure certain tags to identi ...@@ -32,7 +33,9 @@ When developing an application, you may need to configure certain tags to identi
- **Configuring the entry icon and label** - **Configuring the entry icon and label**
The entry icon and label are configured by specifying **icon** and **label** under **abilities** in the [module.json5 file](../quick-start/module-configuration-file.md). For example, if you want to display the icon and label of the UIAbility component on the home screen, add **entity.system.home** to **entities** and **action.system.home** to **actions** under **skills**. If the preceding fields are configured for multiple UIAbility components of an application, multiple icons and labels are displayed on the home screen, corresponding to their respective UIAbility component. On the stage model, you can configure an entry icon and label for each application component. The entry icon and label are displayed on the home screen.
The entry icon is configured by specifying **icon** under **abilities** in the [module.json5 file](../quick-start/module-configuration-file.md). For example, if you want to display the icon of the UIAbility component on the home screen, add **entity.system.home** to **entities** and **ohos.want.action.home** to **actions** under **skills**. If this field is configured for multiple UIAbility components of an application, multiple icons are displayed on the home screen, corresponding to their respective UIAbility component.
```json ```json
{ {
...@@ -49,7 +52,7 @@ When developing an application, you may need to configure certain tags to identi ...@@ -49,7 +52,7 @@ When developing an application, you may need to configure certain tags to identi
"entity.system.home" "entity.system.home"
], ],
"actions": [ "actions": [
"action.system.home" "ohos.want.action.home"
] ]
} }
], ],
...@@ -69,4 +72,3 @@ When developing an application, you may need to configure certain tags to identi ...@@ -69,4 +72,3 @@ When developing an application, you may need to configure certain tags to identi
- **Configuring the module permission** - **Configuring the module permission**
The **requestPermission** field in the [module.json5 file](../quick-start/module-configuration-file.md) is used to configure the permission information required by the module to access the protected part of the system or other applications. This field declares the name of the permission to request, the reason for requesting the permission, and the scenario where the permission is used. The **requestPermission** field in the [module.json5 file](../quick-start/module-configuration-file.md) is used to configure the permission information required by the module to access the protected part of the system or other applications. This field declares the name of the permission to request, the reason for requesting the permission, and the scenario where the permission is used.
...@@ -10,11 +10,11 @@ ...@@ -10,11 +10,11 @@
![context-inheritance](figures/context-inheritance.png) ![context-inheritance](figures/context-inheritance.png)
- The figure below illustrates the holding relationship of contexts. - The figure below illustrates the holding relationship of contexts.
![context-holding](figures/context-holding.png) ![context-holding](figures/context-holding.png)
- The following describes the information provided by different contexts. - The following describes the information provided by different contexts.
- [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md): Each UIAbility has the **Context** attribute, which provides APIs to operate the ability, obtain the ability configuration, and more. - [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md): Each UIAbility has the **Context** attribute, which provides APIs to operate an application component, obtain the application component configuration, and more.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
...@@ -25,6 +25,10 @@ ...@@ -25,6 +25,10 @@
} }
} }
``` ```
> **NOTE**
>
> For details about how to obtain the context of a **UIAbility** instance on the page, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
- Scenario-specific [ExtensionContext](../reference/apis/js-apis-inner-application-extensionContext.md): For example, ServiceExtensionContext, inherited from ExtensionContext, provides APIs related to background services. - Scenario-specific [ExtensionContext](../reference/apis/js-apis-inner-application-extensionContext.md): For example, ServiceExtensionContext, inherited from ExtensionContext, provides APIs related to background services.
```ts ```ts
...@@ -47,7 +51,7 @@ ...@@ -47,7 +51,7 @@
} }
} }
``` ```
- [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md): application-level context. It provides APIs for subscribing to ability lifecycle changes, system memory changes, and system environment changes. The application-level context can be obtained from UIAbility, ExtensionAbility, and AbilityStage. - [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md): application-level context. It provides APIs for subscribing to application component lifecycle changes, system memory changes, and system environment changes. The application-level context can be obtained from UIAbility, ExtensionAbility, and AbilityStage.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
...@@ -179,13 +183,10 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] ...@@ -179,13 +183,10 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
> To obtain the context of another application: > To obtain the context of another application:
> >
> - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
>
> - This is a system API and cannot be called by third-party applications.
>
> - This is a system API and cannot be called by third-party applications. > - This is a system API and cannot be called by third-party applications.
For example, application information displayed on the home screen includes the application name and icon. The home screen application calls the foregoing method to obtain the context information, so as to obtain the resource information including the application name and icon. For example, application information displayed on the home screen includes the application name and icon. The home screen application calls the foregoing method to obtain the context information, so as to obtain the resource information including the application name and icon.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
...@@ -198,7 +199,6 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] ...@@ -198,7 +199,6 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
} }
} }
``` ```
- Call **createModuleContext(bundleName:string, moduleName:string)** to obtain the context of a specified module of another application. After obtaining the context, you can obtain the resource information of that module. - Call **createModuleContext(bundleName:string, moduleName:string)** to obtain the context of a specified module of another application. After obtaining the context, you can obtain the resource information of that module.
> **NOTE** > **NOTE**
...@@ -206,9 +206,6 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] ...@@ -206,9 +206,6 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
> To obtain the context of a specified module of another application: > To obtain the context of a specified module of another application:
> >
> - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
>
> - This is a system API and cannot be called by third-party applications.
>
> - This is a system API and cannot be called by third-party applications. > - This is a system API and cannot be called by third-party applications.
```ts ```ts
...@@ -223,7 +220,7 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] ...@@ -223,7 +220,7 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
} }
} }
``` ```
- Call **createModuleContext(moduleName:string)** to obtain the context of another module in the current application. After obtaining the context, you can obtain the resource information of that module. - Call **createModuleContext(moduleName:string)** to obtain the context of another module in the current application. After obtaining the context, you can obtain the resource information of that module.
```ts ```ts
......
...@@ -50,7 +50,7 @@ The system matches the **want** parameter (including the **action**, **entities* ...@@ -50,7 +50,7 @@ The system matches the **want** parameter (including the **action**, **entities*
### Matching Rules of action in the want Parameter ### Matching Rules of action in the want Parameter
The system matches the [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) attribute in the **want** parameter passed by the caller against **actions** under **skills** of the abilities. The system matches the **action** attribute in the **want** parameter passed by the caller against **actions** under **skills** of the abilities.
- If **action** in the passed **want** parameter is specified but **actions** under **skills** of an ability is unspecified, the matching fails. - If **action** in the passed **want** parameter is specified but **actions** under **skills** of an ability is unspecified, the matching fails.
...@@ -62,12 +62,12 @@ The system matches the [action](../reference/apis/js-apis-ability-wantConstant.m ...@@ -62,12 +62,12 @@ The system matches the [action](../reference/apis/js-apis-ability-wantConstant.m
**Figure 1** Matching rules of action in the want parameter **Figure 1** Matching rules of action in the want parameter
![want-action](figures/want-action.png) ![want-action](figures/want-action.png)
### Matching Rules of entities in the want Parameter ### Matching Rules of entities in the want Parameter
The system matches the [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) attribute in the **want** parameter passed by the caller against **entities** under **skills** of the abilities. The system matches the **entities** attribute in the **want** parameter passed by the caller against **entities** under **skills** of the abilities.
- If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an ability is specified, the matching is successful. - If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an ability is specified, the matching is successful.
...@@ -117,7 +117,7 @@ To simplify the description, **uri** and **type** passed in the **want** paramet ...@@ -117,7 +117,7 @@ To simplify the description, **uri** and **type** passed in the **want** paramet
Figure 4 Matching rules of uri and type in the want parameter Figure 4 Matching rules of uri and type in the want parameter
![want-uri-type2](figures/want-uri-type2.png) ![want-uri-type2](figures/want-uri-type2.png)
### Matching Rules of uri ### Matching Rules of uri
......
...@@ -93,7 +93,7 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -93,7 +93,7 @@ On device A, touch the **Start** button provided by the initiator application to
} }
``` ```
4. Set the target component parameters, and call **startAbility()** to start UIAbility or ServiceExtensionAbility. 4. Set the target component parameters, and call [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start UIAbility or ServiceExtensionAbility.
```ts ```ts
let want = { let want = {
...@@ -382,68 +382,68 @@ The following describes how to implement multi-device collaboration through cros ...@@ -382,68 +382,68 @@ The following describes how to implement multi-device collaboration through cros
```ts ```ts
export default class MySequenceable { export default class MySequenceable {
num: number = 0 num: number = 0;
str: string = "" str: string = "";
constructor(num, string) { constructor(num, string) {
this.num = num this.num = num;
this.str = string this.str = string;
} }
marshalling(messageParcel) { marshalling(messageParcel) {
messageParcel.writeInt(this.num) messageParcel.writeInt(this.num);
messageParcel.writeString(this.str) messageParcel.writeString(this.str);
return true return true;
} }
unmarshalling(messageParcel) { unmarshalling(messageParcel) {
this.num = messageParcel.readInt() this.num = messageParcel.readInt();
this.str = messageParcel.readString() this.str = messageParcel.readString();
return true return true;
} }
} }
``` ```
4. Implement **Callee.on** and **Callee.off**. 4. Implement **Callee.on** and **Callee.off**.
In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements.
```ts ```ts
const TAG: string = '[CalleeAbility]' const TAG: string = '[CalleeAbility]';
const MSG_SEND_METHOD: string = 'CallSendMsg' const MSG_SEND_METHOD: string = 'CallSendMsg';
function sendMsgCallback(data) { function sendMsgCallback(data) {
console.info('CalleeSortFunc called') console.info('CalleeSortFunc called');
// Obtain the sequenceable data sent by the caller ability. // Obtain the sequenceable data sent by the caller ability.
let receivedData = new MySequenceable(0, '') let receivedData = new MySequenceable(0, '');
data.readSequenceable(receivedData) data.readSequenceable(receivedData);
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`) console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`);
// Process the data. // Process the data.
// Return the sequenceable data result to the caller ability. // Return the sequenceable data result to the caller ability.
return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`) return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`);
} }
export default class CalleeAbility extends Ability { export default class CalleeAbility extends Ability {
onCreate(want, launchParam) { onCreate(want, launchParam) {
try { try {
this.callee.on(MSG_SEND_METHOD, sendMsgCallback) this.callee.on(MSG_SEND_METHOD, sendMsgCallback);
} catch (error) { } catch (error) {
console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`);
} }
} }
onDestroy() { onDestroy() {
try { try {
this.callee.off(MSG_SEND_METHOD) this.callee.off(MSG_SEND_METHOD);
} catch (error) { } catch (error) {
console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`) console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`);
} }
} }
} }
``` ```
4. Obtain the caller object and access the callee ability. 4. Obtain the caller object and access the callee ability.
1. Import the **UIAbility** module. 1. Import the **UIAbility** module.
...@@ -458,8 +458,8 @@ The following describes how to implement multi-device collaboration through cros ...@@ -458,8 +458,8 @@ The following describes how to implement multi-device collaboration through cros
```ts ```ts
async onButtonGetRemoteCaller() { async onButtonGetRemoteCaller() {
var caller = undefined var caller = undefined;
var context = this.context var context = this.context;
context.startAbilityByCall({ context.startAbilityByCall({
deviceId: getRemoteDeviceId(), deviceId: getRemoteDeviceId(),
...@@ -467,16 +467,16 @@ The following describes how to implement multi-device collaboration through cros ...@@ -467,16 +467,16 @@ The following describes how to implement multi-device collaboration through cros
abilityName: 'CalleeAbility' abilityName: 'CalleeAbility'
}).then((data) => { }).then((data) => {
if (data != null) { if (data != null) {
caller = data caller = data;
console.info('get remote caller success') console.info('get remote caller success');
// Register the onRelease() listener of the caller ability. // Register the onRelease() listener of the caller ability.
caller.onRelease((msg) => { caller.onRelease((msg) => {
console.info(`remote caller onRelease is called ${msg}`) console.info(`remote caller onRelease is called ${msg}`);
}) })
console.info('remote caller register OnRelease succeed') console.info('remote caller register OnRelease succeed');
} }
}).catch((error) => { }).catch((error) => {
console.error(`get remote caller failed with ${error}`) console.error(`get remote caller failed with ${error}`);
}) })
} }
``` ```
......
...@@ -10,7 +10,7 @@ The following describes how the mission list manager manages the UIAbility insta ...@@ -10,7 +10,7 @@ The following describes how the mission list manager manages the UIAbility insta
**Figure 1** Missions and singleton mode **Figure 1** Missions and singleton mode
![mission-and-singleton](figures/mission-and-singleton.png) ![mission-and-singleton](figures/mission-and-singleton.png)
- **standard**: Each time **startAbility()** is called, a UIAbility instance is created in the application process. - **standard**: Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, a **UIAbility** instance is created in the application process.
**Figure 2** Missions and standard mode **Figure 2** Missions and standard mode
![mission-and-standard](figures/mission-and-standard.png) ![mission-and-standard](figures/mission-and-standard.png)
...@@ -30,4 +30,3 @@ Every mission retains a snapshot of the UIAbility instance. After the UIAbility ...@@ -30,4 +30,3 @@ Every mission retains a snapshot of the UIAbility instance. After the UIAbility
> **NOTE** > **NOTE**
> >
> The **specified** mode is supported in the stage model only. > The **specified** mode is supported in the stage model only.
...@@ -28,7 +28,7 @@ Missions are managed by system applications (such as home screen), rather than t ...@@ -28,7 +28,7 @@ Missions are managed by system applications (such as home screen), rather than t
- Switch a mission to the foreground. - Switch a mission to the foreground.
A UIAbility instance corresponds to an independent mission. Therefore, when an application calls the **startAbility()** method to start a UIAbility, a mission is created. A UIAbility instance corresponds to an independent mission. Therefore, when an application calls [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start a UIAbility, a mission is created.
To call [missionManager](../reference/apis/js-apis-application-missionManager.md) to manage missions, the home screen application must request the **ohos.permission.MANAGE_MISSIONS** permission. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). To call [missionManager](../reference/apis/js-apis-application-missionManager.md) to manage missions, the home screen application must request the **ohos.permission.MANAGE_MISSIONS** permission. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
...@@ -36,6 +36,8 @@ To call [missionManager](../reference/apis/js-apis-application-missionManager.md ...@@ -36,6 +36,8 @@ To call [missionManager](../reference/apis/js-apis-application-missionManager.md
You can use **missionManager** to manage missions, for example, listening for mission changes, obtaining mission information or snapshots, and clearing, locking, or unlocking missions. The sample code is as follows: You can use **missionManager** to manage missions, for example, listening for mission changes, obtaining mission information or snapshots, and clearing, locking, or unlocking missions. The sample code is as follows:
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager' import missionManager from '@ohos.app.ability.missionManager'
......
# ServiceExtensionAbility # ServiceExtensionAbility
[ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) is an ExtensionAbility component of the service type that provides extension capabilities related to background services. [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) is an ExtensionAbility component of the service type that provides extension capabilities related to background services.
...@@ -40,28 +41,24 @@ This feature applies only to system applications. [ServiceExtensionAbility](../r ...@@ -40,28 +41,24 @@ This feature applies only to system applications. [ServiceExtensionAbility](../r
![ServiceExtensionAbility-lifecycle](figures/ServiceExtensionAbility-lifecycle.png) ![ServiceExtensionAbility-lifecycle](figures/ServiceExtensionAbility-lifecycle.png)
- **onCreate** - **onCreate**
This callback is triggered when a service is created for the first time. You can perform initialization operations, for example, registering a common event listener. This callback is triggered when a service is created for the first time. You can perform initialization operations, for example, registering a common event listener.
> **NOTE** > **NOTE**
> >
> If a service has been created, starting it again does not trigger the **onCreate()** callback. > If a service has been created, starting it again does not trigger the **onCreate()** callback.
- **onRequest** - **onRequest**
This callback is triggered when another component calls the **startServiceExtensionAbility()** method to start the service. After being started, the service runs in the background. This callback is triggered when another component calls the **startServiceExtensionAbility()** method to start the service. After being started, the service runs in the background.
- **onConnect** - **onConnect**
This callback is triggered when another component calls the **connectServiceExtensionAbility()** method to connect to the service. In this method, a remote proxy object (IRemoteObject) is returned, through which the client communicates with the server by means of RPC. This callback is triggered when another component calls the **connectServiceExtensionAbility()** method to connect to the service. In this method, a remote proxy object (IRemoteObject) is returned, through which the client communicates with the server by means of RPC.
- **onDisconnect** - **onDisconnect**
This callback is triggered when a component calls the **disconnectServiceExtensionAbility()** method to disconnect from the service. This callback is triggered when a component calls the **disconnectServiceExtensionAbility()** method to disconnect from the service.
- **onDestroy** - **onDestroy**
......
...@@ -27,7 +27,7 @@ async function startServiceAbility() { ...@@ -27,7 +27,7 @@ async function startServiceAbility() {
``` ```
In the preceding code, **startAbility()** is used to start the ServiceAbility. In the preceding code, [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is used to start the ServiceAbility.
- If the ServiceAbility is not running, the system calls **onStart()** to initialize the ServiceAbility, and then calls **onCommand()** on the ServiceAbility. - If the ServiceAbility is not running, the system calls **onStart()** to initialize the ServiceAbility, and then calls **onCommand()** on the ServiceAbility.
......
# StaticSubscriberExtensionAbility Development
## Scenario Description
​The common event service provides two subscription modes: dynamic and static. In dynamic subscription mode, a subscriber calls an API during the running period to subscribe to common events. For details, see [Subscribing to Common Events](common-event-subscription.md). In static subscription mode, no common event subscription API is called. A common event is subscribed by configuring a declaration file and implementing a class that inherits from **StaticSubscriberExtensionAbility**. A static subscriber is started once it receives a target event (for example, a power-on event) published by the system or application. At the same time, the **onReceiveEvent** callback is triggered, in which you can implement the service logic. **The static subscriber APIs are system APIs and can be used only by system applications that have passed the system-level power consumption review.**
## How to Develop
1. Prerequisites
The application must meet the following requirements:
The application is a system application.
The application is developed using the full SDK.
The application's power consumption has passed the system-level power consumption review. If you want to use static subscription in the debugging phase, add the bundle name of your application to the system configuration file **/etc/static_subscriber_config.json**.
2. Declaring a Static Subscriber
To declare a static subscriber, create an ExtensionAbility, which is derived from the **StaticSubscriberExtensionAbility** class, in the project. The sample code is as follows:
```ts
import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility'
export default class StaticSubscriber extends StaticSubscriberExtensionAbility {
onReceiveEvent(event) {
console.log('onReceiveEvent, event:' + event.event);
}
}
```
You can implement service logic in the **onReceiveEvent** callback.
3. Project Configuration for a Static Subscriber
After writing the static subscriber code, configure the subscriber in the **module.json5** file. The configuration format is as follows:
```ts
{
"module": {
......
"extensionAbilities": [
{
"name": "StaticSubscriber",
"srcEntrance": "./ets/StaticSubscriber/StaticSubscriber.ts",
"description": "$string:StaticSubscriber_desc",
"icon": "$media:icon",
"label": "$string:StaticSubscriber_label",
"type": "staticSubscriber",
"visible": true,
"metadata": [
{
"name": "ohos.extension.staticSubscriber",
"resource": "$profile:subscribe"
}
]
}
]
......
}
}
```
Pay attention to the following fields in the JSON file:
**srcEntrance**: entry file path of the ExtensionAbility, that is, the file path of the static subscriber declared in Step 2.
**type**: ExtensionAbility type. For a static subscriber, set this field to **staticSubscriber**.
**metadata**: level-2 configuration file information of the ExtensionAbility. The configuration information varies according to the ExtensionAbility type. Therefore, you must use different config files to indicate the specific configuration. The **metadata** field contains two keywords: **name** and **resource**. The **name** field indicates the ExtensionAbility type name. For a static subscriber, declare the name as **ohos.extension.staticSubscriber** for successful identification. The **resource** field indicates the path that stores the ExtensionAbility configuration, which is customizable. In this example, the path is **resources/base/profile/subscribe.json**.
A level-2 configuration file pointed to by **metadata** must be in the following format:
```ts
{
"commonEvents": [
{
"name": "xxx",
"permission": "xxx",
"events":[
"xxx"
]
}
]
}
```
If the level-2 configuration file is not declared in this format, the file cannot be identified. The fields are described as follows:
**name**: name of the ExtensionAbility, which must be the same as the name of **extensionAbility** declared in **module.json5**.
**permission**: permission required by the publisher. If a publisher without the required permission attempts to publish an event, the event is regarded as invalid and will not be published.
**events**: list of subscribed target events
## Samples
For details about how to develop StaticSubscriberExtensionAbility, see [StaticSubscriber (ArkTS, API version 9, Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/StaticSubscriber).
...@@ -3,17 +3,16 @@ ...@@ -3,17 +3,16 @@
Based on the OpenHarmony application model, you can use any of the following ways to implement data synchronization between the UIAbility component and UI: Based on the OpenHarmony application model, you can use any of the following ways to implement data synchronization between the UIAbility component and UI:
- EventHub: The [base class Context](application-context-stage.md) provides the EventHub capability. It is implemented based on the publish/subscribe (pub/sub) pattern. Your application subscribes to an event and when the event occurs, receives a notification. - [Using EventHub for Data Synchronization](#using-eventhub-for-data-synchronization): The **EventHub** object is provided by the base class **Context**. Events are transferred using the publish/subscribe (pub/sub) pattern. Specifically, after subscribing to an event, your application will receive the event and process it accordingly when the event is published.
- [Using globalThis for Data Synchronization](#using-globalthis-for-data-synchronization): **globalThis** is a global object inside the ArkTS engine instance and can be accessed by components such as UIAbility, ExtensionAbility, and Page.
- globalThis: It is a global object accessible in the ArkTS engine instance. - [Using AppStorage or LocalStorage for Data Synchronization](#using-appstorage-or-localstorage-for-data-synchronization): ArkUI provides two application-level state management solutions: AppStorage and LocalStorage, which implement application- and UIAbility-level data synchronization, respectively.
- LocalStorage/AppStorage: See [State Management of Application-Level Variables](../quick-start/arkts-state-mgmt-application-level.md).
## Using EventHub for Data Synchronization ## Using EventHub for Data Synchronization
[EventHub](../reference/apis/js-apis-inner-application-eventHub.md) provides an event mechanism at the UIAbility or ExtensionAbility component level. Centered on the UIAbility or ExtensionAbility component, EventHub provides data communication capabilities for subscribing to, unsubscribing from, and triggering events. [EventHub](../reference/apis/js-apis-inner-application-eventHub.md) provides an event mechanism for the UIAbility or ExtensionAbility component so that they can subscribe to, unsubscribe from, and trigger events.
Before using EventHub, you must obtain an EventHub object, which is provided by the [base class Context](application-context-stage.md). This section uses EventHub as an example to describe how to implement data synchronization between the UIAbility component and the UI. Before using the APIs provided by **EventHub**, you must obtain an **EventHub** object, which is provided by the [base class Context](application-context-stage.md). This section uses EventHub as an example to describe how to implement data synchronization between the UIAbility component and the UI.
1. Call [eventHub.on()](../reference/apis/js-apis-inner-application-eventHub.md#eventhubon) in the UIAbility in either of the following ways to register a custom event **event1**. 1. Call [eventHub.on()](../reference/apis/js-apis-inner-application-eventHub.md#eventhubon) in the UIAbility in either of the following ways to register a custom event **event1**.
...@@ -81,17 +80,16 @@ Before using EventHub, you must obtain an EventHub object, which is provided by ...@@ -81,17 +80,16 @@ Before using EventHub, you must obtain an EventHub object, which is provided by
4. After **event1** is used, you can call [eventHub.off()](../reference/apis/js-apis-inner-application-eventHub.md#eventhuboff) to unsubscribe from the event. 4. After **event1** is used, you can call [eventHub.off()](../reference/apis/js-apis-inner-application-eventHub.md#eventhuboff) to unsubscribe from the event.
```ts ```ts
// context is the ability context of the UIAbility instance. // context is the ability-level context of the UIAbility instance.
this.context.eventHub.off('event1'); this.context.eventHub.off('event1');
``` ```
## Using globalThis for Data Synchronization ## Using globalThis for Data Synchronization
**globalThis** is a global object inside the [ArkTS engine instance](thread-model-stage.md) and can be used by UIAbility, ExtensionAbility, and Page inside the engine. Therefore, you can use **globalThis** for data synchronization. **globalThis** is a global object inside the [ArkTS engine instance](thread-model-stage.md) and can be used by UIAbility, ExtensionAbility, and Page inside the engine. Therefore, you can use **globalThis** for data synchronization.
**Figure 1** Using globalThis for data synchronization **Figure 1** Using globalThis for data synchronization
![globalThis1](figures/globalThis1.png) ![globalThis1](figures/globalThis1.png)
...@@ -99,18 +97,18 @@ Before using EventHub, you must obtain an EventHub object, which is provided by ...@@ -99,18 +97,18 @@ Before using EventHub, you must obtain an EventHub object, which is provided by
The following describes how to use **globalThis** in three scenarios. Precautions are provided as well. The following describes how to use **globalThis** in three scenarios. Precautions are provided as well.
- [Using globalThis Between UIAbility and Page](#using-globalthis-between-uiability-and-page) - [Using globalThis Between UIAbility and Page](#using-globalthis-between-uiability-and-page)
- [Using globalThis Between UIAbility and UIAbility](##using-globalthis-between-uiability-and-uiability) - [Using globalThis Between UIAbility and UIAbility](#using-globalthis-between-uiability-and-uiability)
- [Use globalThis Between UIAbility and ExtensionAbility](#using-globalthis-between-uiability-and-extensionability) - [Use globalThis Between UIAbility and ExtensionAbility](#using-globalthis-between-uiability-and-extensionability)
- [Precautions for Using globalThis](#precautions-for-using-globalthis) - [Precautions for Using globalThis](#precautions-for-using-globalthis)
### Using globalThis Between UIAbility and Page ### Using globalThis Between UIAbility and Page
You can use **globalThis** to bind attributes or methods to implement data synchronization between the UIAbility component and UI. For example, if you bind the **want** parameter in the UIAbility component, you can use the **want** parameter information on the UI corresponding to the UIAbility component. By binding attributes or methods to **globalThis**, you can implement data synchronization between the UIAbility component and UI. For example, if you bind the **want** parameter in the UIAbility component, you can use the **want** parameter information on the UI corresponding to the UIAbility component.
1. When **startAbility()** is called to start a UIAbility instance, the **onCreate()** callback is invoked, and the **want** parameter can be passed in the callback. Therefore, you can bind the **want** parameter to **globalThis**. 1. When [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called to start a UIAbility instance, the **onCreate()** callback is invoked, and the **want** parameter can be passed in the callback. Therefore, you can bind the **want** parameter to **globalThis**.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate(want, launch) { onCreate(want, launch) {
...@@ -144,29 +142,29 @@ You can use **globalThis** to bind attributes or methods to implement data synch ...@@ -144,29 +142,29 @@ You can use **globalThis** to bind attributes or methods to implement data synch
### Using globalThis Between UIAbility and UIAbility ### Using globalThis Between UIAbility and UIAbility
To implement data synchronization between two UIAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in AbilityA and obtain the data from AbilityB. To implement data synchronization between two UIAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in UIAbilityA and obtain the data from UIAbilityB.
1. AbilityA stores a string and binds it to globalThis. 1. UIAbilityA stores a string and binds it to globalThis.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
export default class AbilityA extends UIAbility { export default class UIAbilityA extends UIAbility {
onCreate(want, launch) { onCreate(want, launch) {
globalThis.entryAbilityStr = 'AbilityA'; // AbilityA stores the string "AbilityA" to globalThis. globalThis.entryAbilityStr = 'UIAbilityA'; // UIAbilityA stores the string "UIAbilityA" to globalThis.
// ... // ...
} }
} }
``` ```
2. Obtain the data from AbilityB. 2. Obtain the data from UIAbilityB.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
export default class AbilityB extends UIAbility { export default class UIAbilityB extends UIAbility {
onCreate(want, launch) { onCreate(want, launch) {
// AbilityB reads the name from globalThis and outputs it. // UIAbilityB reads name from globalThis and outputs it.
console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr); console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr);
// ... // ...
} }
...@@ -176,17 +174,17 @@ To implement data synchronization between two UIAbility components in the same a ...@@ -176,17 +174,17 @@ To implement data synchronization between two UIAbility components in the same a
### Using globalThis Between UIAbility and ExtensionAbility ### Using globalThis Between UIAbility and ExtensionAbility
To implement data synchronization between the UIAbility and ExtensionAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in AbilityA and obtain the data from ServiceExtensionAbility. To implement data synchronization between the UIAbility and ExtensionAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in UIAbilityA and obtain the data from ServiceExtensionAbility.
1. AbilityA stores a string and binds it to globalThis. 1. UIAbilityA stores a string and binds it to globalThis.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
export default class AbilityA extends UIAbility { export default class UIAbilityA extends UIAbility {
onCreate(want, launch) { onCreate(want, launch) {
// AbilityA stores the string "AbilityA" to globalThis. // UIAbilityA stores the string "UIAbilityA" to globalThis.
globalThis.entryAbilityStr = 'AbilityA'; globalThis.entryAbilityStr = 'UIAbilityA';
// ... // ...
} }
} }
...@@ -209,11 +207,11 @@ To implement data synchronization between the UIAbility and ExtensionAbility com ...@@ -209,11 +207,11 @@ To implement data synchronization between the UIAbility and ExtensionAbility com
### Precautions for Using globalThis ### Precautions for Using globalThis
**Figure 2** Precautions for globalThis **Figure 2** Precautions for globalThis
![globalThis2](figures/globalThis2.png) ![globalThis2](figures/globalThis2.png)
- In the stage model, all the UIAbility components in a process share one ArkTS engine instance. When using **globalThis**, do not store objects with the same name. For example, if AbilityA and AbilityB use **globalThis** to store two objects with the same name, the object stored earlier will be overwritten. - In the stage model, all the UIAbility components in a process share one ArkTS engine instance. When using **globalThis**, do not store objects with the same name. For example, if UIAbilityA and UIAbilityB use **globalThis** to store two objects with the same name, the object stored earlier will be overwritten.
- This problem does not occur in the FA model because each UIAbility component uses an independent engine. - This problem does not occur in the FA model because each UIAbility component uses an independent engine.
...@@ -221,20 +219,20 @@ To implement data synchronization between the UIAbility and ExtensionAbility com ...@@ -221,20 +219,20 @@ To implement data synchronization between the UIAbility and ExtensionAbility com
The following provides an example to describe the object overwritten problem in the stage model. The following provides an example to describe the object overwritten problem in the stage model.
1. In the AbilityA file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis**. 1. In the UIAbilityA file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis**.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
export default class AbilityA extends UIAbility { export default class UIAbilityA extends UIAbility {
onCreate(want, launch) { onCreate(want, launch) {
globalThis.context = this.context; // AbilityA stores the context in globalThis. globalThis.context = this.context; // UIAbilityA stores the context in globalThis.
// ... // ...
} }
} }
``` ```
2. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of Ability A. After the AbilityA instance is used, switch it to the background. 2. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of UIAbilityA. After the UIAbilityA instance is used, switch it to the background.
```ts ```ts
@Entry @Entry
...@@ -254,21 +252,21 @@ The following provides an example to describe the object overwritten problem in ...@@ -254,21 +252,21 @@ The following provides an example to describe the object overwritten problem in
} }
``` ```
3. In the AbilityB file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis** and has the same name as that in the AbilityA file. 3. In the UIAbilityB file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis** and has the same name as that in the UIAbilityA file.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
export default class AbilityB extends UIAbility { export default class UIAbilityB extends UIAbility {
onCreate(want, launch) { onCreate(want, launch) {
// AbilityB overwrites the context stored by AbilityA in globalThis. // UIAbilityB overwrites the context stored by UIAbilityA in globalThis.
globalThis.context = this.context; globalThis.context = this.context;
// ... // ...
} }
} }
``` ```
4. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of Ability B. The obtained **globalThis.context** is the value of [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) in AbilityB. 4. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of UIAbilityB. The obtained **globalThis.context** is the value of [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) in UIAbilityB.
```ts ```ts
@Entry @Entry
...@@ -288,27 +286,27 @@ The following provides an example to describe the object overwritten problem in ...@@ -288,27 +286,27 @@ The following provides an example to describe the object overwritten problem in
} }
``` ```
5. Switch the AbilityB instance to the background and switch the AbilityA instance to the foreground. In this case, AbilityA will not enter the **onCreate()** lifecycle again. 5. Switch the UIAbilityB instance to the background and switch the UIAbilityA instance to the foreground. In this case, UIAbilityA will not enter the **onCreate()** lifecycle again.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
export default class AbilityA extends UIAbility { export default class UIAbilityA extends UIAbility {
onCreate(want, launch) { // AbilityA will not enter this lifecycle. onCreate(want, launch) { // UIAbilityA will not enter this lifecycle.
globalThis.context = this.context; globalThis.context = this.context;
// ... // ...
} }
} }
``` ```
6. When the page of AbilityA is displayed, the obtained **globalThis.context** is [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) of AbilityB instead of AbilityA. An error occurs. 6. When the page of UIAbilityA is displayed, the obtained **globalThis.context** is [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) of UIAbilityB instead of UIAbilityA. An error occurs.
```ts ```ts
@Entry @Entry
@Component @Component
struct Index { struct Index {
onPageShow() { onPageShow() {
let ctx = globalThis.context; // The context in globalThis is the context of AbilityB. let ctx = globalThis.context; // The context in globalThis is the context of UIAbilityB.
let permissions=['com.example.permission']; let permissions=['com.example.permission'];
ctx.requestPermissionsFromUser(permissions,(result) => { // Using this object causes a process breakdown. ctx.requestPermissionsFromUser(permissions,(result) => { // Using this object causes a process breakdown.
console.info('requestPermissionsFromUser result:' + JSON.stringify(result)); console.info('requestPermissionsFromUser result:' + JSON.stringify(result));
...@@ -320,3 +318,7 @@ The following provides an example to describe the object overwritten problem in ...@@ -320,3 +318,7 @@ The following provides an example to describe the object overwritten problem in
} }
} }
``` ```
## Using AppStorage or LocalStorage for Data Synchronization
ArkUI provides AppStorage and LocalStorage to implement application- and UIAbility-level data synchronization, respectively. Both solutions can be used to manage the application state, enhance application performance, and improve user experience. The AppStorage is a global state manager and is applicable when multiple UIAbilities share the same state data. The LocalStorage is a local state manager that manages state data used inside a single UIAbility. They help you control the application state more flexibly and improve the maintainability and scalability of applications. For details, see [State Management of Application-Level Variables](../quick-start/arkts-state-mgmt-application-level.md).
...@@ -26,7 +26,7 @@ This scenario is possible when an application contains multiple UIAbility compon ...@@ -26,7 +26,7 @@ This scenario is possible when an application contains multiple UIAbility compon
Assume that your application has two UIAbility components: EntryAbility and FuncAbility, either in the same module or different modules. You are required to start FuncAbility from EntryAbility. Assume that your application has two UIAbility components: EntryAbility and FuncAbility, either in the same module or different modules. You are required to start FuncAbility from EntryAbility.
1. In EntryAbility, call **startAbility()** to start UIAbility. The [want](../reference/apis/js-apis-app-ability-want.md) parameter is the entry parameter for starting the UIAbility instance. In the **want** parameter, **bundleName** indicates the bundle name of the application to start; **abilityName** indicates the name of the UIAbility to start; **moduleName** is required only when the target UIAbility belongs to a different module; **parameters** is used to carry custom information. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). 1. In EntryAbility, call [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start UIAbility. The [want](../reference/apis/js-apis-app-ability-want.md) parameter is the entry parameter for starting the UIAbility instance. In the **want** parameter, **bundleName** indicates the bundle name of the application to start; **abilityName** indicates the name of the UIAbility to start; **moduleName** is required only when the target UIAbility belongs to a different module; **parameters** is used to carry custom information. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
```ts ```ts
let wantInfo = { let wantInfo = {
...@@ -62,21 +62,27 @@ Assume that your application has two UIAbility components: EntryAbility and Func ...@@ -62,21 +62,27 @@ Assume that your application has two UIAbility components: EntryAbility and Func
} }
``` ```
3. To stop the **UIAbility** instance after the FuncAbility service is complete, call **terminateSelf()** in FuncAbility. 3. To stop the **UIAbility** instance after the FuncAbility service is complete, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) in FuncAbility.
```ts ```ts
// context is the ability context of the UIAbility instance to stop. // context is the ability-level context of the UIAbility instance to stop.
this.context.terminateSelf((err) => { this.context.terminateSelf((err) => {
// ... // ...
}); });
``` ```
> **NOTE**
>
> When [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) is called to stop the **UIAbility** instance, the snapshot of the instance is retained by default. That is, the mission corresponding to the instance is still displayed in Recents. If you do not want to retain the snapshot, set **removeMissionAfterTerminate** under the [abilities](../quick-start/module-configuration-file.md#abilities) tag to **true** in the [module.json5 file](../quick-start/module-configuration-file.md) of the corresponding UIAbility.
4. To stop all UIAbility instances of the application, call [killProcessBySelf()](../reference/apis/js-apis-inner-application-applicationContext.md#applicationcontextkillallprocesses9) of [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md) to stop all processes of the application.
## Starting UIAbility in the Same Application and Obtaining the Return Result ## Starting UIAbility in the Same Application and Obtaining the Return Result
When starting FuncAbility from EntryAbility, you want the result to be returned after the FuncAbility service is finished. For example, your application uses two independent UIAbility components to carry the entry and sign-in functionalities. After the sign-in operation is finished in the sign-in UIAbility, the sign-in result needs to be returned to the entry UIAbility. When starting FuncAbility from EntryAbility, you want the result to be returned after the FuncAbility service is finished. For example, your application uses two independent UIAbility components to carry the entry and sign-in functionalities. After the sign-in operation is finished in the sign-in UIAbility, the sign-in result needs to be returned to the entry UIAbility.
1. In EntryAbility, call **startAbilityForResult()** to start FuncAbility. Use **data** in the asynchronous callback to receive information returned after FuncAbility stops itself. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). 1. In EntryAbility, call [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to start FuncAbility. Use **data** in the asynchronous callback to receive information returned after FuncAbility stops itself. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
```ts ```ts
let wantInfo = { let wantInfo = {
...@@ -96,7 +102,7 @@ When starting FuncAbility from EntryAbility, you want the result to be returned ...@@ -96,7 +102,7 @@ When starting FuncAbility from EntryAbility, you want the result to be returned
}) })
``` ```
2. Call **terminateSelfWithResult()** to stop FuncAbility. Use the input parameter **abilityResult** to carry the information that FuncAbility needs to return to EntryAbility. 2. Call [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to stop FuncAbility. Use the input parameter **abilityResult** to carry the information that FuncAbility needs to return to EntryAbility.
```ts ```ts
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
...@@ -111,13 +117,13 @@ When starting FuncAbility from EntryAbility, you want the result to be returned ...@@ -111,13 +117,13 @@ When starting FuncAbility from EntryAbility, you want the result to be returned
}, },
}, },
} }
// context is the ability context of the callee UIAbility. // context is the ability-level context of the callee UIAbility.
this.context.terminateSelfWithResult(abilityResult, (err) => { this.context.terminateSelfWithResult(abilityResult, (err) => {
// ... // ...
}); });
``` ```
3. After FuncAbility stops itself, EntryAbility uses the **startAbilityForResult()** method to receive the information returned by FuncAbility. The value of **RESULT_CODE** must be the same as the preceding value. 3. After FuncAbility stops itself, EntryAbility uses [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to receive the information returned by FuncAbility. The value of **RESULT_CODE** must be the same as the preceding value.
```ts ```ts
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
...@@ -145,11 +151,11 @@ There are two ways to start **UIAbility**: [explicit and implicit](want-overview ...@@ -145,11 +151,11 @@ There are two ways to start **UIAbility**: [explicit and implicit](want-overview
- Explicit Want launch: This mode is used to start a determined UIAbility component of an application. You need to set **bundleName** and **abilityName** of the target application in the **want** parameter. - Explicit Want launch: This mode is used to start a determined UIAbility component of an application. You need to set **bundleName** and **abilityName** of the target application in the **want** parameter.
- Implicit Want launch: The user selects a UIAbility to start based on the matching conditions. That is, the UIAbility to start is not determined (the **abilityName** parameter is not specified). When the **startAbility()** method is called, the **want** parameter specifies a series of parameters such as [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) and [actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction). **entities** provides additional type information of the target UIAbility, such as the browser or video player. **actions** specifies the common operations to perform, such as viewing, sharing, and application details. Then the system analyzes the **want** parameter to find the right UIAbility to start. You usually do not know whether the target application is installed and what **bundleName** and **abilityName** of the target application are. Therefore, implicit Want launch is usually used to start the UIAbility of another application. - Implicit Want launch: The user selects a UIAbility to start based on the matching conditions. That is, the UIAbility to start is not determined (the **abilityName** parameter is not specified). When [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, the want parameter specifies a series of parameters such as **entities** and **actions**. **entities** provides category information of the target UIAbility, such as the browser or video player. **actions** specifies the common operations to perform, such as viewing, sharing, and application details. Then the system analyzes the **want** parameter to find the right UIAbility to start. You usually do not know whether the target application is installed and what **bundleName** and **abilityName** of the target application are. Therefore, implicit Want launch is usually used to start the UIAbility of another application.
This section describes how to start the UIAbility of another application through implicit Want. This section describes how to start the UIAbility of another application through implicit Want.
1. Install multiple document applications on your device. In the **module.json5** file of each UIAbility component, configure [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) and [actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) under **skills**. 1. Install multiple document applications on your device. In the [module.json5 file](../quick-start/module-configuration-file.md) of each UIAbility component, configure **entities** and **actions** under **skills**.
```json ```json
{ {
...@@ -196,13 +202,13 @@ This section describes how to start the UIAbility of another application through ...@@ -196,13 +202,13 @@ This section describes how to start the UIAbility of another application through
``` ```
The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select. The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select.
![uiability-intra-device-interaction](figures/uiability-intra-device-interaction.png) ![uiability-intra-device-interaction](figures/uiability-intra-device-interaction.png)
3. To stop the **UIAbility** instance after the document application is used, call **terminateSelf()**. 3. To stop the **UIAbility** instance after the document application is used, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself).
```ts ```ts
// context is the ability context of the UIAbility instance to stop. // context is the ability-level context of the UIAbility instance to stop.
this.context.terminateSelf((err) => { this.context.terminateSelf((err) => {
// ... // ...
}); });
...@@ -211,9 +217,9 @@ This section describes how to start the UIAbility of another application through ...@@ -211,9 +217,9 @@ This section describes how to start the UIAbility of another application through
## Starting UIAbility of Another Application and Obtaining the Return Result ## Starting UIAbility of Another Application and Obtaining the Return Result
If you want to obtain the return result when using implicit Want to start the UIAbility of another application, use the **startAbilityForResult()** method. An example scenario is that the main application needs to start a third-party payment application and obtain the payment result. If you want to obtain the return result when using implicit Want to start the UIAbility of another application, use [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult). An example scenario is that the main application needs to start a third-party payment application and obtain the payment result.
1. In the **module.json5** file of the UIAbility corresponding to the payment application, set [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) and [actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) under **skills**. 1. In the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility corresponding to the payment application, set **entities** and **actions** under **skills**.
```json ```json
{ {
...@@ -239,7 +245,7 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -239,7 +245,7 @@ If you want to obtain the return result when using implicit Want to start the UI
} }
``` ```
2. Call the **startAbilityForResult()** method to start the UIAbility of the payment application. Include **entities** and **actions** of the caller's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. Use **data** in the asynchronous callback to receive the information returned to the caller after the payment UIAbility stops itself. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select. 2. Call [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to start the UIAbility of the payment application. Include **entities** and **actions** of the caller's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. Use **data** in the asynchronous callback to receive the information returned to the caller after the payment UIAbility stops itself. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select.
```ts ```ts
let wantInfo = { let wantInfo = {
...@@ -259,7 +265,7 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -259,7 +265,7 @@ If you want to obtain the return result when using implicit Want to start the UI
}) })
``` ```
3. After the payment is finished, call the **terminateSelfWithResult()** method to stop the payment UIAbility and return the **abilityResult** parameter. 3. After the payment is finished, call [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to stop the payment UIAbility and return the **abilityResult** parameter.
```ts ```ts
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
...@@ -274,13 +280,13 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -274,13 +280,13 @@ If you want to obtain the return result when using implicit Want to start the UI
}, },
}, },
} }
// context is the ability context of the callee UIAbility. // context is the ability-level context of the callee UIAbility.
this.context.terminateSelfWithResult(abilityResult, (err) => { this.context.terminateSelfWithResult(abilityResult, (err) => {
// ... // ...
}); });
``` ```
4. Receive the information returned by the payment application in the callback of the **startAbilityForResult()** method. The value of **RESULT_CODE** must be the same as that returned by **terminateSelfWithResult()**. 4. Receive the information returned by the payment application in the callback of the [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) method. The value of **RESULT_CODE** must be the same as that returned by [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult).
```ts ```ts
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
...@@ -443,7 +449,7 @@ Ability call is usually used in the following scenarios: ...@@ -443,7 +449,7 @@ Ability call is usually used in the following scenarios:
The following figure shows the ability call process. The following figure shows the ability call process.
**Figure 1** Ability call process Figure 1 Ability call process
![call](figures/call.png) ![call](figures/call.png)
...@@ -490,24 +496,23 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -490,24 +496,23 @@ For the callee ability, implement the callback to receive data and the methods t
Set **launchType** of the callee ability to **singleton** in the **module.json5** file. Set **launchType** of the callee ability to **singleton** in the **module.json5** file.
| JSON Field| Description| | JSON Field| Description|
| -------- | -------- | | -------- | -------- |
| "launchType" | Ability launch type. Set this parameter to **singleton**.| | "launchType" | Ability launch type. Set this parameter to **singleton**.|
An example of the ability configuration is as follows: An example of the ability configuration is as follows:
```json
```json "abilities":[{
"abilities":[{ "name": ".CalleeAbility",
"name": ".CalleeAbility", "srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts",
"srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts", "launchType": "singleton",
"launchType": "singleton", "description": "$string:CalleeAbility_desc",
"description": "$string:CalleeAbility_desc", "icon": "$media:icon",
"icon": "$media:icon", "label": "$string:CalleeAbility_label",
"label": "$string:CalleeAbility_label", "visible": true
"visible": true }]
}] ```
```
2. Import the **UIAbility** module. 2. Import the **UIAbility** module.
...@@ -519,7 +524,6 @@ An example of the ability configuration is as follows: ...@@ -519,7 +524,6 @@ An example of the ability configuration is as follows:
The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string. The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string.
```ts ```ts
export default class MySequenceable { export default class MySequenceable {
num: number = 0 num: number = 0
...@@ -548,7 +552,6 @@ An example of the ability configuration is as follows: ...@@ -548,7 +552,6 @@ An example of the ability configuration is as follows:
The time to register a listener for the callee ability depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code is as follows: The time to register a listener for the callee ability depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code is as follows:
```ts ```ts
const TAG: string = '[CalleeAbility]'; const TAG: string = '[CalleeAbility]';
const MSG_SEND_METHOD: string = 'CallSendMsg'; const MSG_SEND_METHOD: string = 'CallSendMsg';
...@@ -598,7 +601,6 @@ An example of the ability configuration is as follows: ...@@ -598,7 +601,6 @@ An example of the ability configuration is as follows:
The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements. The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements.
```ts ```ts
// Register the onRelease() listener of the caller ability. // Register the onRelease() listener of the caller ability.
private regOnRelease(caller) { private regOnRelease(caller) {
......
...@@ -3,17 +3,16 @@ ...@@ -3,17 +3,16 @@
## Definition and Usage of Want ## Definition and Usage of Want
[Want](../reference/apis/js-apis-app-ability-want.md) is used as the carrier to transfer information between application components. It is used as a parameter of **startAbility()** to specify the 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. For example, when UIAbilityA starts UIAbilityB and needs to transfer some data to UIAbilityB, it can use Want to transfer the data. [Want](../reference/apis/js-apis-app-ability-want.md) is an object that transfers information between application components. It is often used as a parameter of [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability). For example, when UIAbilityA needs to start UIAbilityB and transfer some data to UIAbilityB, it can use the **want** parameter in **startAbility()** to transfer the data.
**Figure 1** Want usage **Figure 1** Want usage
![usage-of-want](figures/usage-of-want.png)
![usage-of-want](figures/usage-of-want.png)
## Types of Want ## Types of Want
- **Explicit Want**: A type of Want with **abilityName** and **bundleName** specified when starting an ability. - **Explicit Want**: If **abilityName** and **bundleName** are specified when starting an ability, explicit Want is used.
When there is an explicit object to process the request, the target ability can be started by specifying the bundle name and ability name in Want. Explicit Want is usually used to start a known ability. Explicit Want is usually used to start a known target ability in the same application. The target ability is started by specifying **bundleName** of the application where the target ability is located and **abilityName** in the **Want** object. When there is an explicit object to process the request, explicit Want is a simple and effective way to start the target ability.
```ts ```ts
let wantInfo = { let wantInfo = {
...@@ -23,8 +22,8 @@ ...@@ -23,8 +22,8 @@
} }
``` ```
- **Implicit Want**: A type of Want with **abilityName** unspecified when starting the ability. - **Implicit Want**: If **abilityName** is not specified when starting the ability, implicit Want is used.
Implicit Want can be used when the object used to process the request is unclear and the current application wants to use a capability (defined by the [skills tag](../quick-start/module-configuration-file.md#skills)) provided by another application. For example, you can use implicit Want to describe a request for opening a link, since you do not care which application is used to open the link. The system matches all applications that support the request. Implicit Want can be used when the object used to process the request is unclear and the current application wants to use a capability (defined by the [skills tag](../quick-start/module-configuration-file.md#skills)) provided by another application. The system matches all applications that declare to support the capability. For example, for a link open request, the system matches all applications that support the request and provides the available ones for users to select.
```ts ```ts
......
...@@ -100,7 +100,7 @@ The widget provider development based on the [stage model](stage-model-developme ...@@ -100,7 +100,7 @@ The widget provider development based on the [stage model](stage-model-developme
- [Configuring the Widget Configuration File](#configuring-the-widget-configuration-file): Configure the application configuration file **module.json5** and profile configuration file. - [Configuring the Widget Configuration File](#configuring-the-widget-configuration-file): Configure the application configuration file **module.json5** and profile configuration file.
- [Persistently Storing Widget Data](#persistently-storing-widget-data): Perform persistent management on widget information. - [Persistently Storing Widget Data](#persistently-storing-widget-data): This operation is a form of widget data exchange.
- [Updating Widget Data](#updating-widget-data): Call **updateForm()** to update the information displayed on a widget. - [Updating Widget Data](#updating-widget-data): Call **updateForm()** to update the information displayed on a widget.
...@@ -597,3 +597,13 @@ The following is an example: ...@@ -597,3 +597,13 @@ The following is an example:
}; };
``` ```
## Restrictions
To minimize the abuse of **FormExtensionAbility** by third-party applications, the following APIs cannot be invoked in **FormExtensionAbility**:
- @ohos.ability.particleAbility.d.ts
- @ohos.backgroundTaskManager.d.ts
- @ohos.resourceschedule.backgroundTaskManager.d.ts
- @ohos.multimedia.camera.d.ts
- @ohos.multimedia.audio.d.ts
- @ohos.multimedia.media.d.ts
...@@ -40,7 +40,7 @@ There are two roles in **DataShare**: ...@@ -40,7 +40,7 @@ There are two roles in **DataShare**:
- **onCreate** - **onCreate**
Called by the server to initialize service logic when the **DataShare** client connects to the **DataShareExtensionAbility** server. Called by the server to initialize service logic when the **DataShare** client connects to the **DataShareExtensionAbility** server.
- **insert** - **insert**
...@@ -64,11 +64,11 @@ There are two roles in **DataShare**: ...@@ -64,11 +64,11 @@ There are two roles in **DataShare**:
- **normalizeUri** - **normalizeUri**
Converts the URI provided by the client to the URI used by the server. This API can be overridden as required. Converts the URI provided by the client to the URI used by the server.
- **denormalizeUri** - **denormalizeUri**
Converts the URI used by the server to the initial URI passed by the client. This API can be overridden as required. Converts the URI used by the server to the initial URI passed by the client.
Before implementing a **DataShare** service, create a **DataShareExtensionAbility** object in the DevEco Studio project as follows: Before implementing a **DataShare** service, create a **DataShareExtensionAbility** object in the DevEco Studio project as follows:
...@@ -76,7 +76,7 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -76,7 +76,7 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
2. Right-click the **DataShareAbility** directory, and choose **New > TypeScript File** to create a file named **DataShareAbility.ts**. 2. Right-click the **DataShareAbility** directory, and choose **New > TypeScript File** to create a file named **DataShareAbility.ts**.
3. In the **DataShareAbility.ts** file, import the **DataShareExtensionAbility** and other dependencies. 3. In the **DataShareAbility.ts** file, import **DataShareExtensionAbility** and other dependencies.
```ts ```ts
import Extension from '@ohos.application.DataShareExtensionAbility'; import Extension from '@ohos.application.DataShareExtensionAbility';
...@@ -85,9 +85,9 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -85,9 +85,9 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
``` ```
5. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**. 4. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**.
6. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network. 5. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network.
```ts ```ts
const DB_NAME = "DB00.db"; const DB_NAME = "DB00.db";
...@@ -95,13 +95,13 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -95,13 +95,13 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
+ TBL_NAME + TBL_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)"; + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)";
let rdbStore; let rdbStore;
let result; let result;
export default class DataShareExtAbility extends Extension { export default class DataShareExtAbility extends Extension {
private rdbStore_; private rdbStore_;
// Override onCreate(). // Override onCreate().
onCreate(want, callback) { onCreate(want, callback) {
result = this.context.cacheDir + '/datashare.txt'; result = this.context.cacheDir + '/datashare.txt';
...@@ -114,12 +114,12 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -114,12 +114,12 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err)); console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err));
}); });
if (callbakc) { if (callback) {
callback(); callback();
} }
}); });
} }
// Override query(). // Override query().
query(uri, predicates, columns, callback) { query(uri, predicates, columns, callback) {
if (predicates == null || predicates == undefined) { if (predicates == null || predicates == undefined) {
...@@ -143,17 +143,18 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -143,17 +143,18 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
}; };
``` ```
7. Define **DataShareExtensionAbility** in **module.json5**. 6. Define **DataShareExtensionAbility** in **module.json5**.
| Field| Description | | Field | Description | Mandatory |
| ------------ | ------------------------------------------------------------ | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | | "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | Yes |
| "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template.| | "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template. | Yes |
| "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. | | "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. | Yes |
| "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**.| | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**. | Yes |
| "metadata" | Configuration for silent access, including the **name** and **resource** fields. <br/>The **name** field identifies the configuration, which has a fixed value of **ohos.extension.dataShare**. <br/>The **resource** field has a fixed value of **$profile:data_share_config**, which indicates that the profile name is **data_share_config.json**. | **metadata** is mandatory when the ability launch type is **singleton**. For details about the ability launch type, see **launchType** in the [Internal Structure of the abilities Attribute](../quick-start/module-structure.md#internal-structure-of-the-abilities-attribute). |
**module.json5 example** **module.json5 example**
```json ```json
"extensionAbilities": [ "extensionAbilities": [
{ {
...@@ -163,10 +164,44 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -163,10 +164,44 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
"description": "$string:description_datashareextability", "description": "$string:description_datashareextability",
"type": "dataShare", "type": "dataShare",
"uri": "datashare://com.samples.datasharetest.DataShare", "uri": "datashare://com.samples.datasharetest.DataShare",
"visible": true "visible": true,
"metadata": [{"name": "ohos.extension.dataShare", "resource": "$profile:data_share_config"}]
} }
] ]
``` ```
**data_share_config.json Description**
| Field | Description | Mandatory |
| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| "tableConfig" | Label configuration. | Yes |
| "uri" | Range for which the configuration takes effect. The URI supports the following formats in descending order by priority:<br>- **\***: indicates all databases and tables.<br>- **datashare:///{bundleName\}/{moduleName\}/{storeName\}**: specifies a database.<br>- **datashare:///{bundleName\}/{moduleName\}/{storeName\}/{tableName\}**: specifies a table.<br>If URIs of different formats are configured, only the URI with higher priority takes effect. | Yes |
| "crossUserMode" | Whether data is shared by multiple users. The value **1** means to share data between multiple users, and the value **2** means the opposite. | **crossUserMode** is mandatory when the ability launch type is **singleton**. For details about the ability launch type, see **launchType** in the [Internal Structure of the abilities Attribute](../quick-start/module-structure.md#internal-structure-of-the-abilities-attribute). |
| "writePermission" | Write permission required for silent access. | No |
| "readPermission" | Read permission required for silent access. | No |
**data_share_config.json Example**
```json
"tableConfig": [
{
"uri": "*",
"writePermission": "ohos.permission.xxx"
},
{
"uri": "datashare:///com.acts.datasharetest/entry/DB00",
"crossUserMode": 1,
"writePermission": "ohos.permission.xxx",
"readPermission": "ohos.permission.xxx"
},
{
"uri": "datashare:///com.acts.datasharetest/entry/DB00/TBL00",
"crossUserMode": 2
}
]
```
### Data Consumer Application Development ### Data Consumer Application Development
...@@ -182,7 +217,7 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -182,7 +217,7 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
```ts ```ts
// Different from the URI defined in the module.json5 file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). // Different from the URI defined in the module.json5 file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/).
let dseUri = ("datashare:///com.samples.datasharetest.DataShare"); let dseUri = ('datashare:///com.samples.datasharetest.DataShare');
``` ```
3. Create a **DataShareHelper** instance. 3. Create a **DataShareHelper** instance.
...@@ -211,18 +246,18 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -211,18 +246,18 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
let valArray = ['*']; let valArray = ['*'];
// Insert a piece of data. // Insert a piece of data.
dsHelper.insert(dseUri, valuesBucket, (err, data) => { dsHelper.insert(dseUri, valuesBucket, (err, data) => {
console.log("dsHelper insert result: " + data); console.log('dsHelper insert result: ' + data);
}); });
// Update data. // Update data.
dsHelper.update(dseUri, predicates, updateBucket, (err, data) => { dsHelper.update(dseUri, predicates, updateBucket, (err, data) => {
console.log("dsHelper update result: " + data); console.log('dsHelper update result: ' + data);
}); });
// Query data. // Query data.
dsHelper.query(dseUri, predicates, valArray, (err, data) => { dsHelper.query(dseUri, predicates, valArray, (err, data) => {
console.log("dsHelper query result: " + data); console.log('dsHelper query result: ' + data);
}); });
// Delete data. // Delete data.
dsHelper.delete(dseUri, predicates, (err, data) => { dsHelper.delete(dseUri, predicates, (err, data) => {
console.log("dsHelper delete result: " + data); console.log('dsHelper delete result: ' + data);
}); });
``` ```
...@@ -19,7 +19,7 @@ Call **createDistributedObject()** to create a distributed data object instance. ...@@ -19,7 +19,7 @@ Call **createDistributedObject()** to create a distributed data object instance.
| Bundle Name| API| Description| | Bundle Name| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>- **source**: attributes of the distributed data object to set.<br>- **DistributedObject**: returns the distributed data object created. | | ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>- **source**: attributes of the distributed data object to create.<br>- **DistributedObject**: returns the distributed data object created.|
### Generating a Session ID ### Generating a Session ID
...@@ -91,10 +91,9 @@ The following example shows how to implement distributed data object synchroniza ...@@ -91,10 +91,9 @@ The following example shows how to implement distributed data object synchroniza
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
``` ```
2. Apply for the permission. 2. Apply for the permission.
Add the permissions required (FA model) to the **config.json** file. Add the required permission (FA model) to the **config.json** file.
```json ```json
{ {
...@@ -112,18 +111,43 @@ The following example shows how to implement distributed data object synchroniza ...@@ -112,18 +111,43 @@ The following example shows how to implement distributed data object synchroniza
This permission must also be granted by the user when the application is started for the first time. This permission must also be granted by the user when the application is started for the first time.
```js ```js
// FA model
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
function grantPermission() { function grantPermission() {
console.info('grantPermission'); console.info('grantPermission');
let context = featureAbility.getContext(); let context = featureAbility.getContext();
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
console.info(`result.requestCode=${result.requestCode}`) console.info(`requestPermissionsFromUser CallBack`);
}) })
console.info('end grantPermission'); console.info('end grantPermission');
} }
grantPermission();
```
```ts
// Stage model
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
context = this.context;
}
}
function grantPermission() {
let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC'];
context.requestPermissionsFromUser(permissions).then((data) => {
console.info('success: ${data}');
}).catch((error) => {
console.error('failed: ${error}');
});
}
grantPermission(); grantPermission();
``` ```
...@@ -139,10 +163,10 @@ The following example shows how to implement distributed data object synchroniza ...@@ -139,10 +163,10 @@ The following example shows how to implement distributed data object synchroniza
}); });
let sessionId = distributedObject.genSessionId(); let sessionId = distributedObject.genSessionId();
``` ```
4. Add the distributed data object instance to a network for data synchronization. The data objects in the synchronization network include the local and remote objects. 4. Add the distributed data object instance to a network for data synchronization. The data objects in the synchronization network include the local and remote objects.
```js ```js
// Local object // Local object
let localObject = distributedObject.createDistributedObject({ let localObject = distributedObject.createDistributedObject({
name: "jack", name: "jack",
...@@ -164,7 +188,7 @@ The following example shows how to implement distributed data object synchroniza ...@@ -164,7 +188,7 @@ The following example shows how to implement distributed data object synchroniza
// After learning that the local device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18. // After learning that the local device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18.
remoteObject.setSessionId(sessionId); remoteObject.setSessionId(sessionId);
``` ```
5. Observe the data changes of the distributed data object. You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be invoked to return the data changes. 5. Observe the data changes of the distributed data object. You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be invoked to return the data changes.
```js ```js
...@@ -202,33 +226,29 @@ The following example shows how to implement distributed data object synchroniza ...@@ -202,33 +226,29 @@ The following example shows how to implement distributed data object synchroniza
localObject.parent.mother = "mom"; localObject.parent.mother = "mom";
``` ```
7. Access the distributed data object. 7. Access the distributed data object.<br>Obtain the distributed data object attributes, which are the latest data on the network.
Obtain the distributed data object attributes, which are the latest data on the network.
```js ```js
console.info("name " + localObject["name"]); console.info("name " + localObject["name"]);
``` ```
8. Unsubscribe from data changes. You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered. 8. Unsubscribe from data changes. You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered.
```js ```js
// Unregister the specified data change callback. // Unregister the specified data change callback.
localObject.off("change", changeCallback); localObject.off("change", changeCallback);
// Unregister all data change callbacks. // Unregister all data change callbacks.
localObject.off("change"); localObject.off("change");
``` ```
9. Subscribe to status changes of this distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline. 9. Subscribe to status changes of this distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline.
```js ```js
function statusCallback(sessionId, networkId, status) { function statusCallback(sessionId, networkId, status) {
this.response += "status changed " + sessionId + " " + status + " " + networkId; this.response += "status changed " + sessionId + " " + status + " " + networkId;
} }
localObject.on("status", this.statusCallback); localObject.on("status", this.statusCallback);
``` ```
10. Save a distributed data object and delete it. 10. Save a distributed data object and delete it.
```js ```js
...@@ -247,20 +267,16 @@ console.info("name " + localObject["name"]); ...@@ -247,20 +267,16 @@ console.info("name " + localObject["name"]);
console.info("revokeSave failed."); console.info("revokeSave failed.");
}); });
``` ```
11. Unsubscribe from the status changes of this distributed data object. You can specify the callback to unregister. If you do not specify the callback, this API unregisters all status change callbacks of this distributed data object.
11. Unsubscribe from the status changes of the distributed data object.
You can specify the callback to unregister. If you do not specify the callback, all status change callbacks of this distributed data object will be unregistered.
```js ```js
// Unregister the specified status change callback. // Unregister the specified status change callback.
localObject.off("status", this.statusCallback); localObject.off("status", this.statusCallback);
// Unregister all status change callbacks. // Unregister all status change callbacks.
localObject.off("status"); localObject.off("status");
``` ```
12. Remove the distributed data object from the synchronization network. The data changes on the local object will not be synchronized to the removed distributed data object. 12. Remove the distributed data object from the synchronization network. The data changes on the local object will not be synchronized to the removed distributed data object.
```js ```js
localObject.setSessionId(""); localObject.setSessionId("");
``` ```
...@@ -37,14 +37,14 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -37,14 +37,14 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
- **Updating Data** - **Updating Data**
Call **update()** to update data based on the passed data and the conditions specified by **RdbPredicates**. If the data is updated, the number of rows of the updated data will be returned; otherwise, **0** will be returned. Call **update()** to pass the new data and specify the update conditions by using **RdbPredicates**. If the data is updated, the number of rows of the updated data will be returned; otherwise, **0** will be returned.
**Table 3** API for updating data **Table 3** API for updating data
| Class | API | Description | | Class | API | Description |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStore | update(values: ValuesBucket, predicates: RdbPredicates): Promise&lt;number&gt; | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the number of rows updated.<br>- **values**: data to update, which is stored in **ValuesBucket**.<br>- **predicates**: conditions for updating data. | | RdbStore | update(values: ValuesBucket, predicates: RdbPredicates): Promise&lt;number&gt; | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the number of rows updated.<br>- **values**: data to update, which is stored in **ValuesBucket**.<br>- **predicates**: conditions for updating data.|
- **Deleting Data** - **Deleting Data**
...@@ -55,7 +55,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -55,7 +55,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
| Class | API | Description | | Class | API | Description |
| ---------- | ---------------------------------------------------------- | ------------------------------------------------------------ | | ---------- | ---------------------------------------------------------- | ------------------------------------------------------------ |
| RdbStore | delete(predicates: RdbPredicates): Promise&lt;number&gt; | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the number of rows deleted.<br>- **predicates**: conditions for deleting data. | | RdbStore | delete(predicates: RdbPredicates): Promise&lt;number&gt; | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the number of rows deleted.<br>- **predicates**: conditions for deleting data.|
- **Querying Data** - **Querying Data**
...@@ -201,76 +201,81 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -201,76 +201,81 @@ You can obtain the distributed table name for a remote device based on the local
FA model: FA model:
```js ```js
import data_rdb from '@ohos.data.relationalStore' import relationalStore from '@ohos.data.relationalStore'
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
var store;
// Obtain the context. // Obtain the context.
let context = featureAbility.getContext() let context = featureAbility.getContext();
const STORE_CONFIG = { const STORE_CONFIG = {
name: "RdbTest.db", name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1 securityLevel: relationalStore.SecurityLevel.S1
} };
// Assume that the current RDB store version is 3. // Assume that the current RDB store version is 3.
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { relationalStore.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
// When an RDB store is created, the default version is 0. store = rdbStore;
if (rdbStore.version == 0) { // When an RDB store is created, the default version is 0.
rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null) if (store.version == 0) {
// Set the RDB store version. The input parameter must be an integer greater than 0. store.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null);
rdbStore.version = 3 // Set the RDB store version. The input parameter must be an integer greater than 0.
} store.version = 3;
}
// When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2. // When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2.
if (rdbStore.version != 3 && rdbStore.version == 1) { if (store.version != 3 && store.version == 1) {
// version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score) // version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score)
rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null) store.executeSql("ALTER TABLE student ADD COLUMN score REAL", null);
rdbStore.version = 2 store.version = 2;
} }
// When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3. // When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3.
if (rdbStore.version != 3 && rdbStore.version == 2) { if (store.version != 3 && store.version == 2) {
// version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score) // version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score)
rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null) store.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null);
rdbStore.version = 3 store.version = 3;
} }
}) })
``` ```
Stage model: Stage model:
```ts ```ts
import data_rdb from '@ohos.data.relationalStore' import relationalStore from '@ohos.data.relationalStore'
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
const STORE_CONFIG = { var store;
name: "rdbstore.db", const STORE_CONFIG = {
securityLevel: data_rdb.SecurityLevel.S1 name: "RdbTest.db",
} securityLevel: relationalStore.SecurityLevel.S1
};
// Assume that the current RDB store version is 3. // Assume that the current RDB store version is 3.
data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) { relationalStore.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) {
// When an RDB store is created, the default version is 0. store = rdbStore;
if (rdbStore.version == 0) { // When an RDB store is created, the default version is 0.
rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null) if (store.version == 0) {
// Set the RDB store version. The input parameter must be an integer greater than 0. store.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null);
rdbStore.version = 3 // Set the RDB store version. The input parameter must be an integer greater than 0.
} store.version = 3;
}
// When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2. // When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2.
if (rdbStore.version != 3 && rdbStore.version == 1) { if (store.version != 3 && store.version == 1) {
// version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score) // version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score)
rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null) store.executeSql("ALTER TABLE student ADD COLUMN score REAL", null);
rdbStore.version = 2 store.version = 2;
} }
// When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3. // When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3.
if (rdbStore.version != 3 && rdbStore.version == 2) { if (store.version != 3 && store.version == 2) {
// version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score) // version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score)
rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null) store.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null);
rdbStore.version = 3 store.version = 3;
} }
}) })
} }
} }
``` ```
...@@ -284,23 +289,24 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -284,23 +289,24 @@ You can obtain the distributed table name for a remote device based on the local
The sample code is as follows: The sample code is as follows:
```js ```js
let u8 = new Uint8Array([1, 2, 3]) let u8 = new Uint8Array([1, 2, 3]);
const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 } const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 };
let insertPromise = rdbStore.insert("test", valueBucket) let insertPromise = store.insert("test", valueBucket);
``` ```
```js ```js
// Use a transaction to insert data. // Use a transaction to insert data.
beginTransaction()
try { try {
let u8 = new Uint8Array([1, 2, 3]) store.beginTransaction();
const valueBucket1 = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 } let u8 = new Uint8Array([1, 2, 3]);
const valueBucket2 = { "name": "Jam", "age": 19, "salary": 200.5, "blobType": u8 } const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 };
let insertPromise1 = rdbStore.insert("test", valueBucket1) let promise = store.insert("test", valueBucket);
let insertPromise2 = rdbStore.insert("test", valueBucket2) promise.then(() => {
commit() store.commit();
} catch (e) { })
rollBack() } catch (err) {
console.error(`Transaction failed, err: ${err}`);
store.rollBack();
} }
``` ```
...@@ -315,17 +321,17 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -315,17 +321,17 @@ You can obtain the distributed table name for a remote device based on the local
The sample code is as follows: The sample code is as follows:
```js ```js
let predicates = new data_rdb.RdbPredicates("test"); let predicates = new relationalStore.RdbPredicates("test");
predicates.equalTo("name", "Tom") predicates.equalTo("name", "Tom");
let promisequery = rdbStore.query(predicates) let promisequery = store.query(predicates);
promisequery.then((resultSet) => { promisequery.then((resultSet) => {
resultSet.goToFirstRow() resultSet.goToFirstRow();
const id = resultSet.getLong(resultSet.getColumnIndex("id")) const id = resultSet.getLong(resultSet.getColumnIndex("id"));
const name = resultSet.getString(resultSet.getColumnIndex("name")) const name = resultSet.getString(resultSet.getColumnIndex("name"));
const age = resultSet.getLong(resultSet.getColumnIndex("age")) const age = resultSet.getLong(resultSet.getColumnIndex("age"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("salary")) const salary = resultSet.getDouble(resultSet.getColumnIndex("salary"));
const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType"));
resultSet.close() resultSet.close();
}) })
``` ```
...@@ -335,9 +341,9 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -335,9 +341,9 @@ You can obtain the distributed table name for a remote device based on the local
```json ```json
"requestPermissions": "requestPermissions":
{ {
"name": "ohos.permission.DISTRIBUTED_DATASYNC" "name": "ohos.permission.DISTRIBUTED_DATASYNC"
} }
``` ```
(2) Obtain the required permissions. (2) Obtain the required permissions.
...@@ -351,13 +357,13 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -351,13 +357,13 @@ You can obtain the distributed table name for a remote device based on the local
```js ```js
let context = featureAbility.getContext(); let context = featureAbility.getContext();
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
console.info(`result.requestCode=${result.requestCode}`) console.info(`result.requestCode=${result.requestCode}`);
}) })
let promise = rdbStore.setDistributedTables(["test"]) let promise = store.setDistributedTables(["test"]);
promise.then(() => { promise.then(() => {
console.info("setDistributedTables success.") console.info(`setDistributedTables success.`);
}).catch((err) => { }).catch((err) => {
console.info("setDistributedTables failed.") console.error(`setDistributedTables failed, ${err}`);
}) })
``` ```
...@@ -372,16 +378,16 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -372,16 +378,16 @@ You can obtain the distributed table name for a remote device based on the local
The sample code is as follows: The sample code is as follows:
```js ```js
let predicate = new data_rdb.RdbPredicates('test') let predicate = new relationalStore.RdbPredicates('test');
predicate.inDevices(['12345678abcde']) predicate.inDevices(['12345678abcde']);
let promise = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicate) let promise = store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicate);
promise.then((result) => { promise.then((result) => {
console.log('sync done.') console.info(`sync done.`);
for (let i = 0; i < result.length; i++) { for (let i = 0; i < result.length; i++) {
console.log('device=' + result[i][0] + 'status=' + result[i][1]) console.info(`device=${result[i][0]}, status=${result[i][1]}`);
} }
}).catch((err) => { }).catch((err) => {
console.log('sync failed') console.error(`sync failed, err: ${err}`);
}) })
``` ```
...@@ -395,15 +401,15 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -395,15 +401,15 @@ You can obtain the distributed table name for a remote device based on the local
```js ```js
function storeObserver(devices) { function storeObserver(devices) {
for (let i = 0; i < devices.length; i++) { for (let i = 0; i < devices.length; i++) {
console.log('device=' + device[i] + 'data changed') console.info(`device= ${devices[i]} data changed`);
} }
} }
try { try {
rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) store.on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver);
} catch (err) { } catch (err) {
console.log('register observer failed') console.error(`register observer failed, err: ${err}`);
} }
``` ```
...@@ -416,8 +422,24 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -416,8 +422,24 @@ You can obtain the distributed table name for a remote device based on the local
The sample code is as follows: The sample code is as follows:
```js ```js
let tableName = rdbStore.obtainDistributedTableName(deviceId, "test"); import deviceManager from '@ohos.distributedHardware.deviceManager'
let resultSet = rdbStore.querySql("SELECT * FROM " + tableName)
let deviceIds = [];
deviceManager.createDeviceManager('bundleName', (err, value) => {
if (!err) {
let devManager = value;
if (devManager != null) {
// Obtain device IDs.
let devices = devManager.getTrustedDeviceListSync();
for (let i = 0; i < devices.length; i++) {
deviceIds[i] = devices[i].deviceId;
}
}
}
})
let tableName = store.obtainDistributedTableName(deviceIds[0], "test");
let resultSet = store.querySql("SELECT * FROM " + tableName);
``` ```
8. Query data of a remote device. 8. Query data of a remote device.
...@@ -429,19 +451,19 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -429,19 +451,19 @@ You can obtain the distributed table name for a remote device based on the local
The sample code is as follows: The sample code is as follows:
```js ```js
let rdbPredicate = new data_rdb.RdbPredicates('employee') let rdbPredicate = new relationalStore.RdbPredicates('employee');
predicates.greaterThan("id", 0) predicates.greaterThan("id", 0) ;
let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate) let promiseQuery = store.remoteQuery('12345678abcde', 'employee', rdbPredicate);
promiseQuery.then((resultSet) => { promiseQuery.then((resultSet) => {
while (resultSet.goToNextRow()) { while (resultSet.goToNextRow()) {
let idx = resultSet.getLong(0); let idx = resultSet.getLong(0);
let name = resultSet.getString(1); let name = resultSet.getString(1);
let age = resultSet.getLong(2); let age = resultSet.getLong(2);
console.info(idx + " " + name + " " + age); console.info(`indx: ${idx}, name: ${name}, age: ${age}`);
} }
resultSet.close(); resultSet.close();
}).catch((err) => { }).catch((err) => {
console.info("failed to remoteQuery, err: " + err) console.error(`failed to remoteQuery, err: ${err}`);
}) })
``` ```
...@@ -452,11 +474,11 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -452,11 +474,11 @@ You can obtain the distributed table name for a remote device based on the local
The sample code is as follows: The sample code is as follows:
```js ```js
let promiseBackup = rdbStore.backup("dbBackup.db") let promiseBackup = store.backup("dbBackup.db");
promiseBackup.then(() => { promiseBackup.then(() => {
console.info('Backup success.') console.info(`Backup success.`);
}).catch((err) => { }).catch((err) => {
console.info('Backup failed, err: ' + err) console.error(`Backup failed, err: ${err}`);
}) })
``` ```
...@@ -465,10 +487,10 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -465,10 +487,10 @@ You can obtain the distributed table name for a remote device based on the local
The sample code is as follows: The sample code is as follows:
```js ```js
let promiseRestore = rdbStore.restore("dbBackup.db") let promiseRestore = store.restore("dbBackup.db");
promiseRestore.then(() => { promiseRestore.then(() => {
console.info('Restore success.') console.info(`Restore success.`);
}).catch((err) => { }).catch((err) => {
console.info('Restore failed, err: ' + err) console.error(`Restore failed, err: ${err}`);
}) })
``` ```
...@@ -36,5 +36,5 @@ Currently you can have access to statistics on the application usage, and the no ...@@ -36,5 +36,5 @@ Currently you can have access to statistics on the application usage, and the no
Deregister the callback for application group changes. Deregister the callback for application group changes.
## Required Permissions ## Required Permissions
- Before calling the following system APIs, you need to apply for the **ohos.permission.BUNDLE_ACTIVE_INFO** permission: **queryBundleActiveStates**, **queryBundleStateInfos**, **queryBundleStateInfoByInterval**, **queryBundleActiveEventStates**, **queryAppNotificationNumber**, **queryAppUsagePriorityGroup(bundleName?)**, **setBundleGroup**, **registerGroupCallBack**, and **unRegisterGroupCallBack**. - Before calling the following system APIs, you must request the **ohos.permission.BUNDLE_ACTIVE_INFO** permission: **isIdleState**, **queryBundleEvents**, **queryBundleStatsInfos**, **queryBundleStatsInfoByInterval**, **queryDeviceEventStats**, **queryNotificationEventStats**, **queryAppGroup(bundleName)**, **setAppGroup**, **registerAppGroupCallBack**, **unregisterAppGroupCallBack**, **queryModuleUsageRecords**, and **queryModuleUsageRecords(maxnum)**.
- This permission is not required for calling third-party APIs: **queryCurrentBundleActiveStates**, **queryAppUsagePriorityGroup()**, and **isIdleState**. - You do not need to request this permission before calling **queryCurrentBundleEvents** and **queryAppGroup()**, which are third-party APIs.
...@@ -225,7 +225,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -225,7 +225,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
} }
``` ```
7. Check whether the application specified by **bundleName** is in the idle state. This requires no permission to be configured. A third-party application can only check the idle status of itself. 7. Check whether the application specified by **bundleName** is in the idle state. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured.
```js ```js
import usageStatistics from '@ohos.resourceschedule.usageStatistics' import usageStatistics from '@ohos.resourceschedule.usageStatistics'
...@@ -531,4 +531,4 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -531,4 +531,4 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack throw error, code is: ' + error.code + ',message is: ' + error.message);
} }
``` ```
\ No newline at end of file
# Device # Device
- USB Service
- [USB Service Overview](usb-overview.md)
- [USB Service Development](usb-guidelines.md)
- Location - Location
- [Location Service Development](location-guidelines.md) - [Location Service Development](location-guidelines.md)
- Sensor
- [Sensor Overview](sensor-overview.md)
- [Sensor Development](sensor-guidelines.md)
- Vibrator
- [Vibrator Overview](vibrator-overview.md)
- [Vibrator Development](vibrator-guidelines.md)
- Multimodal Input - Multimodal Input
- [Input Device Development](inputdevice-guidelines.md) - [Input Device Development](inputdevice-guidelines.md)
- [Mouse Pointer Development](pointerstyle-guidelines.md) - [Mouse Pointer Development](pointerstyle-guidelines.md)
- Sensor
- [Sensor Overview](sensor-overview.md)
- [Sensor Development](sensor-guidelines.md)
- Update Service - Update Service
- [Sample Server Overview](sample-server-overview.md) - [Sample Server Overview](sample-server-overview.md)
- [Sample Server Development](sample-server-guidelines.md) - [Sample Server Development](sample-server-guidelines.md)
- USB Service
- [USB Service Overview](usb-overview.md)
- [USB Service Development](usb-guidelines.md)
- Vibrator
- [Vibrator Overview](vibrator-overview.md)
- [Vibrator Development](vibrator-guidelines.md)
\ No newline at end of file
...@@ -39,19 +39,19 @@ The following describes how to create an album named **myAlbum**. ...@@ -39,19 +39,19 @@ The following describes how to create an album named **myAlbum**.
```ts ```ts
async function example() { async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE; let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_IMAGE); const path = await media.getPublicDirectory(DIR_IMAGE);
// myAlbum is the path for storing the new file and the name of the new album. // myAlbum is the path for storing the new file and the name of the new album.
media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => { media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => {
if (fileAsset != undefined) { if (fileAsset === undefined) {
console.info('createAlbum successfully, message = ' + fileAsset); console.error('createAlbum failed, message = ' + err);
} else { } else {
console.info('createAlbum failed, message = ' + err); console.info('createAlbum successfully, message = ' + JSON.stringify(fileAsset));
} }
}); });
} }
``` ```
...@@ -75,20 +75,20 @@ The following describes how to rename the album **newAlbum**. ...@@ -75,20 +75,20 @@ The following describes how to rename the album **newAlbum**.
```ts ```ts
async function example() { async function example() {
let AlbumNoArgsfetchOp = { let AlbumNoArgsfetchOp = {
selections: '', selections: '',
selectionArgs: [], selectionArgs: [],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let albumList = await media.getAlbums(AlbumNoArgsfetchOp); let albumList = await media.getAlbums(AlbumNoArgsfetchOp);
let album = albumList[0]; let album = albumList[0];
album.albumName = 'newAlbum'; album.albumName = 'newAlbum';
// Void callback. // Void callback.
album.commitModify().then(function() { album.commitModify().then(() => {
console.info("albumRename successfully"); console.info("albumRename successfully");
}).catch(function(err){ }).catch((err) => {
console.info("albumRename failed with error: " + err); console.error("albumRename failed with error: " + err);
}); });
} }
``` ```
...@@ -37,15 +37,15 @@ The following describes how to obtain the public directory that stores camera fi ...@@ -37,15 +37,15 @@ The following describes how to obtain the public directory that stores camera fi
```ts ```ts
async function example(){ async function example(){
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
const dicResult = await media.getPublicDirectory(DIR_CAMERA); const dicResult = await media.getPublicDirectory(DIR_CAMERA);
if (dicResult == 'Camera/') { if (dicResult == 'Camera/') {
console.info('mediaLibraryTest : getPublicDirectory passed'); console.info('mediaLibraryTest : getPublicDirectory passed');
} else { } else {
console.info('mediaLibraryTest : getPublicDirectory failed'); console.error('mediaLibraryTest : getPublicDirectory failed');
} }
} }
``` ```
...@@ -59,47 +59,52 @@ Users can access files stored in the public directories through the system appli ...@@ -59,47 +59,52 @@ Users can access files stored in the public directories through the system appli
You can call [mediaLibrary.FileAsset.open](../reference/apis/js-apis-medialibrary.md#open8-1) to open a file in a public directory. You can call [mediaLibrary.FileAsset.open](../reference/apis/js-apis-medialibrary.md#open8-1) to open a file in a public directory.
You can call [fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7) to open a file in the application sandbox. The sandbox directory can be accessed only through the application context. You can call [fs.open](../reference/apis/js-apis-file-fs.md#fsopen) to open a file in the application sandbox. The sandbox directory can be accessed only through the application context.
**Prerequisites** **Prerequisites**
- You have obtained a **MediaLibrary** instance. - You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**. - You have granted the permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA**.
- You have imported the module [@ohos.fileio](../reference/apis/js-apis-fileio.md) in addition to @ohos.multimedia.mediaLibrary. - You have imported the module [@ohos.file.fs](../reference/apis/js-apis-file-fs.md) in addition to @ohos.multimedia.mediaLibrary.
- The **testFile.txt** file has been created and contains content.
**How to Develop** **How to Develop**
1. Call [context.filesDir](../reference/apis/js-apis-inner-app-context.md#contextgetfilesdir) to obtain the directory of the application sandbox. 1. Call [context.filesDir](../reference/apis/js-apis-file-fs.md) to obtain the directory of the application sandbox.
2. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory. 2. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory.
3. Call **fileio.open** to open the file in the sandbox. 3. Call **fs.open** to open the file in the sandbox.
4. Call **fileAsset.open** to open the file in the public directory. 4. Call **fileAsset.open** to open the file in the public directory.
5. Call **fileio.copyfile** to copy the file. 5. Call [fs.copyfile](../reference/apis/js-apis-file-fs.md#fscopyfile) to copy the file.
6. Call **fileAsset.close** and **fileio.close** to close the file. 6. Call **fileAsset.close** and [fs.close](../reference/apis/js-apis-file-fs.md#fsclose) to close the file.
**Example 1: Copying Files from the Public Directory to the Sandbox** **Example 1: Copying Files from the Public Directory to the Sandbox**
```ts ```ts
async function copyPublic2Sandbox() { async function copyPublic2Sandbox() {
try {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let sandboxDirPath = globalThis.context.filesDir; let sandboxDirPath = context.filesDir;
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?', selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile.txt'], selectionArgs: ['testFile.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
let fileAsset = await fetchResult.getFirstObject(); let fileAsset = await fetchResult.getFirstObject();
let fdPub = await fileAsset.open('rw'); let fdPub = await fileAsset.open('rw');
let fdSand = await fileio.open(sandboxDirPath + '/testFile.txt', 0o2 | 0o100, 0o666); let fdSand = await fs.open(sandboxDirPath + '/testFile.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
await fileio.copyFile(fdPub, fdSand); await fs.copyFile(fdPub, fdSand.fd);
await fileAsset.close(fdPub); await fileAsset.close(fdPub);
await fileio.close(fdSand); await fs.close(fdSand.fd);
let content_sand = await fileio.readText(sandboxDirPath + '/testFile.txt'); let content_sand = await fs.readText(sandboxDirPath + '/testFile.txt');
console.log('content read from sandbox file: ', content_sand) console.info('content read from sandbox file: ', content_sand)
} catch (err) {
console.info('[demo] copyPublic2Sandbox fail, err: ', err);
}
} }
``` ```
...@@ -107,81 +112,81 @@ async function copyPublic2Sandbox() { ...@@ -107,81 +112,81 @@ async function copyPublic2Sandbox() {
```ts ```ts
async function copySandbox2Public() { async function copySandbox2Public() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let sandboxDirPath = globalThis.context.filesDir; let sandboxDirPath = context.filesDir;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const publicDirPath = await media.getPublicDirectory(DIR_DOCUMENTS); const publicDirPath = await media.getPublicDirectory(DIR_DOCUMENTS);
try { try {
let fileAsset = await media.createAsset(mediaLibrary.MediaType.FILE, 'testFile02.txt', publicDirPath); let fileAsset = await media.createAsset(mediaLibrary.MediaType.FILE, 'testFile02.txt', publicDirPath);
console.info('createFile successfully, message = ' + fileAsset); console.info('createFile successfully, message = ' + fileAsset);
} catch (err) { } catch (err) {
console.info('createFile failed, message = ' + err); console.error('createFile failed, message = ' + err);
} }
try { try {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?', selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile02.txt'], selectionArgs: ['testFile02.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
var fileAsset = await fetchResult.getFirstObject(); var fileAsset = await fetchResult.getFirstObject();
} catch (err) { } catch (err) {
console.info('file asset get failed, message = ' + err); console.error('file asset get failed, message = ' + err);
} }
let fdPub = await fileAsset.open('rw'); let fdPub = await fileAsset.open('rw');
let fdSand = await fileio.open(sandboxDirPath + 'testFile.txt', 0o2); let fdSand = await fs.open(sandboxDirPath + 'testFile.txt', OpenMode.READ_WRITE);
await fileio.copyFile(fdSand, fdPub); await fs.copyFile(fdSand.fd, fdPub);
await fileio.close(fdPub); await fileAsset.close(fdPub);
await fileio.close(fdSand); await fs.close(fdSand.fd);
let fdPubRead = await fileAsset.open('rw'); let fdPubRead = await fileAsset.open('rw');
try { try {
let arrayBuffer = new ArrayBuffer(4096); let arrayBuffer = new ArrayBuffer(4096);
await fileio.read(fdPubRead, arrayBuffer); await fs.read(fdPubRead, arrayBuffer);
var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer)); var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer));
fileAsset.close(fdPubRead); fileAsset.close(fdPubRead);
} catch (err) { } catch (err) {
console.log('read text failed, message = ', err); console.error('read text failed, message = ', err);
} }
console.log('content read from public file: ', content_pub); console.info('content read from public file: ', content_pub);
} }
``` ```
### Reading and Writing a File ### Reading and Writing a File
You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../reference/apis/js-apis-medialibrary.md) to open and close a file, and use **fileio.read** and **fileio.write** of [fileio](../reference/apis/js-apis-fileio.md) to read and write a file. You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../reference/apis/js-apis-medialibrary.md) to open and close a file, and use **fs.read** and **fs.write** in [file.fs](../reference/apis/js-apis-file-fs.md) to read and write the file.
**Prerequisites** **Prerequisites**
- You have obtained a **MediaLibrary** instance. - You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**. - You have granted the permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA**.
- You have imported the module [@ohos.fileio](../reference/apis/js-apis-fileio.md) in addition to @ohos.multimedia.mediaLibrary. - You have imported the module [@ohos.file.fs](../reference/apis/js-apis-file-fs.md) in addition to @ohos.multimedia.mediaLibrary.
**How to Develop** **How to Develop**
1. Create a file. 1. Create a file.
```ts ```ts
async function example() { async function example() {
let mediaType = mediaLibrary.MediaType.FILE; let mediaType = mediaLibrary.MediaType.FILE;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS); const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.text", path).then (function (asset) { media.createAsset(mediaType, "testFile.text", path).then((asset) => {
console.info("createAsset successfully:" + JSON.stringify(asset)); console.info("createAsset successfully:" + JSON.stringify(asset));
}).catch(function(err){ }).catch((err) => {
console.info("createAsset failed with error: " + err); console.error("createAsset failed with error: " + err);
}); });
} }
``` ```
2. Call **FileAsset.open** to open the file. 2. Call **FileAsset.open** to open the file.
3. Call **fileio.write** to write a string to the file. 3. Call [fs.write](../reference/apis/js-apis-file-fs.md#fswrite) to write a string to the file.
4. Call **fileio.read** to read the file and save the data read in an array buffer. 4. Call [fs.read](../reference/apis/js-apis-file-fs.md#fsread) to read the file and save the data read in an array buffer.
5. Convert the array buffer to a string. 5. Convert the array buffer to a string.
...@@ -191,25 +196,25 @@ You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../refe ...@@ -191,25 +196,25 @@ You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../refe
```ts ```ts
async function writeOnlyPromise() { async function writeOnlyPromise() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?', selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile.txt'], selectionArgs: ['testFile.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
let fileAsset = await fetchResult.getFirstObject(); let fileAsset = await fetchResult.getFirstObject();
console.info('fileAssetName: ', fileAsset.displayName); console.info('fileAssetName: ', fileAsset.displayName);
try { try {
let fd = await fileAsset.open('w'); let fd = await fileAsset.open('w');
console.info('file descriptor: ', fd); console.info('file descriptor: ', fd);
await fileio.write(fd, "Write file test content."); await fs.write(fd, "Write file test content.");
await fileAsset.close(fd); await fileAsset.close(fd);
} catch (err) { } catch (err) {
console.info('write file failed, message = ', err); console.error('write file failed, message = ', err);
} }
} }
``` ```
...@@ -217,28 +222,28 @@ async function writeOnlyPromise() { ...@@ -217,28 +222,28 @@ async function writeOnlyPromise() {
```ts ```ts
async function readOnlyPromise() { async function readOnlyPromise() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' , selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
selectionArgs: ['testFile.txt'], selectionArgs: ['testFile.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
let fileAsset = await fetchResult.getFirstObject(); let fileAsset = await fetchResult.getFirstObject();
console.info('fileAssetName: ', fileAsset.displayName); console.info('fileAssetName: ', fileAsset.displayName);
try { try {
let fd = await fileAsset.open('r'); let fd = await fileAsset.open('r');
let arrayBuffer = new ArrayBuffer(4096); let arrayBuffer = new ArrayBuffer(4096);
await fileio.read(fd, arrayBuffer); await fs.read(fd, arrayBuffer);
let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer)); let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer));
globalThis.fileContent = fileContent; globalThis.fileContent = fileContent;
globalThis.fileName = fileAsset.displayName; globalThis.fileName = fileAsset.displayName;
console.info('file content: ', fileContent); console.info('file content: ', fileContent);
await fileAsset.close(fd); await fileAsset.close(fd);
} catch (err) { } catch (err) {
console.info('read file failed, message = ', err); console.error('read file failed, message = ', err);
} }
} }
``` ```
...@@ -64,64 +64,64 @@ After configuring the permissions in the **module.json5** file, the application ...@@ -64,64 +64,64 @@ After configuring the permissions in the **module.json5** file, the application
1. Declare the permissions in the **module.json5** file. Add the **requestPermissions** tag under **module** in the file, and set the tag based on the project requirements. For details about the tag, see [Guide for Requesting Permissions from User](../security/accesstoken-guidelines.md). 1. Declare the permissions in the **module.json5** file. Add the **requestPermissions** tag under **module** in the file, and set the tag based on the project requirements. For details about the tag, see [Guide for Requesting Permissions from User](../security/accesstoken-guidelines.md).
```json ```json
{ {
"module": { "module": {
"requestPermissions": [ "requestPermissions": [
{ {
"name": "ohos.permission.MEDIA_LOCATION", "name": "ohos.permission.MEDIA_LOCATION",
"reason": "$string:reason", "reason": "$string:reason",
"usedScene": { "usedScene": {
"abilities": [ "abilities": [
"EntryAbility" "EntryAbility"
], ],
"when": "always" "when": "always"
} }
}, },
{ {
"name": "ohos.permission.READ_MEDIA", "name": "ohos.permission.READ_MEDIA",
"reason": "$string:reason", "reason": "$string:reason",
"usedScene": { "usedScene": {
"abilities": [ "abilities": [
"EntryAbility" "EntryAbility"
], ],
"when": "always" "when": "always"
} }
}, },
{ {
"name": "ohos.permission.WRITE_MEDIA", "name": "ohos.permission.WRITE_MEDIA",
"reason": "$string:reason", "reason": "$string:reason",
"usedScene": { "usedScene": {
"abilities": [ "abilities": [
"EntryAbility" "EntryAbility"
], ],
"when": "always" "when": "always"
} }
} }
] ]
} }
} }
``` ```
2. In the **Ability.ts** file, call **requestPermissionsFromUser** in the **onWindowStageCreate** callback to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box. 2. In the **Ability.ts** file, call **requestPermissionsFromUser** in the **onWindowStageCreate** callback to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
let list : Array<Permissions> = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA']; let list : Array<Permissions> = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA'];
let permissionRequestResult; let permissionRequestResult;
let atManager = abilityAccessCtrl.createAtManager(); let atManager = abilityAccessCtrl.createAtManager();
atManager.requestPermissionsFromUser(this.context, list, (err, result) => { atManager.requestPermissionsFromUser(this.context, list, (err, result) => {
if (err) { if (err) {
console.log('requestPermissionsFromUserError: ' + JSON.stringify(err)); console.error('requestPermissionsFromUserError: ' + JSON.stringify(err));
} else { } else {
permissionRequestResult=result; permissionRequestResult = result;
console.log('permissionRequestResult: ' + JSON.stringify(permissionRequestResult)); console.info('permissionRequestResult: ' + JSON.stringify(permissionRequestResult));
} }
}); });
} }
} }
``` ```
...@@ -33,30 +33,33 @@ To specify the image as the media type, set **selectionArgs** to **MediaType.IMA ...@@ -33,30 +33,33 @@ To specify the image as the media type, set **selectionArgs** to **MediaType.IMA
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE; let fileType = mediaLibrary.MediaType.IMAGE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getFirstObject().then((fileAsset) => {
fetchFileResult.getNextObject((err, fileAsset) => { console.log('getFirstObject.displayName : ' + fileAsset.displayName);
if (err) { for (let i = 1; i < fetchFileResult.getCount(); i++) {
console.error('Failed '); fetchFileResult.getNextObject().then((fileAsset) => {
return; console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
} }).catch((err) => {
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.error('Failed to get next object: ' + err);
}) });
} }
}).catch((err) => {
console.error('Failed to get first object: ' + err);
});
} }
``` ```
### Querying Media Assets with the Specified Date ### Querying Media Assets with the Specified Date
The following describes how to obtain media assets that are added on the specified date. You can also use the modification date and shooting date as the retrieval conditions. The following describes how to obtain all the media assets that are added from the specified date. You can also use the modification date and shooting date as the retrieval conditions.
To specify the date when the files are added as the retrieval condition, set **selections** to **FileKey.DATE_ADDED**. To specify the date when the files are added as the retrieval condition, set **selections** to **FileKey.DATE_ADDED**.
...@@ -64,23 +67,26 @@ To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**. ...@@ -64,23 +67,26 @@ To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**.
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let option = { let option = {
selections: fileKeyObj.DATE_ADDED + '= ?', selections: fileKeyObj.DATE_ADDED + '> ?',
selectionArgs: ['2022-8-5'], selectionArgs: ['2022-8-5'],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getFirstObject().then((fileAsset) => {
fetchFileResult.getNextObject((err, fileAsset) => { console.info('getFirstObject.displayName : ' + fileAsset.displayName);
if (err) { for (let i = 1; i < fetchFileResult.getCount(); i++) {
console.error('Failed '); fetchFileResult.getNextObject().then((fileAsset) => {
return; console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
} }).catch((err) => {
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.error('Failed to get next object: ' + err);
}) });
} }
}).catch((err) => {
console.error('Failed to get first object: ' + err);
});
} }
``` ```
...@@ -92,25 +98,28 @@ To sort files in descending order by the date when they are added, set **order** ...@@ -92,25 +98,28 @@ To sort files in descending order by the date when they are added, set **order**
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE; let fileType = mediaLibrary.MediaType.IMAGE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + " DESC",
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getFirstObject().then((fileAsset) => {
fetchFileResult.getNextObject((err, fileAsset) => { console.info('getFirstObject.displayName : ' + fileAsset.displayName);
if (err) { for (let i = 1; i < fetchFileResult.getCount(); i++) {
console.error('Failed '); fetchFileResult.getNextObject().then((fileAsset) => {
return; console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
} }).catch((err) => {
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.error('Failed to get next object: ' + err);
}) });
} }
}).catch((err) => {
console.error('Failed to get first object: ' + err);
});
} }
``` ```
...@@ -124,31 +133,29 @@ To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**. ...@@ -124,31 +133,29 @@ To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**.
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE; let option = {
let option = { selections: fileKeyObj.ALBUM_NAME + '= ?',
selections: fileKeyObj.ALBUM_NAME + '= ?', selectionArgs: ['myAlbum'],
selectionArgs: ['myAlbum'], };
}; const context = getContext(this);
const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option);
const fetchFileResult = await media.getFileAssets(option); if (albumList.length > 0) {
for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getFirstObject().then((album) => {
fetchFileResult.getNextObject((err, fileAsset) => { console.info('getFirstObject.displayName : ' + album.albumName);
if (err) { }).catch((err) => {
console.error('Failed '); console.error('Failed to get first object: ' + err);
return; });
} } else {
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.info('getAlbum list is: 0');
}) }
}
} }
``` ```
## Obtaining Images and Videos in an Album ## Obtaining Images and Videos in an Album
You can obtain media assets in an album in either of the following ways: You can obtain media assets in an album in either of the following ways:
- Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified, as described in [Querying Media Assets with the Specfied Album Name](#querying-media-assets-with-the-specified-album-name). - Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified, as described in [Querying Media Assets with the Specfied Album Name](#querying-media-assets-with-the-specified-album-name).
- Call [Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3) to obtain an **Album** instance, so as to obtain the media assets in it. - Call [Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3) to obtain an **Album** instance, so as to obtain the media assets in it.
...@@ -163,24 +170,24 @@ The following describes how to obtain videos in an album named **New Album 1**. ...@@ -163,24 +170,24 @@ The following describes how to obtain videos in an album named **New Album 1**.
1. Create a retrieval condition for obtaining the target **Album** instance. 1. Create a retrieval condition for obtaining the target **Album** instance.
```ts ```ts
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let AlbumNoArgsFetchOp = { let AlbumNoArgsFetchOp = {
selections: fileKeyObj.ALBUM_NAME + '= ?', selections: fileKeyObj.ALBUM_NAME + '= ?',
selectionArgs:['New Album 1'] selectionArgs:['New Album 1']
} }
``` ```
2. Create a retrieval condition for obtaining videos in the target album. 2. Create a retrieval condition for obtaining videos in the target album.
```ts ```ts
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.VIDEO; let videoType = mediaLibrary.MediaType.VIDEO;
let imagesFetchOp = { let videoFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [videoType.toString()],
} }
``` ```
3. Call **Album.getFileAssets** to obtain the videos in the target album. 3. Call **Album.getFileAssets** to obtain the videos in the target album.
...@@ -188,28 +195,28 @@ Complete sample code: ...@@ -188,28 +195,28 @@ Complete sample code:
```ts ```ts
async function getCameraImagePromise() { async function getCameraImagePromise() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let videoType = mediaLibrary.MediaType.VIDEO;
let imagesFetchOp = { let videoFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [videoType.toString()],
} }
let AlbumNoArgsFetchOp = { let AlbumNoArgsFetchOp = {
selections: fileKeyObj.ALBUM_NAME + '= ?', selections: fileKeyObj.ALBUM_NAME + '= ?',
selectionArgs:['New Album 1'] selectionArgs:['New Album 1']
} }
let albumList = await media.getAlbums(AlbumNoArgsFetchOp); let albumList = await media.getAlbums(AlbumNoArgsFetchOp);
if (albumList.length > 0) { if (albumList.length > 0) {
const album = albumList[0]; const album = albumList[0];
let fetchFileResult = await album.getFileAssets(imagesFetchOp); let fetchFileResult = await album.getFileAssets(videoFetchOp);
let count = fetchFileResult.getCount(); let count = fetchFileResult.getCount();
console.info("get mediaLibrary IMAGE number", count); console.info("get mediaLibrary VIDEO number", count);
} else { } else {
console.info('getAlbum list is: 0'); console.info('getAlbum list is: 0');
} }
} }
``` ```
...@@ -235,31 +242,32 @@ The following describes how to obtain the thumbnail (size: 720 x 720) of the fir ...@@ -235,31 +242,32 @@ The following describes how to obtain the thumbnail (size: 720 x 720) of the fir
```ts ```ts
async function getFirstThumbnailPromise() { async function getFirstThumbnailPromise() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let imagesFetchOp = { let imagesFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
} }
let size = { width: 720, height: 720 }; let size = { width: 720, height: 720 };
const fetchFileResult = await media.getFileAssets(imagesFetchOp); const fetchFileResult = await media.getFileAssets(imagesFetchOp);
if (fetchFileResult != undefined) { if (fetchFileResult === undefined) {
const asset = await fetchFileResult.getFirstObject(); console.error("get image failed with error");
asset.getThumbnail(size).then((pixelMap) => { return;
pixelMap.getImageInfo().then((info) => { } else {
console.info('get Thumbnail info: ' + "width: " + info.size.width + " height: " + info.size.height); const asset = await fetchFileResult.getFirstObject();
}).catch((err) => { asset.getThumbnail(size).then((pixelMap) => {
console.info("getImageInfo failed with error:" + err); pixelMap.getImageInfo().then((info) => {
}); console.info('get Thumbnail info: ' + "width: " + info.size.width + " height: " + info.size.height);
}).catch((err) => { }).catch((err) => {
console.info("getImageInfo failed with error:" + err); console.error("getImageInfo failed with error: " + err);
}); });
} else { }).catch((err) => {
console.info("get image failed with error"); console.error("getImageInfo failed with error: " + err);
} });
}
} }
``` ```
...@@ -277,16 +285,16 @@ The following describes how to create a file of the **MediaType.FILE** type. ...@@ -277,16 +285,16 @@ The following describes how to create a file of the **MediaType.FILE** type.
```ts ```ts
async function example() { async function example() {
let mediaType = mediaLibrary.MediaType.FILE; let mediaType = mediaLibrary.MediaType.FILE;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS); const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.text", path).then ((asset) => { media.createAsset(mediaType, "testFile.text", path).then((asset) => {
console.info("createAsset successfully:"+ JSON.stringify(asset)); console.info("createAsset successfully:"+ JSON.stringify(asset));
}).catch((err) => { }).catch((err) => {
console.info("createAsset failed with error:"+ err); console.error("createAsset failed with error: " + err);
}); });
} }
``` ```
...@@ -312,26 +320,26 @@ The following describes how to move the first file in the result set to the recy ...@@ -312,26 +320,26 @@ The following describes how to move the first file in the result set to the recy
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE; let fileType = mediaLibrary.MediaType.FILE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject(); let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) { if (asset === undefined) {
console.error('asset not exist'); console.error('asset not exist');
return; return;
} }
// Void callback. // Void callback.
asset.trash(true).then(() => { asset.trash(true).then(() => {
console.info("trash successfully"); console.info("trash successfully");
}).catch((err) => { }).catch((err) => {
console.info("trash failed with error: " + err); console.error("trash failed with error: " + err);
}); });
} }
``` ```
...@@ -346,7 +354,7 @@ Before renaming a file, you must obtain the file, for example, by calling [Fetch ...@@ -346,7 +354,7 @@ Before renaming a file, you must obtain the file, for example, by calling [Fetch
- You have obtained a **MediaLibrary** instance. - You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**. - You have granted the permission **ohos.permission.WRITE_MEDIA**.
The following describes how to rename the first file in the result set as **newtitle.text**. The following describes how to rename the first file in the result set as **newImage.jpg**.
**How to Develop** **How to Develop**
...@@ -358,28 +366,28 @@ The following describes how to rename the first file in the result set as **newt ...@@ -358,28 +366,28 @@ The following describes how to rename the first file in the result set as **newt
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE; let fileType = mediaLibrary.MediaType.IMAGE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject(); let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) { if (asset === undefined) {
console.error('asset not exist'); console.error('asset not exist');
return;
}
asset.displayName = 'newImage.jpg';
// Void callback.
asset.commitModify((err) => {
if (err) {
console.error('fileRename Failed ');
return; return;
} }
asset.displayName = 'newImage.jpg'; console.info('fileRename successful.');
// Void callback. });
asset.commitModify((err) => {
if (err) {
console.error('fileRename Failed ');
return;
}
console.log('fileRename successful.');
});
} }
``` ```
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
You can call the APIs provided by the **Camera** module to develop a distributed camera that provides the basic camera functions such as shooting and video recording. You can call the APIs provided by the **Camera** module to develop a distributed camera that provides the basic camera functions such as shooting and video recording.
## How to Develop ## How to Develop
Connect your calculator to a distributed device. Your calculator will call **getCameras()** to obtain the camera list and traverse the returned camera list to check **ConnectionType** of the **Camera** objects. If **ConnectionType** of a **Camera** object is **CAMERA_CONNECTION_REMOTE**, your calculator will use this object to create a **CameraInput** object. The subsequent call process is the same as that of the local camera development. For details about the local camera development, see [Camera Development](./camera.md). Connect your calculator to a distributed device. Your calculator will call **getSupportedCameras()** to obtain the camera list and traverse the returned camera list to check **ConnectionType** of the **Camera** objects. If **ConnectionType** of a **Camera** object is **CAMERA_CONNECTION_REMOTE**, your calculator will use this object to create a **cameraInput** object. The subsequent call process is the same as that of the local camera development. For details about the local camera development, see [Camera Development](./camera.md).
For details about the APIs, see [Camera Management](../reference/apis/js-apis-camera.md). For details about the APIs, see [Camera Management](../reference/apis/js-apis-camera.md).
...@@ -24,15 +24,11 @@ import media from '@ohos.multimedia.media' ...@@ -24,15 +24,11 @@ import media from '@ohos.multimedia.media'
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
// Create a CameraManager object. // Create a CameraManager object.
let cameraManager let cameraManager = camera.getCameraManager(globalThis.Context)
await camera.getCameraManager(globalThis.Context, (err, manager) => { if (!cameraManager) {
if (err) { console.error("camera.getCameraManager error")
console.error('Failed to get the CameraManager instance ${err.message}'); return;
return; }
}
console.log('Callback returned with the CameraManager instance');
cameraManager = manager
})
// Register a callback to listen for camera status changes and obtain the updated camera status information. // Register a callback to listen for camera status changes and obtain the updated camera status information.
cameraManager.on('cameraStatus', (cameraStatusInfo) => { cameraManager.on('cameraStatus', (cameraStatusInfo) => {
...@@ -41,16 +37,12 @@ cameraManager.on('cameraStatus', (cameraStatusInfo) => { ...@@ -41,16 +37,12 @@ cameraManager.on('cameraStatus', (cameraStatusInfo) => {
}) })
// Obtain the camera list. // Obtain the camera list.
let cameraArray
let remoteCamera let remoteCamera
await cameraManager.getCameras((err, cameras) => { let cameraArray = cameraManager.getSupportedCameras();
if (err) { if (cameraArray.length <= 0) {
console.error('Failed to get the cameras. ${err.message}'); console.error("cameraManager.getSupportedCameras error")
return; return;
} }
console.log('Callback returned with an array of supported cameras: ' + cameras.length);
cameraArray = cameras
})
for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) { for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) {
console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // Obtain the camera ID. console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // Obtain the camera ID.
...@@ -58,15 +50,16 @@ for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) { ...@@ -58,15 +50,16 @@ for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) {
console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type. console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type.
console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) // Obtain the camera connection type. console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) // Obtain the camera connection type.
if (cameraArray[cameraIndex].connectionType == CAMERA_CONNECTION_REMOTE) { if (cameraArray[cameraIndex].connectionType == CAMERA_CONNECTION_REMOTE) {
remoteCamera = cameraArray[cameraIndex].cameraId remoteCamera = cameraArray[cameraIndex]
} }
} }
// Create a camera input stream. // Create a camera input stream.
let cameraInput let cameraInput
await cameraManager.createCameraInput(remoteCamera).then((input) => { try {
console.log('Promise returned with the CameraInput instance'); cameraInput = cameraManager.createCameraInput(remoteCamera);
cameraInput = input } catch () {
}) console.error('Failed to createCameraInput errorCode = ' + error.code);
}
``` ```
For details about the subsequent steps, see [Camera Development](./camera.md). For details about the subsequent steps, see [Camera Development](./camera.md).
...@@ -4,9 +4,7 @@ OpenHarmony applications use JavaScript (JS) when calling native APIs. The nativ ...@@ -4,9 +4,7 @@ OpenHarmony applications use JavaScript (JS) when calling native APIs. The nativ
## How to Develop ## How to Develop
The DevEco Studio has a default project that uses NAPIs. The DevEco Studio has a default project that uses NAPIs. You can choose **File** > **New** > **Create Project** to create a **Native C++** project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **ace_napi** repository for development.
You can choose **File** > **New** > **Create Project** to create a **Native C++** project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **ace_napi** repository for development.
You can import the native .so that contains the JS processing logic. For example, **import hello from 'libhello.so'** to use the **libhello.so** capability. Then, the JS object created using the NAPI can be passed to the **hello** object of the application to call the native capability. You can import the native .so that contains the JS processing logic. For example, **import hello from 'libhello.so'** to use the **libhello.so** capability. Then, the JS object created using the NAPI can be passed to the **hello** object of the application to call the native capability.
...@@ -19,7 +17,10 @@ You can import the native .so that contains the JS processing logic. For example ...@@ -19,7 +17,10 @@ You can import the native .so that contains the JS processing logic. For example
### .so Naming Rules ### .so Naming Rules
Each module has a .so file. For example, if the module name is **hello**, name the .so file **libhello.so**. The **nm_modname** field in **napi_module** must be **hello**, which is the same as the module name. The sample code for importing the .so file is **import hello from 'libhello.so'**. The .so file names must comply with the following rules:
* Each module has a .so file.
* The **nm_modname** field in **napi_module** must be the same as the module name. For example, if the module name is **hello**, name the .so file **libhello.so**. The sample code for importing the .so file is **import hello from 'libhello.so'**.
### JS Objects and Threads ### JS Objects and Threads
......
...@@ -44,6 +44,6 @@ For details about the APIs, see [@ohos.notificationManager](../reference/apis/js ...@@ -44,6 +44,6 @@ For details about the APIs, see [@ohos.notificationManager](../reference/apis/js
notificationManager.requestEnableNotification().then(() => { notificationManager.requestEnableNotification().then(() => {
console.info(`[ANS] requestEnableNotification success`); console.info(`[ANS] requestEnableNotification success`);
}).catch((err) => { }).catch((err) => {
console.error(`[ANS] requestEnableNotification failed, errCode[${err}]`); console.error(`[ANS] requestEnableNotification failed, code is ${err.code}, message is ${err.message}`);
}); });
``` ```
...@@ -74,7 +74,7 @@ The major APIs for notification subscription are described as follows. For detai ...@@ -74,7 +74,7 @@ The major APIs for notification subscription are described as follows. For detai
```ts ```ts
notificationSubscribe.subscribe(subscriber, (err, data) => { // This API uses an asynchronous callback to return the result. notificationSubscribe.subscribe(subscriber, (err, data) => { // This API uses an asynchronous callback to return the result.
if (err) { if (err) {
console.error(`[ANS] failed to subscribe, error[${err}]`); console.error(`[ANS] subscribe failed, code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.info(`[ANS] subscribeTest success : + ${data}`); console.info(`[ANS] subscribeTest success : + ${data}`);
......
...@@ -5,6 +5,7 @@ A [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md) object encapsu ...@@ -5,6 +5,7 @@ A [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md) object encapsu
Below you can see the process of adding a **WantAgent** object to a notification. The notification publisher requests a **WantAgent** object from the Ability Manager Service (AMS), and then sends a notification carrying the **WantAgent** object to the home screen. When the user touches the notification from the notification panel on the home screen, the **WantAgent** object is triggered. Below you can see the process of adding a **WantAgent** object to a notification. The notification publisher requests a **WantAgent** object from the Ability Manager Service (AMS), and then sends a notification carrying the **WantAgent** object to the home screen. When the user touches the notification from the notification panel on the home screen, the **WantAgent** object is triggered.
**Figure 1** Publishing a notification with a WantAgent object **Figure 1** Publishing a notification with a WantAgent object
![notification-with-wantagent](figures/notification-with-wantagent.png) ![notification-with-wantagent](figures/notification-with-wantagent.png)
...@@ -14,11 +15,11 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/ ...@@ -14,11 +15,11 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| getWantAgent(info: WantAgentInfo, callback: AsyncCallback&lt;WantAgent&gt;): void | Creates a **WantAgent** object.| |getWantAgent(info: WantAgentInfo, callback: AsyncCallback&lt;WantAgent&gt;): void | Creates a **WantAgent** object.|
| trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback&lt;CompleteData&gt;): void | Triggers a **WantAgent** object.| |trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback&lt;CompleteData&gt;): void | Triggers a **WantAgent** object.|
| cancel(agent: WantAgent, callback: AsyncCallback&lt;void&gt;): void | Cancels a **WantAgent** object.| |cancel(agent: WantAgent, callback: AsyncCallback&lt;void&gt;): void | Cancels a **WantAgent** object.|
| getWant(agent: WantAgent, callback: AsyncCallback&lt;Want&gt;): void | Obtains a **WantAgent** object.| |getWant(agent: WantAgent, callback: AsyncCallback&lt;Want&gt;): void | Obtains a **WantAgent** object.|
| equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether two **WantAgent** objects are equal. | |equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether two **WantAgent** objects are equal.|
## How to Develop ## How to Develop
...@@ -95,7 +96,7 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/ ...@@ -95,7 +96,7 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/
```typescript ```typescript
// Create a NotificationRequest object. // Create a NotificationRequest object.
let notificationRequest = { let notificationRequest: notificationManager.NotificationRequest = {
content: { content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: { normal: {
...@@ -111,7 +112,7 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/ ...@@ -111,7 +112,7 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/
notificationManager.publish(notificationRequest, (err) => { notificationManager.publish(notificationRequest, (err) => {
if (err) { if (err) {
console.error(`[ANS] failed to publish, error[${err}]`); console.error(`[ANS] publish failed, code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.info(`[ANS] publish success`); console.info(`[ANS] publish success`);
......
...@@ -5,12 +5,11 @@ The progress notification is a commonly used notification type, mainly used to d ...@@ -5,12 +5,11 @@ The progress notification is a commonly used notification type, mainly used to d
In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#notificationtemplate), which can only be of the progress type, **data** indicates custom template data. In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#notificationtemplate), which can only be of the progress type, **data** indicates custom template data.
## Available APIs ## Available APIs
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| isSupportTemplate(templateName: string, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether a specific template is supported. This API uses an asynchronous callback to return the result.<br>Only the progress-type template is supported.| | isSupportTemplate(templateName: string, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether a specific template is supported. This API uses an asynchronous callback to return the result. For details, see [isSupportTemplate()](../reference/apis/js-apis-notificationManager.md#notificationmanagerissupporttemplate).<br>Only the progress-type template is supported.|
## How to Develop ## How to Develop
...@@ -31,17 +30,18 @@ In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#n ...@@ -31,17 +30,18 @@ In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#n
let isSupportTpl: boolean = data; // The value **true** means that the template of the **downloadTemplate** type is supported; and false means the opposite. let isSupportTpl: boolean = data; // The value **true** means that the template of the **downloadTemplate** type is supported; and false means the opposite.
// ... // ...
}).catch((err) => { }).catch((err) => {
console.error(`[ANS] isSupportTemplate failed, error[${err}]`); console.error(`[ANS] isSupportTemplate failed, code is ${err.code}, message is ${err.message}`);
}); });
``` ```
> **NOTE** > **NOTE**
> >
> Proceed with the step below only when the specified template is supported. > Proceed with the step below only when the specified template is supported.
4. Create a **NotificationRequest** object and publish a progress notification. 4. Create a **NotificationRequest** object and publish a progress notification.
```ts ```ts
let notificationRequest = { let notificationRequest: notificationManager.NotificationRequest = {
id: 1, id: 1,
content: { content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
...@@ -61,7 +61,7 @@ In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#n ...@@ -61,7 +61,7 @@ In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#n
// Publish the notification. // Publish the notification.
notificationManager.publish(notificationRequest, (err) => { notificationManager.publish(notificationRequest, (err) => {
if (err) { if (err) {
console.error(`[ANS] failed to publish, error[${err}]`); console.error(`[ANS] publish failed, code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.info(`[ANS] publish success `); console.info(`[ANS] publish success `);
......
...@@ -45,7 +45,7 @@ The following table describes the APIs for notification publishing. You specify ...@@ -45,7 +45,7 @@ The following table describes the APIs for notification publishing. You specify
- A normal text notification consists of the **title**, **text**, and **additionalText** parameters, of which **title** and **text** are mandatory. The value of these parameters contains less than 200 bytes. - A normal text notification consists of the **title**, **text**, and **additionalText** parameters, of which **title** and **text** are mandatory. The value of these parameters contains less than 200 bytes.
```ts ```ts
let notificationRequest = { let notificationRequest: notificationManager.NotificationRequest = {
id: 1, id: 1,
content: { content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // Basic notification contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // Basic notification
...@@ -59,10 +59,10 @@ The following table describes the APIs for notification publishing. You specify ...@@ -59,10 +59,10 @@ The following table describes the APIs for notification publishing. You specify
notificationManager.publish(notificationRequest, (err) => { notificationManager.publish(notificationRequest, (err) => {
if (err) { if (err) {
console.error(`[ANS] failed to publish, error[${err}]`); console.error(`[ANS] publish failed, code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.info(`[ANS] publish success`); console.info(`[ANS] publish success.`);
}); });
``` ```
...@@ -71,7 +71,7 @@ The following table describes the APIs for notification publishing. You specify ...@@ -71,7 +71,7 @@ The following table describes the APIs for notification publishing. You specify
- In addition to the parameters in the normal text notification, the long text notification provides the **longText**, **briefText**, and **expandedTitle** parameters. The value of **longText** contains a maximum of 1024 bytes, while that of any other parameters contains less than 200 bytes. By default, a long-text notification looks in the same way as a normal text notification. When expanded, the notification displays the title and content specified in **expandedTitle** and **longText**, respectively. - In addition to the parameters in the normal text notification, the long text notification provides the **longText**, **briefText**, and **expandedTitle** parameters. The value of **longText** contains a maximum of 1024 bytes, while that of any other parameters contains less than 200 bytes. By default, a long-text notification looks in the same way as a normal text notification. When expanded, the notification displays the title and content specified in **expandedTitle** and **longText**, respectively.
```ts ```ts
let notificationRequest = { let notificationRequest: notificationManager.NotificationRequest = {
id: 1, id: 1,
content: { content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, // Long-text notification contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, // Long-text notification
...@@ -89,10 +89,10 @@ The following table describes the APIs for notification publishing. You specify ...@@ -89,10 +89,10 @@ The following table describes the APIs for notification publishing. You specify
// Publish the notification. // Publish the notification.
notificationManager.publish(notificationRequest, (err) => { notificationManager.publish(notificationRequest, (err) => {
if (err) { if (err) {
console.error(`[ANS] failed to publish, error[${err}]`); console.error(`[ANS] publish failed, code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.info(`[ANS] publish success`); console.info(`[ANS] publish success.`);
}); });
``` ```
...@@ -101,7 +101,7 @@ The following table describes the APIs for notification publishing. You specify ...@@ -101,7 +101,7 @@ The following table describes the APIs for notification publishing. You specify
- In addition to the parameters in the normal text notification, the multi-line text notification provides the **lines**, **briefText**, and **longTitle** parameters. The value of these parameters contains less than 200 bytes. By default, a multi-line notification looks in the same way as a normal text notification. When expanded, the notification displays the title and content specified in **longTitle** and **lines**, respectively. - In addition to the parameters in the normal text notification, the multi-line text notification provides the **lines**, **briefText**, and **longTitle** parameters. The value of these parameters contains less than 200 bytes. By default, a multi-line notification looks in the same way as a normal text notification. When expanded, the notification displays the title and content specified in **longTitle** and **lines**, respectively.
```ts ```ts
let notificationRequest = { let notificationRequest: notificationManager.NotificationRequest = {
id: 1, id: 1,
content: { content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // Multi-line text notification contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // Multi-line text notification
...@@ -118,7 +118,7 @@ The following table describes the APIs for notification publishing. You specify ...@@ -118,7 +118,7 @@ The following table describes the APIs for notification publishing. You specify
// Publish the notification. // Publish the notification.
notificationManager.publish(notificationRequest, (err) => { notificationManager.publish(notificationRequest, (err) => {
if (err) { if (err) {
console.error(`[ANS] failed to publish, error[${err}]`); console.error(`[ANS] publish failed, code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.info(`[ANS] publish success`); console.info(`[ANS] publish success`);
...@@ -131,7 +131,7 @@ The following table describes the APIs for notification publishing. You specify ...@@ -131,7 +131,7 @@ The following table describes the APIs for notification publishing. You specify
```ts ```ts
let notificationPicture: PixelMap = undefined; // Obtain the pixel map information. let notificationPicture: PixelMap = undefined; // Obtain the pixel map information.
let notificationRequest = { let notificationRequest: notificationManager.NotificationRequest = {
id: 1, id: 1,
content: { content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE, contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE,
...@@ -149,10 +149,10 @@ The following table describes the APIs for notification publishing. You specify ...@@ -149,10 +149,10 @@ The following table describes the APIs for notification publishing. You specify
// Publish the notification. // Publish the notification.
notificationManager.publish(notificationRequest, (err) => { notificationManager.publish(notificationRequest, (err) => {
if (err) { if (err) {
console.error(`[ANS] failed to publish, error[${err}]`); console.error(`[ANS] publish failed, code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.info(`[ANS] publish success `); console.info(`[ANS] publish success.`);
}); });
``` ```
......
...@@ -13,12 +13,10 @@ This document gives an overview of the **app.json5** configuration file. To star ...@@ -13,12 +13,10 @@ This document gives an overview of the **app.json5** configuration file. To star
"icon": "$media:app_icon", "icon": "$media:app_icon",
"label": "$string:app_name", "label": "$string:app_name",
"description": "$string:description_application", "description": "$string:description_application",
"distributedNotificationEnabled": true,
"minAPIVersion": 9, "minAPIVersion": 9,
"targetAPIVersion": 9, "targetAPIVersion": 9,
"apiReleaseType": "Release", "apiReleaseType": "Release",
"debug": false, "debug": false,
"entityType": "media",
"car": { "car": {
"minAPIVersion": 8, "minAPIVersion": 8,
} }
...@@ -46,9 +44,8 @@ As shown above, the **app.json5** file contains several tags. ...@@ -46,9 +44,8 @@ As shown above, the **app.json5** file contains several tags.
| minAPIVersion | Minimum API version required for running the application.| Number| Yes (initial value: value of **compatibleSdkVersion** in **build-profile.json5**)| | minAPIVersion | Minimum API version required for running the application.| Number| Yes (initial value: value of **compatibleSdkVersion** in **build-profile.json5**)|
| targetAPIVersion | Target API version required for running the application.| Number| Yes (initial value: value of **compileSdkVersion** in **build-profile.json5**)| | targetAPIVersion | Target API version required for running the application.| Number| Yes (initial value: value of **compileSdkVersion** in **build-profile.json5**)|
| apiReleaseType | Type of the target API version required for running the application. The value can be **"CanaryN"**, **"BetaN"**, or **"Release"**, where **N** represents a positive integer.<br>- **Canary**: indicates a restricted release.<br>- **Beta**: indicates a publicly released beta version.<br>- **Release**: indicates a publicly released official version.<br>The value is set by DevEco Studio reading the stage of the SDK in use.| String| Yes (initial value: set by DevEco Studio)| | apiReleaseType | Type of the target API version required for running the application. The value can be **"CanaryN"**, **"BetaN"**, or **"Release"**, where **N** represents a positive integer.<br>- **Canary**: indicates a restricted release.<br>- **Beta**: indicates a publicly released beta version.<br>- **Release**: indicates a publicly released official version.<br>The value is set by DevEco Studio reading the stage of the SDK in use.| String| Yes (initial value: set by DevEco Studio)|
| distributedNotificationEnabled | Whether distributed notification is enabled for the application. When distributed notification is enabled and device A and device B where the application is installed are on the same distributed network, the devices behave in this way: If device A receives a message, device B will receive a distributed notification prompting the user to check the message received on device A.<br>- **true**: Distributed notification is enabled.<br>- **false**: Distributed notification is not enabled.| Boolean| Yes (initial value: **false**)| | multiProjects | Whether the application supports joint development of multiple projects.<br>- **true**: The application supports joint development of multiple projects.<br>- **false**: The application does not support joint development of multiple projects. For details about multi-project development, see [Multi-Project Build](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-building-overview-0000001263360495-V3#section71471033104216).| Boolean| Yes (initial value: **false**)|
| entityType | Type of the application. The options are as follows:<br>- game<br>- media<br>- communication<br>- news<br>- travel<br>- utility<br>- shopping<br>- education<br>- kids<br>- business<br>- photography<br>- unspecified| String| Yes (initial value: **"unspecified"**)| | assanEnabled | Whether to enable AddressSanitizer (ASan) to detect memory corruption issues such as buffer overflows.<br>- **true**: ASan is enabled.<br>- **false**: ASan is disabled. Note that ASan is not available in the Release version.| Boolean| Yes (initial value: **false**)|
| multiProjects | Whether the application supports joint development of multiple projects.<br>- **true**: The application supports joint development of multiple projects.<br>- **false**: The application does not support joint development of multiple projects.| Boolean| Yes (initial value: **false**)|
| tablet | Tablet-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.<br>When running on tablets, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| | tablet | Tablet-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.<br>When running on tablets, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)|
| tv | TV-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.<br>When running on TVs, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| | tv | TV-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.<br>When running on TVs, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)|
| wearable | Wearable-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.<br>When running on wearables, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| | wearable | Wearable-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.<br>When running on wearables, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)|
......
...@@ -123,7 +123,7 @@ export default class EntryAbility extends UIAbility { ...@@ -123,7 +123,7 @@ export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
// storage is passed to the loadContent API as a parameter. // storage is passed to the loadContent API as a parameter.
windowStage.loadContent('pages/index', this.storage) windowStage.loadContent('pages/Index', this.storage)
} }
onWindowStageDestroy() { onWindowStageDestroy() {
...@@ -143,7 +143,7 @@ export default class EntryAbility extends UIAbility { ...@@ -143,7 +143,7 @@ export default class EntryAbility extends UIAbility {
The **@Component** decorated component obtains data. The **@Component** decorated component obtains data.
```ts ```ts
// index.ets // Index.ets
let storage = LocalStorage.GetShared() let storage = LocalStorage.GetShared()
@Entry(storage) @Entry(storage)
......
...@@ -494,7 +494,7 @@ struct CompA { ...@@ -494,7 +494,7 @@ struct CompA {
this.updateTotal() this.updateTotal()
} }
updateTotal(): number { updateTotal(): void {
let sum = 0; let sum = 0;
this.shopBasket.forEach((i) => { this.shopBasket.forEach((i) => {
sum += i sum += i
......
...@@ -3,25 +3,27 @@ ...@@ -3,25 +3,27 @@
DevEco Studio allows you to develop and build multiple HAP files in one application project, as shown below. DevEco Studio allows you to develop and build multiple HAP files in one application project, as shown below.
**Figure 1** Multi-HAP build view
**Figure 1** Multi-HAP build view
![hap-multi-view](figures/hap-multi-view.png) ![hap-multi-view](figures/hap-multi-view.png)
1. Development view in DevEco Studio 1. Development view in DevEco Studio
- AppScope folder - **AppScope** folder
- [app.json5](app-configuration-file.md): application-wide configuration, such as the application bundle name, version number, application icon, application name, and dependent SDK version number.
- **[app.json5](app-configuration-file.md)**: stores application-wide configuration, such as the application bundle name, version number, application icon, application name, and dependent SDK version number.
- **resources** folder: stores application icon resources and application name string resources. - **resources** folder: stores application icon resources and application name string resources.
**NOTE** **NOTE**
- The folder is automatically generated by DevEco Studio and its name cannot be changed.
- The file names in the **AppScope** folder cannot be the same as those in the entry- or feature-type module directories. Otherwise, DevEco Studio reports an error. - The folder is automatically generated by DevEco Studio and its name cannot be changed.
- Entry- or feature-type module directories (the names are customizable) - The file names in the **AppScope** folder cannot be the same as those in the entry- or feature-type module folder. Otherwise, an error will be reported.
- You implement service logic of your application in these module directories. In this example, the module folders are **entry.hap** and **feature.hap**. - **entry** or **feature** folder (whose name is customizable)
- **resources** directory: stores the resources used by the module. - A module folder created by the developer by following the creation wizard of DevEco Studio. It stores the service logic implementation of the application. Multiple module folders can be created. In the preceding figure, **entry** and **feature** are two created module folders.
- **resources** folder: stores the resources used by the module.
- **ets** folder: stores the service logic. - **ets** folder: stores the service logic.
- [module.json5](module-configuration-file.md): module configuration, such as the module name, entry code path of the module, and component information. - **[module.json5](module-configuration-file.md)**: stores module configuration, such as the module name, entry code path of the module, and component information.
2. View after build and packaging 2. View after build and packaging
- After a module is built, a HAP file for deployment is generated. Each module corresponds to a HAP file. - After a module is built, a HAP file for deployment is generated. Each module corresponds to a HAP file.
- The **module.json** file in the HAP file is composed of the **app.json5** and **module.json5** files in the development view. - The **module.json** file in the HAP file is composed of the **app.json5** and **module.json5** files in the development view.
......
...@@ -6,32 +6,40 @@ Below is the process of developing, debugging, releasing, and deploying multiple ...@@ -6,32 +6,40 @@ Below is the process of developing, debugging, releasing, and deploying multiple
![hap-release](figures/hap-release.png) ![hap-release](figures/hap-release.png)
## Development ## Development
You can use [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio) to create multiple modules based on service requirements and develop services in independent modules. You can use [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio) to create multiple modules as needed and develop services in respective modules.
## Debugging ## Debugging
You can use DevEco Studio to build code into one or more HAP files. Then, you can debug the HAP files. After building code into one or more HAP files and installing or updating these HAP files, you can debug them by using the methods:
* Using DevEco Studio for debugging * Using DevEco Studio for debugging
Follow the instructions in [Debugging Configuration](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-debugging-and-running-0000001263040487#section10491183521520). Follow the instructions in [Debugging Configuration](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-debugging-and-running-0000001263040487#section10491183521520).
* Using [hdc_std](../../device-dev/subsystems/subsys-toolchain-hdc-guide.md) for debugging * Using [hdc](../../device-dev/subsystems/subsys-toolchain-hdc-guide.md) (which can be obtained in the **toolchains** directory of the OpenHarmony SDK) for debugging
Before debugging HAP files, install or update them using either of the methods:
1. Use hdc to install and update the HAP files.
When specifying the HAP files, use the paths of the files on the operating system, for example, Windows.
You can obtain the hdc_std tool from the **toolchains** directory of the SDK. When using this tool to install an HAP file, the HAP file path is the one on the operating platform. In this example, the Windows operating platform is used. The command reference is as follows:
``` ```
// Installation and update: Multiple file paths can be specified. // Installation and update: Multiple file paths can be specified.
hdc_std install C:\entry.hap C:\feature.hap hdc install C:\entry.hap C:\feature.hap
// The execution result is as follows: // The execution result is as follows:
install bundle successfully. install bundle successfully.
// Uninstall // Uninstall
hdc_std uninstall com.example.myapplication hdc uninstall com.example.myapplication
// The execution result is as follows: // The execution result is as follows:
uninstall bundle successfully. uninstall bundle successfully.
``` ```
2. Run the hdc shell command, and then use the Bundle Manager (bm) tool to install and update the HAP files.
* Using [Bundle Manager (bm)](../../application-dev/tools/bm-tool.md) for debugging When specifying the HAP files, use the paths of the files on the real device. The sample code is as follows:
When using bm to install or update an HAP file, the HAP file path is the one on the real device. The command reference is as follows:
``` ```
// Run the hdc shell command before using the bm tool.
hdc shell
// Installation and update: Multiple file paths can be specified. // Installation and update: Multiple file paths can be specified.
bm install -p /data/app/entry.hap /data/app/feature.hap bm install -p /data/app/entry.hap /data/app/feature.hap
// The execution result is as follows: // The execution result is as follows:
...@@ -41,6 +49,8 @@ You can use DevEco Studio to build code into one or more HAP files. Then, you ca ...@@ -41,6 +49,8 @@ You can use DevEco Studio to build code into one or more HAP files. Then, you ca
// The execution result is as follows: // The execution result is as follows:
uninstall bundle successfully. uninstall bundle successfully.
``` ```
After the HAP files are installed or updated, you can debug them by following the instructions in [Ability Assistant](https://docs.openharmony.cn/pages/v3.2Beta/en/application-dev/tools/aa-tool.md/).
## Release ## Release
When your application package meets the release requirements, you can package and build it into an App Pack and release it to the application market on the cloud. The application market verifies the signature of the App Pack. If the signature verification is successful, the application market obtains the HAP files from the App Pack, signs them, and distributes the signed HAP files. When your application package meets the release requirements, you can package and build it into an App Pack and release it to the application market on the cloud. The application market verifies the signature of the App Pack. If the signature verification is successful, the application market obtains the HAP files from the App Pack, signs them, and distributes the signed HAP files.
......
# Multi-HAP Usage Rules # Multi-HAP Usage Rules
- The App Pack cannot be directly installed on the device. It is only a unit that is released to AppGallery. - The App Pack cannot be directly installed on a device. It is only used to be released to the application market.
- All HAP files in the App Pack must share the same **bundleName** value in the configuration files. - All HAP files in the App Pack must share the same **bundleName** value in the configuration files.
- All HAP files in the App Pack must share the same **versionCode** value in the configuration files. - All HAP files in the App Pack must share the same **versionCode** value in the configuration files.
- In an application, each type of device supports only one HAP of the entry type. Each application can contain zero, one, or more HAP files of the feature type. - In an App Pack, each type of device supports only one HAP file of the entry type and zero, one, or more HAP files of the feature type.
- Each HAP file in the App Pack must have **moduleName** configured. The **moduleName** value corresponding to all HAP files of the same device type must be unique. - Each HAP file in the App Pack must have **moduleName** configured. Among HAP files of the same device type, the **moduleName** value must be unique.
- The signing certificates of all HAP files in the same application must be the same. Applications are released to the application market in the form of App Pack after being signed. Before distribution, the application market splits an App Pack into HAP files and resigns them to ensure the consistency of all HAP file signing certificates. Before installing HAP files on a device through the CLI or DevEco Studio for debugging, you must ensure that their signing certificates are the same. Otherwise, the installation will fail. - The signing certificates of all HAP files in the same application must be the same. Applications are released to the application market in the form of App Pack after being signed. Before distribution, the application market splits an App Pack into HAP files and resigns them to ensure the consistency of HAP file signing certificates. Before installing HAP files on a device through the CLI or DevEco Studio for debugging, ensure that their signing certificates are the same. Otherwise, the installation will fail.
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
> >
> To use ArkTS, your DevEco Studio must be V3.0.0.601 Beta1 or later. > To use ArkTS, your DevEco Studio must be V3.0.0.601 Beta1 or later.
> >
> For best possible results, use [DevEco Studio V3.1.0.100](https://developer.harmonyos.com/cn/develop/deveco-studio) for your development. > For best possible results, use [DevEco Studio 3.1 Beta1](https://developer.harmonyos.com/cn/develop/deveco-studio) for your development.
## Creating an ArkTS Project ## Creating an ArkTS Project
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
> >
> To use ArkTS, your DevEco Studio must be V3.0.0.900 Beta3 or later. > To use ArkTS, your DevEco Studio must be V3.0.0.900 Beta3 or later.
> >
> For best possible results, use [DevEco Studio V3.1.0.100](https://developer.harmonyos.com/cn/develop/deveco-studio) for your development. > For best possible results, use [DevEco Studio 3.1 Beta1](https://developer.harmonyos.com/cn/develop/deveco-studio) for your development.
## Creating an ArkTS Project ## Creating an ArkTS Project
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
> **NOTE** > **NOTE**
> >
> For best possible results, use [DevEco Studio V3.0.0.993](https://developer.harmonyos.com/cn/develop/deveco-studio#download) for your development. > For best possible results, use [DevEco Studio 3.1 Beta1](https://developer.harmonyos.com/cn/develop/deveco-studio#download) for your development.
## Creating a JavaScript Project ## Creating a JavaScript Project
......
...@@ -19,16 +19,7 @@ ...@@ -19,16 +19,7 @@
- [@ohos.application.DataShareExtensionAbility (DataShare Extension Ability)](js-apis-application-dataShareExtensionAbility.md) - [@ohos.application.DataShareExtensionAbility (DataShare Extension Ability)](js-apis-application-dataShareExtensionAbility.md)
- [@ohos.application.StaticSubscriberExtensionAbility (StaticSubscriberExtensionAbility)](js-apis-application-staticSubscriberExtensionAbility.md) - [@ohos.application.StaticSubscriberExtensionAbility (StaticSubscriberExtensionAbility)](js-apis-application-staticSubscriberExtensionAbility.md)
- Stage Model (To Be Deprecated Soon) - Stage Model (To Be Deprecated Soon)
- [@ohos.application.Ability (Ability)](js-apis-application-ability.md)
- [@ohos.application.AbilityConstant (AbilityConstant)](js-apis-application-abilityConstant.md)
- [@ohos.application.AbilityLifecycleCallback (AbilityLifecycleCallback)](js-apis-application-abilityLifecycleCallback.md)
- [@ohos.application.AbilityStage (AbilityStage)](js-apis-application-abilityStage.md)
- [@ohos.application.context (Context)](js-apis-application-context.md)
- [@ohos.application.EnvironmentCallback (EnvironmentCallback)](js-apis-application-environmentCallback.md) - [@ohos.application.EnvironmentCallback (EnvironmentCallback)](js-apis-application-environmentCallback.md)
- [@ohos.application.ExtensionAbility (ExtensionAbility)](js-apis-application-extensionAbility.md)
- [@ohos.application.FormExtension (FormExtension)](js-apis-application-formExtension.md)
- [@ohos.application.ServiceExtensionAbility (ServiceExtensionAbility)](js-apis-application-serviceExtensionAbility.md)
- [@ohos.application.StartOptions (StartOptions)](js-apis-application-startOptions.md)
- FA Model - FA Model
- [@ohos.ability.ability (Ability)](js-apis-ability-ability.md) - [@ohos.ability.ability (Ability)](js-apis-ability-ability.md)
- [@ohos.ability.featureAbility (FeatureAbility)](js-apis-ability-featureAbility.md) - [@ohos.ability.featureAbility (FeatureAbility)](js-apis-ability-featureAbility.md)
...@@ -41,6 +32,7 @@ ...@@ -41,6 +32,7 @@
- [@ohos.app.ability.Configuration (Configuration)](js-apis-app-ability-configuration.md) - [@ohos.app.ability.Configuration (Configuration)](js-apis-app-ability-configuration.md)
- [@ohos.app.ability.ConfigurationConstant (ConfigurationConstant)](js-apis-app-ability-configurationConstant.md) - [@ohos.app.ability.ConfigurationConstant (ConfigurationConstant)](js-apis-app-ability-configurationConstant.md)
- [@ohos.app.ability.dataUriUtils (DataUriUtils)](js-apis-app-ability-dataUriUtils.md) - [@ohos.app.ability.dataUriUtils (DataUriUtils)](js-apis-app-ability-dataUriUtils.md)
- [@ohos.app.ability.dialogRequest (dialogRequest)](js-apis-app-ability-dialogRequest.md)
- [@ohos.app.ability.errorManager (ErrorManager)](js-apis-app-ability-errorManager.md) - [@ohos.app.ability.errorManager (ErrorManager)](js-apis-app-ability-errorManager.md)
- [@ohos.app.ability.missionManager (missionManager)](js-apis-app-ability-missionManager.md) - [@ohos.app.ability.missionManager (missionManager)](js-apis-app-ability-missionManager.md)
- [@ohos.app.ability.quickFixManager (quickFixManager)](js-apis-app-ability-quickFixManager.md) - [@ohos.app.ability.quickFixManager (quickFixManager)](js-apis-app-ability-quickFixManager.md)
...@@ -60,7 +52,6 @@ ...@@ -60,7 +52,6 @@
- [@ohos.application.appManager (appManager)](js-apis-application-appManager.md) - [@ohos.application.appManager (appManager)](js-apis-application-appManager.md)
- [@ohos.application.Configuration (Configuration)](js-apis-application-configuration.md) - [@ohos.application.Configuration (Configuration)](js-apis-application-configuration.md)
- [@ohos.application.ConfigurationConstant (ConfigurationConstant)](js-apis-application-configurationConstant.md) - [@ohos.application.ConfigurationConstant (ConfigurationConstant)](js-apis-application-configurationConstant.md)
- [@ohos.application.errorManager (ErrorManager)](js-apis-application-errorManager.md)
- [@ohos.application.formBindingData (formBindingData)](js-apis-application-formBindingData.md) - [@ohos.application.formBindingData (formBindingData)](js-apis-application-formBindingData.md)
- [@ohos.application.formError (FormError)](js-apis-application-formError.md) - [@ohos.application.formError (FormError)](js-apis-application-formError.md)
- [@ohos.application.formHost (FormHost)](js-apis-application-formHost.md) - [@ohos.application.formHost (FormHost)](js-apis-application-formHost.md)
...@@ -83,7 +74,6 @@ ...@@ -83,7 +74,6 @@
- [context](js-apis-inner-app-context.md) - [context](js-apis-inner-app-context.md)
- [processInfo](js-apis-inner-app-processInfo.md) - [processInfo](js-apis-inner-app-processInfo.md)
- application - application
- [AbilityContext](js-apis-ability-context.md)
- [abilityDelegator](js-apis-inner-application-abilityDelegator.md) - [abilityDelegator](js-apis-inner-application-abilityDelegator.md)
- [abilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) - [abilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md)
- [abilityMonitor](js-apis-inner-application-abilityMonitor.md) - [abilityMonitor](js-apis-inner-application-abilityMonitor.md)
...@@ -110,10 +100,11 @@ ...@@ -110,10 +100,11 @@
- [MissionSnapshot](js-apis-inner-application-missionSnapshot.md) - [MissionSnapshot](js-apis-inner-application-missionSnapshot.md)
- [ProcessData](js-apis-inner-application-processData.md) - [ProcessData](js-apis-inner-application-processData.md)
- [ProcessRunningInfo](js-apis-inner-application-processRunningInfo.md) - [ProcessRunningInfo](js-apis-inner-application-processRunningInfo.md)
- [ProcessRunningInformation](js-apis-inner-application-processRunningInformation.md) - [ProcessInformation](js-apis-inner-application-processInformation.md)
- [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) - [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md)
- [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) - [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md)
- [shellCmdResult](js-apis-inner-application-shellCmdResult.md) - [shellCmdResult](js-apis-inner-application-shellCmdResult.md)
- [WindowExtensionContext](js-apis-inner-application-windowExtensionContext.md)
- wantAgent - wantAgent
- [triggerInfo](js-apis-inner-wantAgent-triggerInfo.md) - [triggerInfo](js-apis-inner-wantAgent-triggerInfo.md)
- [wantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) - [wantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md)
...@@ -124,10 +115,12 @@ ...@@ -124,10 +115,12 @@
- [continuationResult](js-apis-continuation-continuationResult.md) - [continuationResult](js-apis-continuation-continuationResult.md)
- Common Event and Notification - Common Event and Notification
- [System Common Events](commonEventManager-definitions.md)
- [@ohos.commonEventManager (Common Event) (Recommended)](js-apis-commonEventManager.md) - [@ohos.commonEventManager (Common Event) (Recommended)](js-apis-commonEventManager.md)
- [@ohos.events.emitter (Emitter)](js-apis-emitter.md) - [@ohos.events.emitter (Emitter)](js-apis-emitter.md)
- [@ohos.notificationManager (NotificationManager) (Recommended)](js-apis-notificationManager.md) - [@ohos.notificationManager (NotificationManager) (Recommended)](js-apis-notificationManager.md)
- [@ohos.notificationSubscribe (NotificationSubscribe) (Recommended)](js-apis-notificationSubscribe.md) - [@ohos.notificationSubscribe (NotificationSubscribe) (Recommended)](js-apis-notificationSubscribe.md)
- [System Common Events (To Be Deprecated Soon)](commonEvent-definitions.md)
- [@ohos.commonEvent (Common Event) (To Be Deprecated Soon)](js-apis-commonEvent.md) - [@ohos.commonEvent (Common Event) (To Be Deprecated Soon)](js-apis-commonEvent.md)
- [@ohos.notification (Notification) (To Be Deprecated Soon)](js-apis-notification.md) - [@ohos.notification (Notification) (To Be Deprecated Soon)](js-apis-notification.md)
- application - application
...@@ -152,7 +145,6 @@ ...@@ -152,7 +145,6 @@
- [hapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) - [hapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)
- [launcherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) - [launcherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md)
- [metadata](js-apis-bundleManager-metadata.md) - [metadata](js-apis-bundleManager-metadata.md)
- [packInfo](js-apis-bundleManager-packInfo.md)
- [permissionDef](js-apis-bundleManager-permissionDef.md) - [permissionDef](js-apis-bundleManager-permissionDef.md)
- [remoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) - [remoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)
- [shortcutInfo](js-apis-bundleManager-shortcutInfo.md) - [shortcutInfo](js-apis-bundleManager-shortcutInfo.md)
...@@ -185,13 +177,14 @@ ...@@ -185,13 +177,14 @@
- [@ohos.i18n (Internationalization)](js-apis-i18n.md) - [@ohos.i18n (Internationalization)](js-apis-i18n.md)
- [@ohos.intl (Internationalization)](js-apis-intl.md) - [@ohos.intl (Internationalization)](js-apis-intl.md)
- [@ohos.resourceManager (Resource Manager)](js-apis-resource-manager.md) - [@ohos.resourceManager (Resource Manager)](js-apis-resource-manager.md)
- Resource Scheduling - Background Tasks
- [@ohos.distributedMissionManager (Distributed Mission Management)](js-apis-distributedMissionManager.md) - [@ohos.distributedMissionManager (Distributed Mission Management)](js-apis-distributedMissionManager.md)
- [@ohos.reminderAgentManager (Reminder Agent Management)](js-apis-reminderAgentManager.md) - [@ohos.reminderAgentManager (Reminder Agent Management)](js-apis-reminderAgentManager.md)
- [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](js-apis-resourceschedule-backgroundTaskManager.md) - [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](js-apis-resourceschedule-backgroundTaskManager.md)
- [@ohos.resourceschedule.workScheduler (Work Scheduler)](js-apis-resourceschedule-workScheduler.md) - [@ohos.resourceschedule.workScheduler (Work Scheduler)](js-apis-resourceschedule-workScheduler.md)
- [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](js-apis-resourceschedule-deviceUsageStatistics.md) - [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](js-apis-resourceschedule-deviceUsageStatistics.md)
- [@ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](js-apis-WorkSchedulerExtensionAbility.md) - [@ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](js-apis-WorkSchedulerExtensionAbility.md)
- Security - Security
- [@ohos.abilityAccessCtrl (Ability Access Control)](js-apis-abilityAccessCtrl.md) - [@ohos.abilityAccessCtrl (Ability Access Control)](js-apis-abilityAccessCtrl.md)
- [@ohos.privacyManager (Privacy Management)](js-apis-privacyManager.md) - [@ohos.privacyManager (Privacy Management)](js-apis-privacyManager.md)
...@@ -223,10 +216,11 @@ ...@@ -223,10 +216,11 @@
- [@ohos.file.hash (File Hash Processing)](js-apis-file-hash.md) - [@ohos.file.hash (File Hash Processing)](js-apis-file-hash.md)
- [@ohos.file.securityLabel (Data Label)](js-apis-file-securityLabel.md) - [@ohos.file.securityLabel (Data Label)](js-apis-file-securityLabel.md)
- [@ohos.file.statvfs (File System Space Statistics)](js-apis-file-statvfs.md) - [@ohos.file.statvfs (File System Space Statistics)](js-apis-file-statvfs.md)
- [@ohos.file.storageStatistics (Application Storage Statistics)](js-apis-file-storage-statistics.md)
- [@ohos.file.volumeManager (Volume Management)](js-apis-file-volumemanager.md)
- [@ohos.filemanagement.userFileManager (User Data Management)](js-apis-userFileManager.md) - [@ohos.filemanagement.userFileManager (User Data Management)](js-apis-userFileManager.md)
- [@ohos.multimedia.medialibrary (Media Library Management)](js-apis-medialibrary.md) - [@ohos.multimedia.medialibrary (Media Library Management)](js-apis-medialibrary.md)
- [@ohos.storageStatistics (Application Storage Statistics)](js-apis-storage-statistics.md)
- [@ohos.volumeManager (Volume Management)](js-apis-volumemanager.md)
- Telephony Service - Telephony Service
- [@ohos.contact (Contacts)](js-apis-contact.md) - [@ohos.contact (Contacts)](js-apis-contact.md)
- [@ohos.telephony.call (Call)](js-apis-call.md) - [@ohos.telephony.call (Call)](js-apis-call.md)
...@@ -278,7 +272,7 @@ ...@@ -278,7 +272,7 @@
- [@ohos.InputMethodSubtype (Input Method Subtype)](js-apis-inputmethod-subtype.md) - [@ohos.InputMethodSubtype (Input Method Subtype)](js-apis-inputmethod-subtype.md)
- [@ohos.pasteboard (Pasteboard)](js-apis-pasteboard.md) - [@ohos.pasteboard (Pasteboard)](js-apis-pasteboard.md)
- [@ohos.screenLock (Screenlock)](js-apis-screen-lock.md) - [@ohos.screenLock (Screenlock)](js-apis-screen-lock.md)
- [@ohos.systemTime (System Time and Time Zone)](js-apis-system-time.md) - [@ohos.systemDateTime (System Time and Time Zone)](js-apis-system-date-time.md)
- [@ohos.systemTimer (System Timer)](js-apis-system-timer.md) - [@ohos.systemTimer (System Timer)](js-apis-system-timer.md)
- [@ohos.wallpaper (Wallpaper)](js-apis-wallpaper.md) - [@ohos.wallpaper (Wallpaper)](js-apis-wallpaper.md)
- [@ohos.web.webview (Webview)](js-apis-webview.md) - [@ohos.web.webview (Webview)](js-apis-webview.md)
...@@ -286,6 +280,9 @@ ...@@ -286,6 +280,9 @@
- [Timer](js-apis-timer.md) - [Timer](js-apis-timer.md)
- application - application
- [AccessibilityExtensionContext](js-apis-inner-application-accessibilityExtensionContext.md) - [AccessibilityExtensionContext](js-apis-inner-application-accessibilityExtensionContext.md)
- imf
- [InputMethodCommon](js-apis-inputmethod-InputMethodCommon.md)
- Device Management - Device Management
- [@ohos.batteryInfo (Battery Information)](js-apis-battery-info.md) - [@ohos.batteryInfo (Battery Information)](js-apis-battery-info.md)
- [@ohos.batteryStatistics (Battery Statistics)](js-apis-batteryStatistics.md) - [@ohos.batteryStatistics (Battery Statistics)](js-apis-batteryStatistics.md)
...@@ -310,7 +307,7 @@ ...@@ -310,7 +307,7 @@
- [@ohos.settings (Data Item Settings)](js-apis-settings.md) - [@ohos.settings (Data Item Settings)](js-apis-settings.md)
- [@ohos.stationary (Device Status Awareness Framework)](js-apis-stationary.md) - [@ohos.stationary (Device Status Awareness Framework)](js-apis-stationary.md)
- [@ohos.systemCapability (SystemCapability)](js-apis-system-capability.md) - [@ohos.systemCapability (SystemCapability)](js-apis-system-capability.md)
- [@ohos.systemParameterV9 (System Parameter)](js-apis-system-parameterV9.md) - [@ohos.systemParameterEnhance (System Parameter)](js-apis-system-parameterEnhance.md)
- [@ohos.thermal (Thermal Management)](js-apis-thermal.md) - [@ohos.thermal (Thermal Management)](js-apis-thermal.md)
- [@ohos.update (Update)](js-apis-update.md) - [@ohos.update (Update)](js-apis-update.md)
- [@ohos.usbManager (USB Management)](js-apis-usbManager.md) - [@ohos.usbManager (USB Management)](js-apis-usbManager.md)
...@@ -321,10 +318,11 @@ ...@@ -321,10 +318,11 @@
- [@ohos.account.osAccount (OS Account Management)](js-apis-osAccount.md) - [@ohos.account.osAccount (OS Account Management)](js-apis-osAccount.md)
- Custom Management - Custom Management
- [@ohos.configPolicy (Configuration Policy)](js-apis-configPolicy.md) - [@ohos.configPolicy (Configuration Policy)](js-apis-configPolicy.md)
- [@ohos.enterprise.deviceInfo (Device Information Management)](js-apis-enterprise-deviceInfo.md)
- [@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)](js-apis-EnterpriseAdminExtensionAbility.md)
- [@ohos.enterprise.adminManager (Enterprise Device Management)](js-apis-enterprise-adminManager.md) - [@ohos.enterprise.adminManager (Enterprise Device Management)](js-apis-enterprise-adminManager.md)
- [@ohos.enterprise.dateTimeManager (System Time Management)](js-apis-enterprise-dateTimeManager.md) - [@ohos.enterprise.dateTimeManager (System Time Management)](js-apis-enterprise-dateTimeManager.md)
- [@ohos.enterprise.deviceControl (Device Control Management)](js-apis-enterprise-deviceControl.md)
- [@ohos.enterprise.deviceInfo (Device Information Management)](js-apis-enterprise-deviceInfo.md)
- [@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)](js-apis-EnterpriseAdminExtensionAbility.md)
- Language Base Class Library - Language Base Class Library
- [@ohos.buffer (Buffer)](js-apis-buffer.md) - [@ohos.buffer (Buffer)](js-apis-buffer.md)
...@@ -371,6 +369,8 @@ ...@@ -371,6 +369,8 @@
- [@ohos.reminderAgent (Reminder Agent)](js-apis-reminderAgent.md) - [@ohos.reminderAgent (Reminder Agent)](js-apis-reminderAgent.md)
- [@ohos.statfs (statfs)](js-apis-statfs.md) - [@ohos.statfs (statfs)](js-apis-statfs.md)
- [@ohos.systemParameter (System Parameter)](js-apis-system-parameter.md) - [@ohos.systemParameter (System Parameter)](js-apis-system-parameter.md)
- [@ohos.systemTime (System Time and Time Zone)](js-apis-system-time.md)
- [@ohos.usb (USB Management)](js-apis-usb-deprecated.md)
- [@ohos.usbV9 (USB Management)](js-apis-usb.md) - [@ohos.usbV9 (USB Management)](js-apis-usb.md)
- [@system.app (Application Context)](js-apis-system-app.md) - [@system.app (Application Context)](js-apis-system-app.md)
- [@system.battery (Battery Information)](js-apis-system-battery.md) - [@system.battery (Battery Information)](js-apis-system-battery.md)
......
...@@ -921,3 +921,7 @@ Indicates that the SPN displayed has been updated. ...@@ -921,3 +921,7 @@ Indicates that the SPN displayed has been updated.
Indicates the result of applying a quick fix to the application. Indicates the result of applying a quick fix to the application.
- Value: **usual.event.QUICK_FIX_APPLY_RESULT** - Value: **usual.event.QUICK_FIX_APPLY_RESULT**
- Required subscriber permissions: none - Required subscriber permissions: none
## COMMON_EVENT_HTTP_PROXY_CHANGE<sup>10+<sup>
Indicates that the HTTP proxy configuration has changed.
- Value: **usual.event.HTTP_PROXY_CHANGE**
- Required subscriber permissions: none
...@@ -1230,7 +1230,7 @@ SystemCapability.BundleManager.BundleFramework ...@@ -1230,7 +1230,7 @@ SystemCapability.BundleManager.BundleFramework
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------------------------------- | ---- | ----------------------- | | -------- | -------------------------------------------- | ---- | ----------------------- |
| info | [AbilityInfo](js-apis-bundle-AbilityInfo.md) | Yes | Ability information. | | info | [AbilityInfo](js-apis-bundle-AbilityInfo.md) | Yes | Ability information. |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that the ability is enabled, and **false** means the opposite.| | callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.|
**Example** **Example**
...@@ -1603,7 +1603,7 @@ bundle.getNameForUid(uid, (err, data) => { ...@@ -1603,7 +1603,7 @@ bundle.getNameForUid(uid, (err, data) => {
## bundle.getAbilityIcon<sup>8+</sup> <sup>deprecated<sup> ## bundle.getAbilityIcon<sup>8+</sup> <sup>deprecated<sup>
> This API is deprecated since API version 9. You are advised to use [bundleManager.getAbilityIcon](js-apis-bundleManager.md#bundlemanagergetabilityicon) instead. > This API is deprecated since API version 9. You are advised to use [resourceManager.getMediaContent](js-apis-resource-manager.md#getmediacontent9) instead.
getAbilityIcon(bundleName: string, abilityName: string): Promise\<image.PixelMap>; getAbilityIcon(bundleName: string, abilityName: string): Promise\<image.PixelMap>;
...@@ -1646,7 +1646,7 @@ bundle.getAbilityIcon(bundleName, abilityName) ...@@ -1646,7 +1646,7 @@ bundle.getAbilityIcon(bundleName, abilityName)
## bundle.getAbilityIcon<sup>8+</sup> <sup>deprecated<sup> ## bundle.getAbilityIcon<sup>8+</sup> <sup>deprecated<sup>
> This API is deprecated since API version 9. You are advised to use [bundleManager.getAbilityIcon](js-apis-bundleManager.md#bundlemanagergetabilityicon) instead. > This API is deprecated since API version 9. You are advised to use [resourceManager.getMediaContent](js-apis-resource-manager.md#getmediacontent9) instead.
getAbilityIcon(bundleName: string, abilityName: string, callback: AsyncCallback\<image.PixelMap>): void; getAbilityIcon(bundleName: string, abilityName: string, callback: AsyncCallback\<image.PixelMap>): void;
......
...@@ -10,7 +10,7 @@ The **Ability** module provides all level-2 module APIs for developers to export ...@@ -10,7 +10,7 @@ The **Ability** module provides all level-2 module APIs for developers to export
## Modules to Import ## Modules to Import
```ts ```ts
import ability from '@ohos.ability.ability' import ability from '@ohos.ability.ability';
``` ```
**System capability**: SystemCapability.Ability.AbilityBase **System capability**: SystemCapability.Ability.AbilityBase
......
# @ohos.ability.dataUriUtils (dataUriUtils) # @ohos.ability.dataUriUtils (DataUriUtils)
The **DataUriUtils** module provides APIs to process URI objects. 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. The **DataUriUtils** module provides APIs to process URI objects. 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.
...@@ -35,7 +35,7 @@ Obtains the ID attached to the end of a given URI. ...@@ -35,7 +35,7 @@ Obtains the ID attached to the end of a given URI.
**Example** **Example**
```ts ```ts
let id = dataUriUtils.getId("com.example.dataUriUtils/1221"); let id = dataUriUtils.getId('com.example.dataUriUtils/1221');
``` ```
...@@ -66,9 +66,9 @@ Attaches an ID to the end of a given URI. ...@@ -66,9 +66,9 @@ Attaches an ID to the end of a given URI.
```ts ```ts
let id = 1122; let id = 1122;
let uri = dataUriUtils.attachId( let uri = dataUriUtils.attachId(
"com.example.dataUriUtils", 'com.example.dataUriUtils',
id, id,
) );
``` ```
...@@ -96,7 +96,7 @@ Deletes the ID from the end of a given URI. ...@@ -96,7 +96,7 @@ Deletes the ID from the end of a given URI.
**Example** **Example**
```ts ```ts
let uri = dataUriUtils.deleteId("com.example.dataUriUtils/1221") let uri = dataUriUtils.deleteId('com.example.dataUriUtils/1221');
``` ```
...@@ -127,7 +127,7 @@ Updates the ID in a given URI. ...@@ -127,7 +127,7 @@ Updates the ID in a given URI.
```ts ```ts
let id = 1122; let id = 1122;
let uri = dataUriUtils.updateId( let uri = dataUriUtils.updateId(
"com.example.dataUriUtils/1221", 'com.example.dataUriUtils/1221',
id id
) );
``` ```
...@@ -9,7 +9,7 @@ The **ErrorCode** module defines the error codes that may be returned when an ab ...@@ -9,7 +9,7 @@ The **ErrorCode** module defines the error codes that may be returned when an ab
## Modules to Import ## Modules to Import
```ts ```ts
import errorCode from '@ohos.ability.errorCode' import errorCode from '@ohos.ability.errorCode';
``` ```
## ErrorCode ## ErrorCode
......
...@@ -14,7 +14,7 @@ The ParticleAbility module is used to perform operations on abilities of the Dat ...@@ -14,7 +14,7 @@ The ParticleAbility module is used to perform operations on abilities of the Dat
## Modules to Import ## Modules to Import
```ts ```ts
import particleAbility from '@ohos.ability.particleAbility' import particleAbility from '@ohos.ability.particleAbility';
``` ```
## particleAbility.startAbility ## particleAbility.startAbility
...@@ -40,27 +40,27 @@ Observe the following when using this API: ...@@ -40,27 +40,27 @@ Observe the following when using this API:
**Example** **Example**
```ts ```ts
import particleAbility from '@ohos.ability.particleAbility' import particleAbility from '@ohos.ability.particleAbility';
import wantConstant from '@ohos.ability.wantConstant' import wantConstant from '@ohos.ability.wantConstant';
particleAbility.startAbility( particleAbility.startAbility(
{ {
want: want:
{ {
action: "action.system.home", action: 'action.system.home',
entities: ["entity.system.home"], entities: ['entity.system.home'],
type: "MIMETYPE", type: 'MIMETYPE',
flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION,
deviceId: "", deviceId: '',
bundleName: "com.example.Data", bundleName: 'com.example.Data',
abilityName: "EntryAbility", abilityName: 'EntryAbility',
uri: "" uri: ''
}, },
}, },
(error, result) => { (error, result) => {
console.log('particleAbility startAbility errCode:' + error + 'result:' + result) console.error('particleAbility startAbility errCode: ${JSON.stringify(error)}, result: ${JSON.stringify(result)}');
}, },
) );
``` ```
## particleAbility.startAbility ## particleAbility.startAbility
...@@ -91,25 +91,25 @@ Observe the following when using this API: ...@@ -91,25 +91,25 @@ Observe the following when using this API:
**Example** **Example**
```ts ```ts
import particleAbility from '@ohos.ability.particleAbility' import particleAbility from '@ohos.ability.particleAbility';
import wantConstant from '@ohos.ability.wantConstant' import wantConstant from '@ohos.ability.wantConstant';
particleAbility.startAbility( particleAbility.startAbility(
{ {
want: want:
{ {
action: "action.system.home", action: 'action.system.home',
entities: ["entity.system.home"], entities: ['entity.system.home'],
type: "MIMETYPE", type: 'MIMETYPE',
flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION,
deviceId: "", deviceId: '',
bundleName: "com.example.Data", bundleName: 'com.example.Data',
abilityName: "EntryAbility", abilityName: 'EntryAbility',
uri: "" uri: ''
}, },
}, },
).then((data) => { ).then((data) => {
console.info("particleAbility startAbility"); console.info('particleAbility startAbility');
}); });
``` ```
...@@ -130,13 +130,13 @@ Terminates this ParticleAbility. This API uses an asynchronous callback to retur ...@@ -130,13 +130,13 @@ Terminates this ParticleAbility. This API uses an asynchronous callback to retur
**Example** **Example**
```ts ```ts
import particleAbility from '@ohos.ability.particleAbility' import particleAbility from '@ohos.ability.particleAbility';
particleAbility.terminateSelf( particleAbility.terminateSelf(
(error, result) => { (error, result) => {
console.log('particleAbility terminateSelf errCode:' + error + 'result:' + result) console.log('particleAbility terminateSelf errCode: ${JSON.stringify(error)}, result: ${JSON.stringify(result)}');
} }
) );
``` ```
## particleAbility.terminateSelf ## particleAbility.terminateSelf
...@@ -156,10 +156,10 @@ Terminates this ParticleAbility. This API uses a promise to return the result. ...@@ -156,10 +156,10 @@ Terminates this ParticleAbility. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
import particleAbility from '@ohos.ability.particleAbility' import particleAbility from '@ohos.ability.particleAbility';
particleAbility.terminateSelf().then((data) => { particleAbility.terminateSelf().then((data) => {
console.info("particleAbility terminateSelf"); console.info('particleAbility terminateSelf');
}); });
``` ```
...@@ -194,10 +194,10 @@ Observe the following when using this API: ...@@ -194,10 +194,10 @@ Observe the following when using this API:
**Example** **Example**
```ts ```ts
import particleAbility from '@ohos.ability.particleAbility' import particleAbility from '@ohos.ability.particleAbility';
var uri = ""; let uri = '';
particleAbility.acquireDataAbilityHelper(uri) particleAbility.acquireDataAbilityHelper(uri);
``` ```
...@@ -228,17 +228,17 @@ import wantAgent from '@ohos.app.ability.wantAgent'; ...@@ -228,17 +228,17 @@ import wantAgent from '@ohos.app.ability.wantAgent';
function callback(err, data) { function callback(err, data) {
if (err) { if (err) {
console.error("Operation failed cause: " + JSON.stringify(err)); console.error('Operation failed cause: ${JSON.stringify(err)}');
} else { } else {
console.info("Operation succeeded"); console.info('Operation succeeded');
} }
} }
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
bundleName: "com.example.myapplication", bundleName: 'com.example.myapplication',
abilityName: "EntryAbility" abilityName: 'EntryAbility'
} }
], ],
operationType: wantAgent.OperationType.START_ABILITY, operationType: wantAgent.OperationType.START_ABILITY,
...@@ -248,8 +248,8 @@ let wantAgentInfo = { ...@@ -248,8 +248,8 @@ let wantAgentInfo = {
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
let basicContent = { let basicContent = {
title: "title", title: 'title',
text: "text" text: 'text'
}; };
let notificationContent = { let notificationContent = {
contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
...@@ -298,8 +298,8 @@ import wantAgent from '@ohos.app.ability.wantAgent'; ...@@ -298,8 +298,8 @@ import wantAgent from '@ohos.app.ability.wantAgent';
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
bundleName: "com.example.myapplication", bundleName: 'com.example.myapplication',
abilityName: "EntryAbility" abilityName: 'EntryAbility'
} }
], ],
operationType: wantAgent.OperationType.START_ABILITY, operationType: wantAgent.OperationType.START_ABILITY,
...@@ -309,8 +309,8 @@ let wantAgentInfo = { ...@@ -309,8 +309,8 @@ let wantAgentInfo = {
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
let basicContent = { let basicContent = {
title: "title", title: 'title',
text: "text" text: 'text'
}; };
let notificationContent = { let notificationContent = {
contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
...@@ -322,9 +322,9 @@ wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { ...@@ -322,9 +322,9 @@ wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
}; };
let id = 1; let id = 1;
particleAbility.startBackgroundRunning(id, request).then(() => { particleAbility.startBackgroundRunning(id, request).then(() => {
console.info("Operation succeeded"); console.info('Operation succeeded');
}).catch((err) => { }).catch((err) => {
console.error("Operation failed cause: " + JSON.stringify(err)); console.error('Operation failed cause: ${JSON.stringify(err)}');
}); });
}); });
...@@ -351,9 +351,9 @@ import particleAbility from '@ohos.ability.particleAbility'; ...@@ -351,9 +351,9 @@ import particleAbility from '@ohos.ability.particleAbility';
function callback(err, data) { function callback(err, data) {
if (err) { if (err) {
console.error("Operation failed cause: " + JSON.stringify(err)); console.error('Operation failed cause: ${JSON.stringify(err)}');
} else { } else {
console.info("Operation succeeded"); console.info('Operation succeeded');
} }
} }
...@@ -381,9 +381,9 @@ Requests to cancel a continuous task from the system. This API uses a promise to ...@@ -381,9 +381,9 @@ Requests to cancel a continuous task from the system. This API uses a promise to
import particleAbility from '@ohos.ability.particleAbility'; import particleAbility from '@ohos.ability.particleAbility';
particleAbility.cancelBackgroundRunning().then(() => { particleAbility.cancelBackgroundRunning().then(() => {
console.info("Operation succeeded"); console.info('Operation succeeded');
}).catch((err) => { }).catch((err) => {
console.error("Operation failed cause: " + JSON.stringify(err)); console.error('Operation failed cause: ${JSON.stringify(err)}');
}); });
``` ```
...@@ -413,25 +413,25 @@ Observe the following when using this API: ...@@ -413,25 +413,25 @@ Observe the following when using this API:
**Example** **Example**
```ts ```ts
import particleAbility from '@ohos.ability.particleAbility' import particleAbility from '@ohos.ability.particleAbility';
import rpc from '@ohos.rpc' import rpc from '@ohos.rpc';
function onConnectCallback(element, remote) { function onConnectCallback(element, remote) {
console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); console.log('ConnectAbility onConnect remote is proxy: ${(remote instanceof rpc.RemoteProxy)}');
} }
function onDisconnectCallback(element) { function onDisconnectCallback(element) {
console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) console.log('ConnectAbility onDisconnect element.deviceId : ${element.deviceId}');
} }
function onFailedCallback(code) { function onFailedCallback(code) {
console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) console.log('particleAbilityTest ConnectAbility onFailed errCode : ${code}');
} }
var connId = particleAbility.connectAbility( let connId = particleAbility.connectAbility(
{ {
bundleName: "com.ix.ServiceAbility", bundleName: 'com.ix.ServiceAbility',
abilityName: "ServiceAbilityA", abilityName: 'ServiceAbilityA',
}, },
{ {
onConnect: onConnectCallback, onConnect: onConnectCallback,
...@@ -441,9 +441,9 @@ var connId = particleAbility.connectAbility( ...@@ -441,9 +441,9 @@ var connId = particleAbility.connectAbility(
); );
particleAbility.disconnectAbility(connId).then((data) => { particleAbility.disconnectAbility(connId).then((data) => {
console.log(" data: " + data); console.log(' data: ${data}');
}).catch((error) => { }).catch((error) => {
console.log('particleAbilityTest result errCode : ' + error.code) console.log('particleAbilityTest result errCode : ${error.code}');
}); });
``` ```
...@@ -468,21 +468,21 @@ import particleAbility from '@ohos.ability.particleAbility'; ...@@ -468,21 +468,21 @@ import particleAbility from '@ohos.ability.particleAbility';
import rpc from '@ohos.rpc'; import rpc from '@ohos.rpc';
function onConnectCallback(element, remote) { function onConnectCallback(element, remote) {
console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); console.log('ConnectAbility onConnect remote is proxy: ${(remote instanceof rpc.RemoteProxy)}');
} }
function onDisconnectCallback(element) { function onDisconnectCallback(element) {
console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) console.log('ConnectAbility onDisconnect element.deviceId : ${element.deviceId}');
} }
function onFailedCallback(code) { function onFailedCallback(code) {
console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) console.log('particleAbilityTest ConnectAbility onFailed errCode : ${code}');
} }
var connId = particleAbility.connectAbility( let connId = particleAbility.connectAbility(
{ {
bundleName: "com.ix.ServiceAbility", bundleName: 'com.ix.ServiceAbility',
abilityName: "ServiceAbilityA", abilityName: 'ServiceAbilityA',
}, },
{ {
onConnect: onConnectCallback, onConnect: onConnectCallback,
...@@ -492,8 +492,7 @@ var connId = particleAbility.connectAbility( ...@@ -492,8 +492,7 @@ var connId = particleAbility.connectAbility(
); );
particleAbility.disconnectAbility(connId, (err) => { particleAbility.disconnectAbility(connId, (err) => {
console.log("particleAbilityTest disconnectAbility err====>" console.log('particleAbilityTest disconnectAbility err: ${JSON.stringify(err)}');
+ ("json err=") + JSON.stringify(err));
}); });
``` ```
...@@ -519,21 +518,21 @@ import particleAbility from '@ohos.ability.particleAbility'; ...@@ -519,21 +518,21 @@ import particleAbility from '@ohos.ability.particleAbility';
import rpc from '@ohos.rpc'; import rpc from '@ohos.rpc';
function onConnectCallback(element, remote) { function onConnectCallback(element, remote) {
console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); console.log('ConnectAbility onConnect remote is proxy: ${(remote instanceof rpc.RemoteProxy)}');
} }
function onDisconnectCallback(element) { function onDisconnectCallback(element) {
console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) console.log('ConnectAbility onDisconnect element.deviceId : ${element.deviceId}');
} }
function onFailedCallback(code) { function onFailedCallback(code) {
console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) console.log('particleAbilityTest ConnectAbility onFailed errCode : ${code}');
} }
var connId = particleAbility.connectAbility( let connId = particleAbility.connectAbility(
{ {
bundleName: "com.ix.ServiceAbility", bundleName: 'com.ix.ServiceAbility',
abilityName: "ServiceAbilityA", abilityName: 'ServiceAbilityA',
}, },
{ {
onConnect: onConnectCallback, onConnect: onConnectCallback,
...@@ -543,9 +542,9 @@ var connId = particleAbility.connectAbility( ...@@ -543,9 +542,9 @@ var connId = particleAbility.connectAbility(
); );
particleAbility.disconnectAbility(connId).then((data) => { particleAbility.disconnectAbility(connId).then((data) => {
console.log(" data: " + data); console.log(' data: ${data}');
}).catch((error) => { }).catch((error) => {
console.log('particleAbilityTest result errCode : ' + error.code) console.log('particleAbilityTest result errCode : ${error.code}');
}); });
``` ```
......
...@@ -44,7 +44,7 @@ Enumerates the action constants of the **Want** object. **action** specifies the ...@@ -44,7 +44,7 @@ Enumerates the action constants of the **Want** object. **action** specifies the
| INTENT_PARAMS_INTENT | ability.want.params.INTENT | Action of displaying selection options with an action selector. | | 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. | | INTENT_PARAMS_TITLE | ability.want.params.TITLE | Title of the character sequence dialog box used with the action selector. |
| ACTION_FILE_SELECT<sup>7+</sup> | ohos.action.fileSelect | Action of selecting a file. | | ACTION_FILE_SELECT<sup>7+</sup> | ohos.action.fileSelect | Action of selecting a file. |
| PARAMS_STREAM<sup>7+</sup> | ability.params.stream | URI of the data stream associated with the target when the data is sent. | | PARAMS_STREAM<sup>7+</sup> | ability.params.stream | URI of the data stream associated with the target when the data is sent. The value must be an array of the string type. |
| ACTION_APP_ACCOUNT_OAUTH <sup>8+</sup> | ohos.account.appAccount.action.oauth | Action of providing the OAuth service. | | ACTION_APP_ACCOUNT_OAUTH <sup>8+</sup> | ohos.account.appAccount.action.oauth | Action of providing the OAuth service. |
| ACTION_APP_ACCOUNT_AUTH <sup>9+</sup> | account.appAccount.action.auth | Action of providing the authentication service. | | ACTION_APP_ACCOUNT_AUTH <sup>9+</sup> | account.appAccount.action.auth | Action of providing the authentication service. |
| ACTION_MARKET_DOWNLOAD <sup>9+</sup> | ohos.want.action.marketDownload | Action of downloading an application from the application market.<br>**System API**: This is a system API and cannot be called by third-party applications. | | ACTION_MARKET_DOWNLOAD <sup>9+</sup> | ohos.want.action.marketDownload | Action of downloading an application from the application market.<br>**System API**: This is a system API and cannot be called by third-party applications. |
......
...@@ -37,10 +37,10 @@ Creates an **Animator** object. ...@@ -37,10 +37,10 @@ Creates an **Animator** object.
```js ```js
let options = { let options = {
duration: 1500, duration: 1500,
easing: 'friction', easing: "friction",
delay: 0, delay: 0,
fill: 'forwards', fill: "forwards",
direction: 'normal', direction: "normal",
iterations: 3, iterations: 3,
begin: 200.0, begin: 200.0,
end: 400.0 end: 400.0
...@@ -80,10 +80,10 @@ For details about the error codes, see [Animator Error Codes](../errorcodes/erro ...@@ -80,10 +80,10 @@ For details about the error codes, see [Animator Error Codes](../errorcodes/erro
```js ```js
let options = { let options = {
duration: 1500, duration: 1500,
easing: 'friction', easing: "friction",
delay: 0, delay: 0,
fill: 'forwards', fill: "forwards",
direction: 'normal', direction: "normal",
iterations: 3, iterations: 3,
begin: 200.0, begin: 200.0,
end: 400.0 end: 400.0
...@@ -99,7 +99,7 @@ try { ...@@ -99,7 +99,7 @@ try {
play(): void play(): void
Plays this animation. Plays this animation. The animation retains the previous playback state. For example, if the animation is set to **reverse** and paused, it will remain in **reverse** when resumed.
**System capability**: SystemCapability.ArkUI.ArkUI.Full **System capability**: SystemCapability.ArkUI.ArkUI.Full
...@@ -247,16 +247,16 @@ Defines animator options. ...@@ -247,16 +247,16 @@ Defines animator options.
**System capability**: SystemCapability.ArkUI.ArkUI.Full **System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| ---------- | ---------------------------------------- | ---- | ---------------------------------------- | | ---------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| duration | number | Yes | Duration for playing the animation, in milliseconds. The default value is **0**. | | duration | number | Yes | Duration for playing the animation, in milliseconds. |
| easing | string | Yes | Animation interpolation curve. The default value is **ease**. | | easing | string | Yes | Animation interpolation curve. Only the following values are supported:<br>**"linear"**: The animation speed keeps unchanged.<br>**"ease"**: The animation starts slowly, accelerates, and then slows down towards the end. The cubic-bezier curve (0.25, 0.1, 0.25, 1.0) is used.<br>**"ease-in"**: The animation starts at a low speed and then picks up speed until the end. The cubic-bezier curve (0.42, 0.0, 1.0, 1.0) is used.<br>**"ease-out"**: The animation ends at a low speed. The cubic-bezier curve (0.0, 0.0, 0.58, 1.0) is used.<br>**"ease-in-out"**: The animation starts and ends at a low speed. The cubic-bezier curve (0.42, 0.0, 0.58, 1.0) is used.<br>**"fast-out-slow-in"**: The animation uses the standard cubic-bezier curve (0.4, 0.0, 0.2, 1.0).<br>**"linear-out-slow-in"**: The animation uses the deceleration cubic-bezier curve (0.0, 0.0, 0.2, 1.0).<br>**"friction"**: The animation uses the damping cubic-bezier curve (0.2, 0.0, 0.2, 1.0).<br>**"extreme-deceleration"**: The animation uses the extreme deceleration cubic-bezier curve (0.0, 0.0, 0.0, 1.0).<br>**"rhythm"**: The animation uses the rhythm cubic-bezier curve (0.7, 0.0, 0.2, 1.0).<br>**"sharp"**: The animation uses the sharp cubic-bezier curve (0.33, 0.0, 0.67, 1.0).<br>**"smooth"**: The animation uses the smooth cubic-bezier curve (0.4, 0.0, 0.4, 1.0).<br>**cubic-bezier(x1, y1, x2, y2)**: The animation uses the defined cubic-bezier curve, where the value of the input parameters must range from 0 to 1.<br>**steps(number, step-position)**: The animation uses a step curve. The **number** must be set and only an integer is supported. **step-position** is optional. It can be set to **start** or **end**. The default value is **end**.|
| delay | number | Yes | Animation delay duration, in milliseconds. The default value is **0**, indicating that there is no delay. | | delay | number | Yes | Animation delay duration, in milliseconds. Value **0** means that there is no delay. |
| fill | "none" \| "forwards" \| "backwards" \| "both" | Yes | State of the animated target after the animation is executed. The default value is **none**, which means that the target will retain its end state (defined by the last keyframe) after the animation is executed.| | fill | "none" \| "forwards" \| "backwards" \| "both" | Yes | State of the animated target after the animation is executed.<br>**"none"**: No style is applied to the target before or after the animation is executed.<br>**"forwards"**: The target keeps the state at the end of the animation (defined in the last key frame) after the animation is executed.<br>**"backwards"**: The animation uses the value defined in the first key frame during the **animation-delay**. When **animation-direction** is set to **normal** or **alternate**, the value in the **from** key frame is used. When **animation-direction** is set to **reverse** or **alternate-reverse**, the value in the **to** key frame is used.<br>**"both"**: The animation follows the **forwards** and **backwards** rules.|
| direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes | Animation playback mode. The default value is **normal**. | | direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes | Animation playback mode.<br>**"normal"**: plays the animation in forward loop mode.<br>**"reverse"**: plays the animation in reverse loop mode.<br>**"alternate"**: plays the animation in alternating loop mode. When the animation is played for an odd number of times, the playback is in forward direction. When the animation is played for an even number of times, the playback is in reverse direction.<br>**"alternate-reverse"**: plays the animation in reverse alternating loop mode. When the animation is played for an odd number of times, the playback is in reverse direction. When the animation is played for an even number of times, the playback is in forward direction.|
| iterations | number | Yes | Number of times that the animation is played. The default value is **1**. The value **0** means not to play the animation, and **-1** means to play the animation for an unlimited number of times. | | iterations | number | Yes | Number of times that the animation is played. The value **0** means not to play the animation, and **-1** means to play the animation for an unlimited number of times.<br>**NOTE**<br>If this parameter is set to a negative value other than **-1**, the value is invalid. In this case, the animation is played once.|
| begin | number | Yes | Start point of the animation interpolation. The default value is 0. | | begin | number | Yes | Start point of the animation interpolation. |
| end | number | Yes | End point of animation interpolation. The default value is 1. | | end | number | Yes | End point of animation interpolation. |
## Example ## Example
...@@ -280,10 +280,10 @@ export default { ...@@ -280,10 +280,10 @@ export default {
onInit() { onInit() {
let options = { let options = {
duration: 1500, duration: 1500,
easing: 'friction', easing: "friction",
delay: 0, delay: 0,
fill: 'forwards', fill: "forwards",
direction: 'normal', direction: "normal",
iterations: 2, iterations: 2,
begin: 200.0, begin: 200.0,
end: 400.0 end: 400.0
...@@ -293,9 +293,9 @@ export default { ...@@ -293,9 +293,9 @@ export default {
Show() { Show() {
let options1 = { let options1 = {
duration: 1500, duration: 1500,
easing: 'friction', easing: "friction",
delay: 0, delay: 0,
fill: 'forwards', fill: "forwards",
direction: "normal", direction: "normal",
iterations: 2, iterations: 2,
begin: 0, begin: 0,
...@@ -336,10 +336,10 @@ struct AnimatorTest { ...@@ -336,10 +336,10 @@ struct AnimatorTest {
let _this = this let _this = this
this.backAnimator = animator.create({ this.backAnimator = animator.create({
duration: 2000, duration: 2000,
easing: 'ease', easing: "ease",
delay: 0, delay: 0,
fill: 'none', fill: "none",
direction: 'normal', direction: "normal",
iterations: 1, iterations: 1,
begin: 100, begin: 100,
end: 200 end: 200
...@@ -444,10 +444,10 @@ struct AnimatorTest { ...@@ -444,10 +444,10 @@ struct AnimatorTest {
this.flag = false this.flag = false
this.backAnimator.reset({ this.backAnimator.reset({
duration: 5000, duration: 5000,
easing: 'ease-in', easing: "ease-in",
delay: 0, delay: 0,
fill: 'none', fill: "none",
direction: 'normal', direction: "normal",
iterations: 4, iterations: 4,
begin: 100, begin: 100,
end: 300 end: 300
...@@ -513,10 +513,10 @@ This API is deprecated since API version 9. You are advised to use [create<sup>9 ...@@ -513,10 +513,10 @@ This API is deprecated since API version 9. You are advised to use [create<sup>9
```js ```js
let options = { let options = {
duration: 1500, duration: 1500,
easing: 'friction', easing: "friction",
delay: 0, delay: 0,
fill: 'forwards', fill: "forwards",
direction: 'normal', direction: "normal",
iterations: 3, iterations: 3,
begin: 200.0, begin: 200.0,
end: 400.0, end: 400.0,
......
...@@ -28,7 +28,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; ...@@ -28,7 +28,7 @@ import UIAbility from '@ohos.app.ability.UIAbility';
class MyUIAbility extends UIAbility { class MyUIAbility extends UIAbility {
onConfigurationUpdate(config) { onConfigurationUpdate(config) {
console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); console.log('onConfigurationUpdate, config: ${JSON.stringify(config)}');
} }
} }
``` ```
...@@ -55,7 +55,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; ...@@ -55,7 +55,7 @@ import UIAbility from '@ohos.app.ability.UIAbility';
class MyUIAbility extends UIAbility { class MyUIAbility extends UIAbility {
onMemoryLevel(level) { onMemoryLevel(level) {
console.log('onMemoryLevel, level:' + JSON.stringify(level)); console.log('onMemoryLevel, level: ${JSON.stringify(level)}');
} }
} }
``` ```
...@@ -48,7 +48,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; ...@@ -48,7 +48,7 @@ import UIAbility from '@ohos.app.ability.UIAbility';
class MyAbility extends UIAbility { class MyAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
if (launchParam.launchReason === AbilityConstant.LaunchReason.START_ABILITY) { if (launchParam.launchReason === AbilityConstant.LaunchReason.START_ABILITY) {
console.log("The ability has been started by the way of startAbility."); console.log('The ability has been started by the way of startAbility.');
} }
} }
} }
...@@ -74,7 +74,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; ...@@ -74,7 +74,7 @@ import UIAbility from '@ohos.app.ability.UIAbility';
class MyAbility extends UIAbility { class MyAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
if (launchParam.lastExitReason === AbilityConstant.LastExitReason.ABILITY_NOT_RESPONDING) { if (launchParam.lastExitReason === AbilityConstant.LastExitReason.ABILITY_NOT_RESPONDING) {
console.log("The ability has exit last because the ability was not responding."); console.log('The ability has exit last because the ability was not responding.');
} }
} }
} }
...@@ -110,20 +110,22 @@ Enumerates the window modes in which an ability can be displayed at startup. It ...@@ -110,20 +110,22 @@ Enumerates the window modes in which an ability can be displayed at startup. It
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
| Name | Value| Description | | Name | Value| Description |
| --- | --- | --- | | --- | --- | --- |
| WINDOW_MODE_UNDEFINED | 0 | Undefined window mode. | | WINDOW_MODE_UNDEFINED | 0 | Undefined window mode. |
| WINDOW_MODE_FULLSCREEN | 1 | The ability is displayed in full screen. | | 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_PRIMARY | 100 | The left screen in horizontal direction or the upper screen in vertical direction is the primary window. |
| WINDOW_MODE_SPLIT_SECONDARY | 101 | The ability is displayed in the secondary window in split-screen mode. | | WINDOW_MODE_SPLIT_SECONDARY | 101 | The right screen in horizontal direction or the lower screen in vertical direction is the secondary window. |
| WINDOW_MODE_FLOATING | 102 | The ability is displayed in a floating window.| | WINDOW_MODE_FLOATING | 102 | The ability is displayed in a floating window.|
**Example** **Example**
```ts ```ts
let want = { let want = {
bundleName: "com.example.myapplication", bundleName: 'com.example.myapplication',
abilityName: "EntryAbility" abilityName: 'EntryAbility'
}; };
let option = { let option = {
windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FULLSCREEN windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FULLSCREEN
...@@ -131,9 +133,9 @@ let option = { ...@@ -131,9 +133,9 @@ let option = {
// Ensure that the context is obtained. // Ensure that the context is obtained.
this.context.startAbility(want, option).then(()={ this.context.startAbility(want, option).then(()={
console.log("Succeed to start ability."); console.log('Succeed to start ability.');
}).catch((error)=>{ }).catch((error)=>{
console.log("Failed to start ability with error: " + JSON.stringify(error)); console.log('Failed to start ability with error: ${JSON.stringify(error)}');
}); });
``` ```
...@@ -157,7 +159,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; ...@@ -157,7 +159,7 @@ import UIAbility from '@ohos.app.ability.UIAbility';
class MyAbility extends UIAbility { class MyAbility extends UIAbility {
onMemoryLevel(level) { onMemoryLevel(level) {
if (level === AbilityConstant.MemoryLevel.MEMORY_LEVEL_CRITICAL) { if (level === AbilityConstant.MemoryLevel.MEMORY_LEVEL_CRITICAL) {
console.log("The memory of device is critical, please release some memory."); console.log('The memory of device is critical, please release some memory.');
} }
} }
} }
...@@ -209,7 +211,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; ...@@ -209,7 +211,7 @@ import UIAbility from '@ohos.app.ability.UIAbility';
class MyAbility extends UIAbility { class MyAbility extends UIAbility {
onSaveState(reason, wantParam) { onSaveState(reason, wantParam) {
if (reason === AbilityConstant.StateType.CONTINUATION) { if (reason === AbilityConstant.StateType.CONTINUATION) {
console.log("Save the ability data when the ability continuation."); console.log('Save the ability data when the ability continuation.');
} }
return AbilityConstant.OnSaveResult.ALL_AGREE; return AbilityConstant.OnSaveResult.ALL_AGREE;
} }
......
...@@ -49,16 +49,16 @@ import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry ...@@ -49,16 +49,16 @@ import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry
let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
let want = { let want = {
bundleName: "com.example.myapplication", bundleName: 'com.example.myapplication',
abilityName: "EntryAbility" abilityName: 'EntryAbility'
}; };
abilityDelegator.startAbility(want, (err) => { abilityDelegator.startAbility(want, (err) => {
if (err.code !== 0) { if (!err || err.code === 0) {
console.log("Success start ability."); console.log('Success start ability.');
} else { } else {
console.log("Failed start ability, error: " + JSON.stringify(err)); console.log('Failed start ability, error: ${JSON.stringify(err)}');
} }
}) });
``` ```
## AbilityDelegatorRegistry.getArguments ## AbilityDelegatorRegistry.getArguments
...@@ -81,8 +81,8 @@ Obtains an [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs ...@@ -81,8 +81,8 @@ Obtains an [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
let args = AbilityDelegatorRegistry.getArguments(); let args = AbilityDelegatorRegistry.getArguments();
console.info("getArguments bundleName:" + args.bundleName); console.info('getArguments bundleName: ${args.bundleName}');
console.info("getArguments parameters:" + JSON.stringify(args.parameters)); console.info('getArguments parameters: ${JSON.stringify(args.parameters)}');
console.info("getArguments testCaseNames:" + args.testCaseNames); console.info('getArguments testCaseNames: ${args.testCaseNames}');
console.info("getArguments testRunnerClassName:" + args.testRunnerClassName); console.info('getArguments testRunnerClassName: ${args.testRunnerClassName}');
``` ```
...@@ -11,7 +11,7 @@ The **AbilityLifecycleCallback** module defines the callbacks to receive lifecyc ...@@ -11,7 +11,7 @@ The **AbilityLifecycleCallback** module defines the callbacks to receive lifecyc
## Modules to Import ## Modules to Import
```ts ```ts
import AbilityLifecycleCallback from "@ohos.app.ability.AbilityLifecycleCallback"; import AbilityLifecycleCallback from '@ohos.app.ability.AbilityLifecycleCallback';
``` ```
...@@ -25,15 +25,15 @@ Called when an ability is created. ...@@ -25,15 +25,15 @@ Called when an ability is created.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| | ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.|
**Example** **Example**
```ts ```ts
let abilityLifecycleCallback = { let abilityLifecycleCallback = {
onAbilityCreate(ability){ onAbilityCreate(ability){
console.log("AbilityLifecycleCallback onAbilityCreate."); console.log('AbilityLifecycleCallback onAbilityCreate.');
} }
}; };
``` ```
...@@ -48,16 +48,16 @@ Called when the window stage of an ability is created. ...@@ -48,16 +48,16 @@ Called when the window stage of an ability is created.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| | ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
**Example** **Example**
```ts ```ts
let abilityLifecycleCallback = { let abilityLifecycleCallback = {
onWindowStageCreate(ability, windowStage){ onWindowStageCreate(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageCreate."); console.log('AbilityLifecycleCallback onWindowStageCreate.');
} }
}; };
``` ```
...@@ -72,16 +72,16 @@ Called when the window stage of an ability gains focus. ...@@ -72,16 +72,16 @@ Called when the window stage of an ability gains focus.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| | ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
**Example** **Example**
```ts ```ts
let abilityLifecycleCallback = { let abilityLifecycleCallback = {
onWindowStageActive(ability, windowStage){ onWindowStageActive(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageActive."); console.log('AbilityLifecycleCallback onWindowStageActive.');
} }
}; };
``` ```
...@@ -96,16 +96,16 @@ Called when the window stage of an ability loses focus. ...@@ -96,16 +96,16 @@ Called when the window stage of an ability loses focus.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| | ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
**Example** **Example**
```ts ```ts
let abilityLifecycleCallback = { let abilityLifecycleCallback = {
onWindowStageInactive(ability, windowStage){ onWindowStageInactive(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageInactive."); console.log('AbilityLifecycleCallback onWindowStageInactive.');
} }
}; };
``` ```
...@@ -120,16 +120,16 @@ Called when the window stage of an ability is destroyed. ...@@ -120,16 +120,16 @@ Called when the window stage of an ability is destroyed.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| | ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
**Example** **Example**
```ts ```ts
let abilityLifecycleCallback = { let abilityLifecycleCallback = {
onWindowStageDestroy(ability, windowStage){ onWindowStageDestroy(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageDestroy."); console.log('AbilityLifecycleCallback onWindowStageDestroy.');
} }
}; };
``` ```
...@@ -144,15 +144,15 @@ Called when an ability is destroyed. ...@@ -144,15 +144,15 @@ Called when an ability is destroyed.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| | ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.|
**Example** **Example**
```ts ```ts
let abilityLifecycleCallback = { let abilityLifecycleCallback = {
onAbilityDestroy(ability){ onAbilityDestroy(ability){
console.log("AbilityLifecycleCallback onAbilityDestroy."); console.log('AbilityLifecycleCallback onAbilityDestroy.');
} }
}; };
``` ```
...@@ -167,15 +167,15 @@ Called when an ability is switched from the background to the foreground. ...@@ -167,15 +167,15 @@ Called when an ability is switched from the background to the foreground.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| | ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.|
**Example** **Example**
```ts ```ts
let abilityLifecycleCallback = { let abilityLifecycleCallback = {
onAbilityForeground(ability){ onAbilityForeground(ability){
console.log("AbilityLifecycleCallback onAbilityForeground."); console.log('AbilityLifecycleCallback onAbilityForeground.');
} }
}; };
``` ```
...@@ -190,15 +190,15 @@ Called when an ability is switched from the foreground to the background. ...@@ -190,15 +190,15 @@ Called when an ability is switched from the foreground to the background.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| | ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.|
**Example** **Example**
```ts ```ts
let abilityLifecycleCallback = { let abilityLifecycleCallback = {
onAbilityBackground(ability){ onAbilityBackground(ability){
console.log("AbilityLifecycleCallback onAbilityBackground."); console.log('AbilityLifecycleCallback onAbilityBackground.');
} }
}; };
``` ```
...@@ -213,15 +213,15 @@ Called when an ability is continued on another device. ...@@ -213,15 +213,15 @@ Called when an ability is continued on another device.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| | ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.|
**Example** **Example**
```ts ```ts
let abilityLifecycleCallback = { let abilityLifecycleCallback = {
onAbilityContinue(ability){ onAbilityContinue(ability){
console.log("AbilityLifecycleCallback onAbilityContinue."); console.log('AbilityLifecycleCallback onAbilityContinue.');
} }
}; };
``` ```
...@@ -232,52 +232,52 @@ let abilityLifecycleCallback = { ...@@ -232,52 +232,52 @@ let abilityLifecycleCallback = {
MyFirstAbility.ts MyFirstAbility.ts
```ts ```ts
import AbilityLifecycleCallback from "@ohos.app.ability.AbilityLifecycleCallback"; import AbilityLifecycleCallback from '@ohos.app.ability.AbilityLifecycleCallback';
import AbilityStage from "@ohos.app.ability.AbilityStage"; import AbilityStage from '@ohos.app.ability.AbilityStage';
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
// Declare the ability lifecycle callbacks. A listener can be registered in applicationContext only after all the callbacks are configured. // Declare the ability lifecycle callbacks. A listener can be registered in applicationContext only after all the callbacks are configured.
let abilityLifecycleCallback = { let abilityLifecycleCallback = {
onAbilityCreate(ability){ onAbilityCreate(ability){
console.log("AbilityLifecycleCallback onAbilityCreate."); console.log('AbilityLifecycleCallback onAbilityCreate.');
}, },
onWindowStageCreate(ability, windowStage){ onWindowStageCreate(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageCreate."); console.log('AbilityLifecycleCallback onWindowStageCreate.');
}, },
onWindowStageActive(ability, windowStage){ onWindowStageActive(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageActive."); console.log('AbilityLifecycleCallback onWindowStageActive.');
}, },
onWindowStageInactive(ability, windowStage){ onWindowStageInactive(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageInactive."); console.log('AbilityLifecycleCallback onWindowStageInactive.');
}, },
onWindowStageDestroy(ability, windowStage){ onWindowStageDestroy(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageDestroy."); console.log('AbilityLifecycleCallback onWindowStageDestroy.');
}, },
onAbilityDestroy(ability){ onAbilityDestroy(ability){
console.log("AbilityLifecycleCallback onAbilityDestroy."); console.log('AbilityLifecycleCallback onAbilityDestroy.');
}, },
onAbilityForeground(ability){ onAbilityForeground(ability){
console.log("AbilityLifecycleCallback onAbilityForeground."); console.log('AbilityLifecycleCallback onAbilityForeground.');
}, },
onAbilityBackground(ability){ onAbilityBackground(ability){
console.log("AbilityLifecycleCallback onAbilityBackground."); console.log('AbilityLifecycleCallback onAbilityBackground.');
}, },
onAbilityContinue(ability){ onAbilityContinue(ability){
console.log("AbilityLifecycleCallback onAbilityContinue."); console.log('AbilityLifecycleCallback onAbilityContinue.');
} }
}; };
export default class MyFirstAbility extends UIAbility { export default class MyFirstAbility extends UIAbility {
onCreate() { onCreate() {
console.log("MyAbilityStage onCreate"); console.log('MyAbilityStage onCreate');
// 1. Obtain applicationContext through the context attribute. // 1. Obtain applicationContext through the context attribute.
let applicationContext = this.context.getApplicationContext(); let applicationContext = this.context.getApplicationContext();
// 2. Register the listener for the ability lifecycle changes through the applicationContext object. // 2. Register the listener for the ability lifecycle changes through the applicationContext object.
try { try {
globalThis.lifecycleId = applicationContext.on("abilityLifecycle", abilityLifecycleCallback); globalThis.lifecycleId = applicationContext.on('abilityLifecycle', abilityLifecycleCallback);
console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId)); console.log('registerAbilityLifecycleCallback number: ${JSON.stringify(lifecycleId)}');
} catch (paramError) { } catch (paramError) {
console.log("error: " + paramError.code + " ," + paramError.message); console.log('error: ${paramError.code}, ${paramError.message}');
} }
} }
} }
...@@ -285,17 +285,17 @@ export default class MyFirstAbility extends UIAbility { ...@@ -285,17 +285,17 @@ export default class MyFirstAbility extends UIAbility {
MySecondAbility.ts MySecondAbility.ts
```ts ```ts
import UIAbility from "ohos.app.ability.UIAbility"; import UIAbility from 'ohos.app.ability.UIAbility';
export default class MySecondAbility extends UIAbility { export default class MySecondAbility extends UIAbility {
onDestroy() { onDestroy() {
let applicationContext = this.context.getApplicationContext(); let applicationContext = this.context.getApplicationContext();
// 3. Deregister the listener for the environment changes through the applicationContext object. // 3. Deregister the listener for the ability lifecycle changes through the applicationContext object.
applicationContext.off("abilityLifecycle", globalThis.lifecycleId, (error) => { applicationContext.off('abilityLifecycle', globalThis.lifecycleId, (error) => {
if (error.code != 0) { if (error && error.code !== 0) {
console.log("unregisterAbilityLifecycleCallback failed, error: " + JSON.stringify(error)); console.log('unregisterAbilityLifecycleCallback fail, error: ${JSON.stringify(error)}');
} else { } else {
console.log("unregisterAbilityLifecycleCallback success."); console.log('unregisterAbilityLifecycleCallback success.');
} }
}); });
} }
......
...@@ -30,7 +30,7 @@ import AbilityStage from '@ohos.app.ability.AbilityStage'; ...@@ -30,7 +30,7 @@ import AbilityStage from '@ohos.app.ability.AbilityStage';
class MyAbilityStage extends AbilityStage { class MyAbilityStage extends AbilityStage {
onCreate() { onCreate() {
console.log("MyAbilityStage.onCreate is called"); console.log('MyAbilityStage.onCreate is called');
} }
} }
``` ```
...@@ -63,8 +63,8 @@ import AbilityStage from '@ohos.app.ability.AbilityStage'; ...@@ -63,8 +63,8 @@ import AbilityStage from '@ohos.app.ability.AbilityStage';
class MyAbilityStage extends AbilityStage { class MyAbilityStage extends AbilityStage {
onAcceptWant(want) { onAcceptWant(want) {
console.log("MyAbilityStage.onAcceptWant called"); console.log('MyAbilityStage.onAcceptWant called');
return "com.example.test"; return 'com.example.test';
} }
} }
``` ```
...@@ -91,7 +91,7 @@ import AbilityStage from '@ohos.app.ability.AbilityStage'; ...@@ -91,7 +91,7 @@ import AbilityStage from '@ohos.app.ability.AbilityStage';
class MyAbilityStage extends AbilityStage { class MyAbilityStage extends AbilityStage {
onConfigurationUpdate(config) { onConfigurationUpdate(config) {
console.log('onConfigurationUpdate, language:' + config.language); console.log('onConfigurationUpdate, language: ${config.language}');
} }
} }
``` ```
...@@ -117,7 +117,7 @@ import AbilityStage from '@ohos.app.ability.AbilityStage'; ...@@ -117,7 +117,7 @@ import AbilityStage from '@ohos.app.ability.AbilityStage';
class MyAbilityStage extends AbilityStage { class MyAbilityStage extends AbilityStage {
onMemoryLevel(level) { onMemoryLevel(level) {
console.log('onMemoryLevel, level:' + JSON.stringify(level)); console.log('onMemoryLevel, level: ${JSON.stringify(level)}');
} }
} }
``` ```
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册