提交 f05fa3cc 编写于 作者: Y yuyaozhi 提交者: Gitee

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

Signed-off-by: Nyuyaozhi <yuyaozhi@huawei.com>
...@@ -13,3 +13,6 @@ ...@@ -13,3 +13,6 @@
*.so filter=lfs diff=lfs merge=lfs -text *.so filter=lfs diff=lfs merge=lfs -text
*.bin filter=lfs diff=lfs merge=lfs -text *.bin filter=lfs diff=lfs merge=lfs -text
*.dll filter=lfs diff=lfs merge=lfs -text *.dll filter=lfs diff=lfs merge=lfs -text
OpenHarmony_Icons.zip filter=lfs diff=lfs merge=lfs -text
zip filter=lfs diff=lfs merge=lfs -text
figures/OpenHarmony_Icons.zip filter=lfs diff=lfs merge=lfs -text
...@@ -129,11 +129,38 @@ zh-cn/device-dev/subsystems/subsys-toolchain-bytrace-guide.md @Austin23 ...@@ -129,11 +129,38 @@ zh-cn/device-dev/subsystems/subsys-toolchain-bytrace-guide.md @Austin23
zh-cn/device-dev/subsystems/subsys-toolchain-hdc-guide.md @Austin23 zh-cn/device-dev/subsystems/subsys-toolchain-hdc-guide.md @Austin23
zh-cn/device-dev/subsystems/subsys-toolchain-hiperf.md @Austin23 zh-cn/device-dev/subsystems/subsys-toolchain-hiperf.md @Austin23
zh-cn/device-dev/subsystems/subsys-xts-guide.md @Austin23 zh-cn/device-dev/subsystems/subsys-xts-guide.md @Austin23
zh-cn/application-dev/quick-start/arkts-get-started.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-basic-syntax-overview.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-declarative-ui-description.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-create-custom-components.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-page-custom-components-lifecycle.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-builder.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-builderparam.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-style.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-extend.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-statestyles.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-state-management-overview.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-state.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-prop.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-link.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-provide-and-consume.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-application-state-management-overview.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-localstorage.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-appstorage.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-persiststorage.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-environment.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-other-state-mgmt-functions-overview.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-watch.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-two-way-sync.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-rendering-control-overview.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-rendering-control-ifelse.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-rendering-control-foreach.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/quick-start/arkts-rendering-control-lazyforeach.md @HelloCrease @tomatodevboy @s10021109
zh-cn/application-dev/ability/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/ability/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen
zh-cn/application-dev/IDL/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/IDL/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen
zh-cn/application-dev/device-usage-statistics/ @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 zh-cn/application-dev/device-usage-statistics/ @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/ui/ @HelloCrease @huaweimaxuchu @tomatodevboy @niulihua zh-cn/application-dev/ui/ @HelloCrease @tomatodevboy @niulihua
zh-cn/application-dev/notification/ @RayShih @jayleehw @li-weifeng2 @currydavids zh-cn/application-dev/notification/ @RayShih @jayleehw @li-weifeng2 @currydavids
zh-cn/application-dev/windowmanager/ @ge-yafang @zhangqiang183 @zhouyaoying @zxg-gitee @nobuggers zh-cn/application-dev/windowmanager/ @ge-yafang @zhangqiang183 @zhouyaoying @zxg-gitee @nobuggers
zh-cn/application-dev/webgl/ @zengyawen @zhangqiang183 @wind_zj @zxg-gitee zh-cn/application-dev/webgl/ @zengyawen @zhangqiang183 @wind_zj @zxg-gitee
...@@ -208,8 +235,8 @@ zh-cn/application-dev/device/vibrator-overview.md @ningningW @hellohyh001 @butte ...@@ -208,8 +235,8 @@ zh-cn/application-dev/device/vibrator-overview.md @ningningW @hellohyh001 @butte
zh-cn/application-dev/device/vibrator-guidelines.md @ningningW @hellohyh001 @butterls @star-wind-snow-and-rain zh-cn/application-dev/device/vibrator-guidelines.md @ningningW @hellohyh001 @butterls @star-wind-snow-and-rain
zh-cn/application-dev/device/sample-server-overview.md @ningningW @hughes802 @zhangzhengxue @mamba-ting zh-cn/application-dev/device/sample-server-overview.md @ningningW @hughes802 @zhangzhengxue @mamba-ting
zh-cn/application-dev/device/sample-server-guidelines.md @ningningW @hughes802 @zhangzhengxue @mamba-ting zh-cn/application-dev/device/sample-server-guidelines.md @ningningW @hughes802 @zhangzhengxue @mamba-ting
zh-cn/application-dev/reference/arkui-js/ @HelloCrease @huaweimaxuchu @niulihua @tomatodevboy zh-cn/application-dev/reference/arkui-js/ @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/arkui-ts/ @HelloCrease @huaweimaxuchu @niulihua @tomatodevboy zh-cn/application-dev/reference/arkui-ts/ @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/native-lib @zengyawen @gongjunsong @liwentao_uiw @BlackStone zh-cn/application-dev/reference/native-lib @zengyawen @gongjunsong @liwentao_uiw @BlackStone
zh-cn/application-dev/quick-start/start-overview.md @ge-yafang zh-cn/application-dev/quick-start/start-overview.md @ge-yafang
zh-cn/application-dev/quick-start/start-with-ets-stage.md @ge-yafang zh-cn/application-dev/quick-start/start-with-ets-stage.md @ge-yafang
...@@ -241,7 +268,7 @@ zh-cn/application-dev/quick-start/arkts-state-mgmt-application-level.md @gaoyong ...@@ -241,7 +268,7 @@ zh-cn/application-dev/quick-start/arkts-state-mgmt-application-level.md @gaoyong
zh-cn/application-dev/quick-start/arkts-dynamic-ui-elememt-building.md @gaoyong @niejiteng @jumozhanjiang @HelloCrease zh-cn/application-dev/quick-start/arkts-dynamic-ui-elememt-building.md @gaoyong @niejiteng @jumozhanjiang @HelloCrease
zh-cn/application-dev/quick-start/arkts-rendering-control.md @gaoyong @niejiteng @jumozhanjiang @HelloCrease zh-cn/application-dev/quick-start/arkts-rendering-control.md @gaoyong @niejiteng @jumozhanjiang @HelloCrease
zh-cn/application-dev/quick-start/arkts-restrictions-and-extensions.md @gaoyong @niejiteng @jumozhanjiang @HelloCrease zh-cn/application-dev/quick-start/arkts-restrictions-and-extensions.md @gaoyong @niejiteng @jumozhanjiang @HelloCrease
zh-cn/application-dev/napi/napi-guidelines.md @RayShih @huaweimaxuchu @niulihua @tomatodevboy zh-cn/application-dev/napi/napi-guidelines.md @RayShih @niulihua @tomatodevboy
zh-cn/application-dev/napi/drawing-guidelines.md @zengyawen @zhangqiang183 @wind_zj @zxg-gitee zh-cn/application-dev/napi/drawing-guidelines.md @zengyawen @zhangqiang183 @wind_zj @zxg-gitee
zh-cn/application-dev/napi/rawfile-guidelines.md @ningningW @Buda-Liu @budda-wang @yangqing3 zh-cn/application-dev/napi/rawfile-guidelines.md @ningningW @Buda-Liu @budda-wang @yangqing3
zh-cn/application-dev/reference/js-service-widget-ui/ @HelloCrease zh-cn/application-dev/reference/js-service-widget-ui/ @HelloCrease
...@@ -258,7 +285,7 @@ zh-cn/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md @little ...@@ -258,7 +285,7 @@ zh-cn/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md @little
zh-cn/application-dev/reference/apis/js-apis-abilityrunninginfo.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-abilityrunninginfo.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-abilitystagecontext.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-abilitystagecontext.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md @mupceet @RayShih @mupceet @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md @mupceet @RayShih @mupceet @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-animator.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-animator.md @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-appAccount.md @nianCode @zengyawen @JiDong-CS @murphy1984 zh-cn/application-dev/reference/apis/js-apis-appAccount.md @nianCode @zengyawen @JiDong-CS @murphy1984
zh-cn/application-dev/reference/apis/js-apis-application-ability.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-application-ability.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-application-abilityConstant.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-application-abilityConstant.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
...@@ -393,7 +420,7 @@ zh-cn/application-dev/reference/apis/js-apis-list.md @gongjunsong @ge-yafang @fl ...@@ -393,7 +420,7 @@ zh-cn/application-dev/reference/apis/js-apis-list.md @gongjunsong @ge-yafang @fl
zh-cn/application-dev/reference/apis/js-apis-logs.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-logs.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-media.md @liuyuehua1 @zengyawen @xxb-wzy @currydavids zh-cn/application-dev/reference/apis/js-apis-media.md @liuyuehua1 @zengyawen @xxb-wzy @currydavids
zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-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 @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 @yuanxinying @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
...@@ -412,13 +439,13 @@ zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @nianCode @zengya ...@@ -412,13 +439,13 @@ zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @nianCode @zengya
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
zh-cn/application-dev/reference/apis/js-apis-processrunninginfo.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-processrunninginfo.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-processrunninginformation.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-processrunninginformation.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-prompt.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-prompt.md @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-queue.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-queue.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-radio.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-radio.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @jayleehw @RayShih @li-weifeng2 @currydavids zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @jayleehw @RayShih @li-weifeng2 @currydavids
zh-cn/application-dev/reference/apis/js-apis-request.md @feng-aiwen @ningningW @nagexiucai @murphy1984 zh-cn/application-dev/reference/apis/js-apis-request.md @feng-aiwen @ningningW @nagexiucai @murphy1984
zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @Buda-Liu @ningningW @mengjingzhimo @yangqing3 zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @Buda-Liu @ningningW @mengjingzhimo @yangqing3
zh-cn/application-dev/reference/apis/js-apis-router.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-router.md @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-rpc.md @xuepianpian @RayShih @zhaopeng_gitee @vagrant_world zh-cn/application-dev/reference/apis/js-apis-rpc.md @xuepianpian @RayShih @zhaopeng_gitee @vagrant_world
zh-cn/application-dev/reference/apis/js-apis-runninglock.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-runninglock.md @aqxyjay @zengyawen @aqxyjay @alien0208
zh-cn/application-dev/reference/apis/js-apis-screen.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers zh-cn/application-dev/reference/apis/js-apis-screen.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers
...@@ -427,14 +454,14 @@ zh-cn/application-dev/reference/apis/js-apis-securityLabel.md @panqinxu @zengyaw ...@@ -427,14 +454,14 @@ zh-cn/application-dev/reference/apis/js-apis-securityLabel.md @panqinxu @zengyaw
zh-cn/application-dev/reference/apis/js-apis-sensor.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain zh-cn/application-dev/reference/apis/js-apis-sensor.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain
zh-cn/application-dev/reference/apis/js-apis-service-extension-ability.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-service-extension-ability.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-settings.md @tetex @ge-yafang @cnzhaoxiaohu @anning7 zh-cn/application-dev/reference/apis/js-apis-settings.md @xue-seu @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-sim.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-sim.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-sms.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-sms.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-socket.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-socket.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-stack.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-stack.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-statfs.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-statfs.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-storage-statistics.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-storage-statistics.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-system-app.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-system-app.md @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-system-battery.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-system-battery.md @aqxyjay @zengyawen @aqxyjay @alien0208
zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125
zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208
...@@ -445,14 +472,14 @@ zh-cn/application-dev/reference/apis/js-apis-system-device.md @mupceet @zengyawe ...@@ -445,14 +472,14 @@ zh-cn/application-dev/reference/apis/js-apis-system-device.md @mupceet @zengyawe
zh-cn/application-dev/reference/apis/js-apis-system-fetch.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-system-fetch.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-system-file.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-system-file.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-system-location.md @cheng_guohong @RayShih @cheng_guohong @xiangkejin123 zh-cn/application-dev/reference/apis/js-apis-system-location.md @cheng_guohong @RayShih @cheng_guohong @xiangkejin123
zh-cn/application-dev/reference/apis/js-apis-system-mediaquery.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-system-mediaquery.md @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-system-network.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-system-network.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-system-notification.md @jayleehw @RayShih @li-weifeng2 @currydavids zh-cn/application-dev/reference/apis/js-apis-system-notification.md @jayleehw @RayShih @li-weifeng2 @currydavids
zh-cn/application-dev/reference/apis/js-apis-system-package.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-system-package.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-system-parameter.md @mupceet @zengyawen @handyohos @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-system-parameter.md @mupceet @zengyawen @handyohos @nan-xiansen
zh-cn/application-dev/reference/apis/js-apis-system-prompt.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-system-prompt.md @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-system-request.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-system-request.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-system-router.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-system-router.md @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-system-sensor.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain zh-cn/application-dev/reference/apis/js-apis-system-sensor.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain
zh-cn/application-dev/reference/apis/js-apis-system-storage.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-system-storage.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-system-time.md @feng-aiwen @ningningW @illybyy @murphy1984 zh-cn/application-dev/reference/apis/js-apis-system-time.md @feng-aiwen @ningningW @illybyy @murphy1984
...@@ -534,7 +561,7 @@ zh-cn/application-dev/reference/apis/js-apis-configPolicy.md @liuzuming @ningnin ...@@ -534,7 +561,7 @@ zh-cn/application-dev/reference/apis/js-apis-configPolicy.md @liuzuming @ningnin
zh-cn/application-dev/reference/apis/js-apis-cooperate.md @yuanxinying @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 @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-distributedBundle.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-distributedBundle.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
...@@ -555,11 +582,11 @@ zh-cn/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md @stone2050 ...@@ -555,11 +582,11 @@ zh-cn/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md @stone2050
zh-cn/application-dev/reference/apis/js-apis-inputmethod-subtype.md @feng-aiwen @ningningW @SuperShrimp @murphy1984 zh-cn/application-dev/reference/apis/js-apis-inputmethod-subtype.md @feng-aiwen @ningningW @SuperShrimp @murphy1984
zh-cn/application-dev/reference/apis/js-apis-installer.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-installer.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-launcherBundleManager.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-launcherBundleManager.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-matrix4.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-matrix4.md @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-net-ethernet.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-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 @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceStandby.md @chenmingJay @ningningW @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceStandby.md @chenmingJay @ningningW @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001
...@@ -572,7 +599,12 @@ zh-cn/application-dev/reference/apis/js-apis-system-parameterV9.md @mupceet @zen ...@@ -572,7 +599,12 @@ zh-cn/application-dev/reference/apis/js-apis-system-parameterV9.md @mupceet @zen
zh-cn/application-dev/reference/apis/js-apis-tagSession.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-tagSession.md @cheng_guohong @RayShih @cheng_guohong @quanli125
zh-cn/application-dev/reference/apis/js-apis-userFileManager.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-userFileManager.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md @gaoyong @zengyawen @niejiteng @jumozhanjiang
zh-cn/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-font.md @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-plugincomponent.md @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-uiappearance.md @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/errorcodes/errorcode-ability.md @RayShih zh-cn/application-dev/reference/errorcodes/errorcode-ability.md @RayShih
zh-cn/application-dev/reference/errorcodes/errorcode-access-token.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-access-token.md @zengyawen
zh-cn/application-dev/reference/errorcodes/errorcode-accessibility.md @RayShih zh-cn/application-dev/reference/errorcodes/errorcode-accessibility.md @RayShih
......
# OpenHarmony IDL Specifications and User Guide # IDL Specifications and User Guide
## IDL Overview ## IDL Overview
To ensure successful communications between the client and server, interfaces recognized by both parties must be defined. The OpenHarmony Interface Definition Language (IDL) is a tool for defining such interfaces. OpenHarmony IDL decomposes objects to be transferred into primitives that can be understood by the operating system and encapsulates cross-boundary objects based on developers' requirements. To ensure successful communications between the client and server, interfaces recognized by both parties must be defined. The OpenHarmony Interface Definition Language (IDL) is a tool for defining such interfaces. OpenHarmony IDL decomposes objects to be transferred into primitives that can be understood by the operating system and encapsulates cross-boundary objects based on developers' requirements.
......
...@@ -4,18 +4,16 @@ ...@@ -4,18 +4,16 @@
- About OpenHarmony - About OpenHarmony
- [OpenHarmony Project](../OpenHarmony-Overview.md) - [OpenHarmony Project](../OpenHarmony-Overview.md)
- [Glossary](../glossary.md) - [Glossary](../glossary.md)
- [OpenHarmony Release Notes](../release-notes/Readme.md) - [Release Notes](../release-notes/Readme.md)
- Quick Start - Quick Start
- Getting Started - Getting Started
- [Before You Start](quick-start/start-overview.md) - [Before You Start](quick-start/start-overview.md)
- [Getting Started with ArkTS in Stage Model](quick-start/start-with-ets-stage.md) - [Getting Started with ArkTS in Stage Model](quick-start/start-with-ets-stage.md)
- [Getting Started with ArkTS in FA Model](quick-start/start-with-ets-fa.md)
- [Getting Started with JavaScript in FA Model](quick-start/start-with-js-fa.md)
- Development Fundamentals - Development Fundamentals
- Application Package Fundamentals - Application Package Fundamentals
- [Application Package Overview](quick-start/application-package-overview.md) - [Application Package Overview](quick-start/application-package-overview.md)
- Application Package Structure - Application Package Structure
- [Application Package Structure in Stage Model)](quick-start/application-package-structure-stage.md) - [Application Package Structure in Stage Model](quick-start/application-package-structure-stage.md)
- [Application Package Structure in FA Model](quick-start/application-package-structure-fa.md) - [Application Package Structure in FA Model](quick-start/application-package-structure-fa.md)
- Multi-HAP Mechanism - Multi-HAP Mechanism
- [Multi-HAP Design Objectives](quick-start/multi-hap-objective.md) - [Multi-HAP Design Objectives](quick-start/multi-hap-objective.md)
...@@ -37,9 +35,9 @@ ...@@ -37,9 +35,9 @@
- Application Configuration Files in FA Model - Application Configuration Files in FA Model
- [Application Configuration File Overview (FA Model)](quick-start/application-configuration-file-overview-fa.md) - [Application Configuration File Overview (FA Model)](quick-start/application-configuration-file-overview-fa.md)
- [Internal Structure of the app Tag](quick-start/app-structure.md) - [Internal Structure of the app Tag](quick-start/app-structure.md)
- [Internal structure of deviceConfig Tag](quick-start/deviceconfig-structure.md) - [Internal Structure of the deviceConfig Tag](quick-start/deviceconfig-structure.md)
- [Internal Structure of the module Tag](quick-start/module-structure.md) - [Internal Structure of the module Tag](quick-start/module-structure.md)
- [Resource Categories and Access](quick-start/resource-categories-and-access.md) - [Resource Categories and Access](quick-start/resource-categories-and-access.md)
- Learning ArkTS - Learning ArkTS
- [Getting Started with ArkTS](quick-start/arkts-get-started.md) - [Getting Started with ArkTS](quick-start/arkts-get-started.md)
- Basic Syntax - Basic Syntax
...@@ -49,7 +47,7 @@ ...@@ -49,7 +47,7 @@
- [Creating a Custom Component](quick-start/arkts-create-custom-components.md) - [Creating a Custom Component](quick-start/arkts-create-custom-components.md)
- [Page and Custom Component Lifecycle](quick-start/arkts-page-custom-components-lifecycle.md) - [Page and Custom Component Lifecycle](quick-start/arkts-page-custom-components-lifecycle.md)
- [\@Builder: Custom Builder Function](quick-start/arkts-builder.md) - [\@Builder: Custom Builder Function](quick-start/arkts-builder.md)
- [\@BuilderParam: @Builder Function Reference](quick-start/arkts-builderparam.md) - [\@BuilderParam: \@Builder Function Reference](quick-start/arkts-builderparam.md)
- [\@Styles: Definition of Resusable Styles](quick-start/arkts-style.md) - [\@Styles: Definition of Resusable Styles](quick-start/arkts-style.md)
- [\@Extend: Extension of Built-in Components](quick-start/arkts-extend.md) - [\@Extend: Extension of Built-in Components](quick-start/arkts-extend.md)
- [stateStyles: Polymorphic Style](quick-start/arkts-statestyles.md) - [stateStyles: Polymorphic Style](quick-start/arkts-statestyles.md)
...@@ -72,7 +70,7 @@ ...@@ -72,7 +70,7 @@
- [\@Watch: Getting Notified of State Variable Changes](quick-start/arkts-watch.md) - [\@Watch: Getting Notified of State Variable Changes](quick-start/arkts-watch.md)
- [$$ Syntax: Two-Way Synchronization of Built-in Components](quick-start/arkts-two-way-sync.md) - [$$ Syntax: Two-Way Synchronization of Built-in Components](quick-start/arkts-two-way-sync.md)
- Rendering Control - Rendering Control
- [Rendering Control Overview](quick-start/arkts-rendering-control-overview.md) - [Overview of Rendering Control](quick-start/arkts-rendering-control-overview.md)
- [if/else: Conditional Rendering](quick-start/arkts-rendering-control-ifelse.md) - [if/else: Conditional Rendering](quick-start/arkts-rendering-control-ifelse.md)
- [ForEach: Rendering of Repeated Content](quick-start/arkts-rendering-control-foreach.md) - [ForEach: Rendering of Repeated Content](quick-start/arkts-rendering-control-foreach.md)
- [LazyForEach: Lazy Data Loading](quick-start/arkts-rendering-control-lazyforeach.md) - [LazyForEach: Lazy Data Loading](quick-start/arkts-rendering-control-lazyforeach.md)
...@@ -95,14 +93,14 @@ ...@@ -95,14 +93,14 @@
- [DFX](dfx/Readme-EN.md) - [DFX](dfx/Readme-EN.md)
- [Internationalization](internationalization/Readme-EN.md) - [Internationalization](internationalization/Readme-EN.md)
- [Application Test](application-test/Readme-EN.md) - [Application Test](application-test/Readme-EN.md)
- [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md) - [IDL Specifications and User Guide](IDL/idl-guidelines.md)
- [Native APIs](napi/Readme-EN.md) - [Native APIs](napi/Readme-EN.md)
- Tools - Tools
- [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md) - [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md)
- [Debugging Tools](tools/Readme-EN.md) - [Debugging Tools](tools/Readme-EN.md)
- Hands-On Tutorials - Hands-On Tutorials
- [Samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md) - [Samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md)
- [Codelabs](https://gitee.com/openharmony/codelabs) - [Codelabs](https://gitee.com/openharmony/codelabs/tree/master)
- API References - API References
- [SystemCapability](reference/syscap.md) - [SystemCapability](reference/syscap.md)
- [SystemCapability List](reference/syscap-list.md) - [SystemCapability List](reference/syscap-list.md)
...@@ -113,10 +111,9 @@ ...@@ -113,10 +111,9 @@
- [ArkTS and JS APIs](reference/apis/Readme-EN.md) - [ArkTS and JS APIs](reference/apis/Readme-EN.md)
- [Error Codes](reference/errorcodes/Readme-EN.md) - [Error Codes](reference/errorcodes/Readme-EN.md)
- Native APIs - Native APIs
- [Native APIs](reference/native-apis/Readme-EN.md) - [Native API Reference](reference/native-apis/Readme-EN.md)
- [Standard Libraries](reference/native-lib/third_party_libc/musl.md) - [Standard Libraries](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md) - [Node_API](reference/native-lib/third_party_napi/napi.md)
- [FAQs](faqs/Readme-EN.md) - [FAQs](faqs/Readme-EN.md)
- Contribution - Contribution
- [How to Contribute](../contribute/documentation-contribution.md) - [How to Contribute](../contribute/documentation-contribution.md)
<!--no_check-->
\ No newline at end of file
...@@ -5,17 +5,17 @@ ...@@ -5,17 +5,17 @@
- [Interpretation of the Application Model](application-model-description.md) - [Interpretation of the Application Model](application-model-description.md)
- Stage Model Development - Stage Model Development
- [Stage Model Development Overview](stage-model-development-overview.md) - [Stage Model Development Overview](stage-model-development-overview.md)
- Stage Mode Application Components - Stage Model Application Components
- [Application- or Component-Level Configuration](application-component-configuration-stage.md) - [Application- or Component-Level Configuration](application-component-configuration-stage.md)
- UIAbility Component - UIAbility Component
- [UIAbility Component Overview](uiability-overview.md) - [UIAbility Overview](uiability-overview.md)
- [UIAbility Component Lifecycle](uiability-lifecycle.md) - [UIAbility Lifecycle](uiability-lifecycle.md)
- [UIAbility Component Launch Type](uiability-launch-type.md) - [UIAbility Launch Type](uiability-launch-type.md)
- [UIAbility Component Usage](uiability-usage.md) - [UIAbility Usage](uiability-usage.md)
- [Data Synchronization Between UIAbility and UI](uiability-data-sync-with-ui.md) - [Data Synchronization Between UIAbility and UI Page](uiability-data-sync-with-ui.md)
- [Interaction Between Intra-Device UIAbility Components](uiability-intra-device-interaction.md) - [Interaction Between Intra-Device UIAbility Components](uiability-intra-device-interaction.md)
- ExtensionAbility Component - ExtensionAbility Component
- [ExtensionAbility Component Overview](extensionability-overview.md) - [ExtensionAbility Overview](extensionability-overview.md)
- [ServiceExtensionAbility](serviceextensionability.md) - [ServiceExtensionAbility](serviceextensionability.md)
- [AccessibilityExtensionAbility](accessibilityextensionability.md) - [AccessibilityExtensionAbility](accessibilityextensionability.md)
- [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md) - [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md)
...@@ -56,12 +56,13 @@ ...@@ -56,12 +56,13 @@
- [Using Explicit Want to Start an Application Component](ability-startup-with-explicit-want.md) - [Using Explicit Want to Start an Application Component](ability-startup-with-explicit-want.md)
- [Using Implicit Want to Open a Website](ability-startup-with-implicit-want.md) - [Using Implicit Want to Open a Website](ability-startup-with-implicit-want.md)
- [Using Want to Share Data Between Applications](data-share-via-want.md) - [Using Want to Share Data Between Applications](data-share-via-want.md)
- [Component Startup Rules](component-startup-rules.md) - [Component Startup Rules (Stage Model)](component-startup-rules.md)
- Inter-Device Application Component Interaction (Continuation) - Inter-Device Application Component Interaction (Continuation)
- [Continuation Overview](inter-device-interaction-hop-overview.md) - [Continuation Overview](inter-device-interaction-hop-overview.md)
- [Cross-Device Migration (for System Applications Only)](hop-cross-device-migration.md) - [Cross-Device Migration (for System Applications Only)](hop-cross-device-migration.md)
- [Multi-device Collaboration (for System Applications Only)](hop-multi-device-collaboration.md) - [Multi-device Collaboration (for System Applications Only)](hop-multi-device-collaboration.md)
- [Subscribing to System Environment Variable Changes](subscribe-system-environment-variable-changes.md) - [Subscribing to System Environment Variable Changes](subscribe-system-environment-variable-changes.md)
- [Setting Atomic Services to Support Sharing](atomic-services-support-sharing.md)
- Process Model - Process Model
- [Process Model Overview](process-model-stage.md) - [Process Model Overview](process-model-stage.md)
- Common Events - Common Events
...@@ -81,16 +82,16 @@ ...@@ -81,16 +82,16 @@
- Mission Management - Mission Management
- [Mission Management Scenarios](mission-management-overview.md) - [Mission Management Scenarios](mission-management-overview.md)
- [Mission and Launch Type](mission-management-launch-type.md) - [Mission and Launch Type](mission-management-launch-type.md)
- [Page Stack and MissionList](page-mission-stack.md) - [Page Stack and Mission List](page-mission-stack.md)
- [Setting the Icon and Name of a Mission Snapshot](mission-set-icon-name-for-task-snapshot.md) - [Setting the Icon and Name of a Mission Snapshot](mission-set-icon-name-for-task-snapshot.md)
- [Application Configuration File](config-file-stage.md) - [Application Configuration File](config-file-stage.md)
- FA Model Development - FA Model Development
- [FA Model Development Overview](fa-model-development-overview.md) - [FA Model Development Overview](fa-model-development-overview.md)
- FA Mode Application Components - FA Model Application Components
- [Application- or Component-Level Configuration](application-component-configuration-fa.md) - [Application- or Component-Level Configuration](application-component-configuration-fa.md)
- PageAbility Component Development - PageAbility Component Development
- [PageAbility Component Overview](pageability-overview.md) - [PageAbility Overview](pageability-overview.md)
- [PageAbility Component Configuration](pageability-configuration.md) - [PageAbility Configuration](pageability-configuration.md)
- [PageAbility Lifecycle](pageability-lifecycle.md) - [PageAbility Lifecycle](pageability-lifecycle.md)
- [PageAbility Launch Type](pageability-launch-type.md) - [PageAbility Launch Type](pageability-launch-type.md)
- [Creating a PageAbility](create-pageability.md) - [Creating a PageAbility](create-pageability.md)
...@@ -102,15 +103,15 @@ ...@@ -102,15 +103,15 @@
- [Requesting Permissions](request-permissions.md) - [Requesting Permissions](request-permissions.md)
- [Redirection Rules](redirection-rules.md) - [Redirection Rules](redirection-rules.md)
- ServiceAbility Component Development - ServiceAbility Component Development
- [ServiceAbility Component Overview](serviceability-overview.md) - [ServiceAbility Overview](serviceability-overview.md)
- [ServiceAbility Component Configuration](serviceability-configuration.md) - [ServiceAbility Configuration](serviceability-configuration.md)
- [ServiceAbility Lifecycle](serviceability-lifecycle.md) - [ServiceAbility Lifecycle](serviceability-lifecycle.md)
- [Creating a ServiceAbility](create-serviceability.md) - [Creating a ServiceAbility](create-serviceability.md)
- [Starting a ServiceAbility](start-serviceability.md) - [Starting a ServiceAbility](start-serviceability.md)
- [Connecting to a ServiceAbility](connect-serviceability.md) - [Connecting to a ServiceAbility](connect-serviceability.md)
- DataAbility Component Development - DataAbility Component Development
- [DataAbility Component Overview](dataability-overview.md) - [DataAbility Overview](dataability-overview.md)
- [DataAbility Component Configuration](dataability-configuration.md) - [DataAbility Configuration](dataability-configuration.md)
- [DataAbility Lifecycle](dataability-lifecycle.md) - [DataAbility Lifecycle](dataability-lifecycle.md)
- [Creating a DataAbility](create-dataability.md) - [Creating a DataAbility](create-dataability.md)
- [Starting a DataAbility](start-dataability.md) - [Starting a DataAbility](start-dataability.md)
...@@ -119,7 +120,7 @@ ...@@ -119,7 +120,7 @@
- [Widget Development](widget-development-fa.md) - [Widget Development](widget-development-fa.md)
- [Context](application-context-fa.md) - [Context](application-context-fa.md)
- [Want](want-fa.md) - [Want](want-fa.md)
- [Component Startup Rules](component-startup-rules-fa.md) - [Component Startup Rules (FA Model)](component-startup-rules-fa.md)
- Process Model - Process Model
- [Process Model Overview](process-model-fa.md) - [Process Model Overview](process-model-fa.md)
- [Common Events](common-event-fa.md) - [Common Events](common-event-fa.md)
......
...@@ -11,7 +11,7 @@ The basic dependency packages include: ...@@ -11,7 +11,7 @@ The basic dependency packages include:
- @ohos.data.dataAbility - @ohos.data.dataAbility
- @ohos.data.rdb - @ohos.data.relationalStore
The sample code for accessing a DataAbility is as follows: The sample code for accessing a DataAbility is as follows:
...@@ -23,7 +23,7 @@ The sample code for accessing a DataAbility is as follows: ...@@ -23,7 +23,7 @@ The sample code for accessing a DataAbility is as follows:
// Different from the URI defined in the config.json file, the URI passed in the parameter has an extra slash (/), three slashes in total. // Different from the URI defined in the config.json file, the URI passed in the parameter has an extra slash (/), three slashes in total.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
import ohos_data_ability from '@ohos.data.dataAbility' import ohos_data_ability from '@ohos.data.dataAbility'
import ohos_data_rdb from '@ohos.data.rdb' import relationalStore from '@ohos.data.relationalStore'
let urivar = "dataability:///com.ix.DataAbility" let urivar = "dataability:///com.ix.DataAbility"
let DAHelper = featureAbility.acquireDataAbilityHelper(urivar); let DAHelper = featureAbility.acquireDataAbilityHelper(urivar);
......
...@@ -27,12 +27,14 @@ Instead of manual modification, OpenHarmony adopts the following processing: ...@@ -27,12 +27,14 @@ Instead of manual modification, OpenHarmony adopts the following processing:
## Constraints ## Constraints
1. When you switch a DataAbility to a DataShareExtensionAbility, only the URI prefix can be modified.![FAvsStage-uri](figures/FAvsStage-uri.png) 1. When you switch a DataAbility to a DataShareExtensionAbility, only the URI prefix can be modified.
2. The **DataShareHelper** class implements only certain APIs of **DataAbilityHelper**. For details about the APIs, see the table below. ![FAvsStage-uri](figures/FAvsStage-uri.png)
3. The **DataShareHelper** class implements only certain APIs of **DataAbilityHelper**. For details about the APIs, see the table below.
**Table 1** API compatibility when the FA model accesses a DataShareExtensionAbility of the stage model
**Table 1** APIs invoked when the FA model accesses a DataShareExtensionAbility of the stage model
| API| Provided by DataAbilityHelper| Provided by DataShareHelper| Compatible| | API| Provided by DataAbilityHelper| Provided by DataShareHelper| Compatible|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| on | Yes| Yes| Yes| | on | Yes| Yes| Yes|
......
# AccessibilityExtensionAbility Development # AccessibilityExtensionAbility
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. 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.
...@@ -10,14 +10,6 @@ The **AccessibilityExtensionAbility** module provides accessibility extension ca ...@@ -10,14 +10,6 @@ The **AccessibilityExtensionAbility** module provides accessibility extension ca
> >
> Model: stage > Model: stage
This document is organized as follows:
- [AccessibilityExtensionAbility Overview](#accessibilityextensionability-overview)
- [Creating an Accessibility Extension Service](#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)
## AccessibilityExtensionAbility Overview ## AccessibilityExtensionAbility Overview
Accessibility is about giving equal access to everyone so that they can access and use information equally and conveniently under any circumstances. It helps narrow the digital divide between people of different classes, regions, ages, and health status in terms of information understanding, information exchange, and information utilization, so that they can participate in social life more conveniently and enjoy the benefits of technological advances. Accessibility is about giving equal access to everyone so that they can access and use information equally and conveniently under any circumstances. It helps narrow the digital divide between people of different classes, regions, ages, and health status in terms of information understanding, information exchange, and information utilization, so that they can participate in social life more conveniently and enjoy the benefits of technological advances.
...@@ -28,11 +20,11 @@ Below shows the AccessibilityExtensionAbility framework. ...@@ -28,11 +20,11 @@ Below shows the AccessibilityExtensionAbility framework.
![AccessibilityFramework](figures/AccessibilityFramework.png) ![AccessibilityFramework](figures/AccessibilityFramework.png)
1. Accessibility app: extension service application developed based on the AccessibilityExtensionAbility framework, for example, a screen reader application. 1. Accessibility application: extension service application developed based on the AccessibilityExtensionAbility framework, for example, a screen reader application.
2. Target app: application assisted by the accessibility app. 2. Target application: application assisted by the accessibility application.
3. AccessibilityAbilityManagerService (AAMS): main service of the AccessibilityExtensionAbility framework, which is used to manage the lifecycle of accessibility apps and provide a bridge for information exchange between accessibility apps and target apps. 3. AccessibilityAbilityManagerService (AAMS): main service of the AccessibilityExtensionAbility framework, which is used to manage the lifecycle of accessibility applications and provide a bridge for information exchange between accessibility applications and target applications.
4. AccessibilityAbility (AAkit): ability that is used by the accessibility app to build an extension service ability operating environment and that provides interfaces for the accessibility app to query and operate the target app, including performing click/long press operations. 4. AccessibilityAbility (AAkit): ability that is used by the accessibility application to build an extension service ability operating environment and that provides interfaces for the accessibility application to query and operate the target application, including performing click/long press operations.
5. AccessibilitySystemAbilityClient (ASACkit): used by the target app to send accessibility events, such as content change events, to AAMS, and respond to the instructions (such as performing click/long press operations) sent by the accessibility app through AAMS. 5. AccessibilitySystemAbilityClient (ASACkit): used by the target application to send accessibility events, such as content change events, to AAMS, and respond to the instructions (such as performing click/long press operations) sent by the accessibility application through AAMS.
## Creating an Accessibility Extension Service ## Creating an Accessibility Extension Service
...@@ -124,13 +116,13 @@ After developing the custom logic for an accessibility extension service, you mu ...@@ -124,13 +116,13 @@ After developing the custom logic for an accessibility extension service, you mu
] ]
} }
``` ```
## Enabling a Custom Accessibility Extension Service ## Enabling or Disabling a Custom Accessibility Extension Service
To enable or disable an accessibility extension service, run the following command: 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 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** - 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). 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 and **g** gesture).
If the service is enabled or disabled successfully, the message "enable ability successfully" or "disable ability successfully" is displayed. If the service is enabled or disabled successfully, the message "enable ability successfully" or "disable ability successfully" is displayed.
# API Switching Overview # API Switching Overview
Due to the differences in the thread model and process model, certain APIs (marked with **FAModelOnly** in the SDK) can be used only in the FA model. When switching an application from the FA model to the stage model, replace the APIs marked with **FAModelOnly** in the application with the APIs supported in the stage model. This topic uses the switching of **startAbility()** as an example. Due to the differences in the thread model and process model, certain APIs can be used only in the FA model. They are marked with **FAModelOnly** in the SDK. When switching an application from the FA model to the stage model, replace the APIs marked with **FAModelOnly** in the application with the APIs supported in the stage model. This topic uses the switching of **startAbility()** as an example.
![api-switch-overview](figures/api-switch-overview.png) ![api-switch-overview](figures/api-switch-overview.png)
...@@ -27,7 +27,7 @@ Due to the differences in the thread model and process model, certain APIs (mark ...@@ -27,7 +27,7 @@ Due to the differences in the thread model and process model, certain APIs (mark
- Sample code of **startAbility()** in the stage model: - Sample code of **startAbility()** in the stage model:
```ts ```ts
// context is a member of the ability object and is required for invoking inside a non-ability object. // Context is a member of the ability object and is required for invoking inside a non-ability object.
// Pass in the Context object. // Pass in the Context object.
let wantInfo = { let wantInfo = {
bundleName: "com.example.myapplication", bundleName: "com.example.myapplication",
......
...@@ -13,7 +13,7 @@ The application icon and label are used in **Settings**. For example, they are d ...@@ -13,7 +13,7 @@ The application icon and label are used in **Settings**. For example, they are d
- **Configuring the bundle name** - **Configuring the bundle name**
The bundle name is specified by the **bundleName** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory of the project. This field uniquely identifies an application. You are advised to use the reverse domain name notion, for example, *com.example.demo*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels. The bundle name is specified by the **bundleName** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory of the project. This field uniquely identifies an application. You are advised to use the reverse domain name notation, for example, *com.example.demo*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.
- **Configuring the application icon and label** - **Configuring the application icon and label**
...@@ -21,7 +21,7 @@ The application icon and label are used in **Settings**. For example, they are d ...@@ -21,7 +21,7 @@ The application icon and label are used in **Settings**. For example, they are d
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 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 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 label is specified by the **label** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory 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
{ {
...@@ -37,7 +37,7 @@ The application icon and label are used in **Settings**. For example, they are d ...@@ -37,7 +37,7 @@ The application icon and label are used in **Settings**. For example, they are d
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. 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. 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 components.
```json ```json
{ {
...@@ -65,33 +65,33 @@ The application icon and label are used in **Settings**. For example, they are d ...@@ -65,33 +65,33 @@ The application icon and label are used in **Settings**. For example, they are d
``` ```
OpenHarmony strictly controls applications without icons to prevent malicious applications from deliberately configuring no icon to block uninstall attempts. OpenHarmony strictly controls applications without icons to prevent malicious applications from deliberately configuring no icon to block uninstall attempts.
To hide an application icon from the home screen, you must configure the **AllowAppDesktopIconHide** privilege. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). The rules for displaying the entry icon and entry label are as follows: To hide an application icon on the home screen, you must configure the **AllowAppDesktopIconHide** privilege. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). The rules for displaying the entry icon and entry label are as follows:
1. The HAP file contains UIAbility configuration. 1. The HAP file contains UIAbility configuration.
* An entry icon is set in the **abilities** field of the **module.json5** file. * An entry icon is set in the **abilities** field of the **module.json5** file.
* The application does not have the privilege to hide its icon from the home screen. * The application does not have the privilege to hide its icon on the home screen.
* The system uses the icon configured for the UIAbility as the entry icon and displays it on the home screen. Touching this icon will direct the user to the home page of the UIAbility. * The system uses the icon configured for the UIAbility as the entry icon and displays it on the home screen. Touching this icon will direct the user to the home page of the UIAbility.
* The system uses the label configured for the UIAbility as the entry label and displays it on the home screen. If no label is configured, the system uses the label specified in the **app.json5** file as the entry label and displays it on the home screen. * The system uses the label configured for the UIAbility as the entry label and displays it on the home screen. If no label is configured, the system uses the label specified in the **app.json5** file as the entry label and displays it on the home screen.
* The application has the privilege to hide its icon from the home screen. * The application has the privilege to hide its icon on the home screen.
* The application information is not returned when the home screen queries the information, and the entry icon and label of the application are not displayed on the home screen. * The application information is not returned when the home screen queries the information, and the entry icon and label of the application are not displayed on the home screen.
* No entry icon is set in the **abilities** field of the **module.json5** file. * No entry icon is set in the **abilities** field of the **module.json5** file.
* The application does not have the privilege to hide its icon from the home screen. * The application does not have the privilege to hide its icon on the home screen.
* The system uses the icon specified in the **app.json5** file as the entry icon and displays it on the home screen. Touching this icon will direct the user to the application details page, as shown below. * The system uses the icon specified in the **app.json5** file as the entry icon and displays it on the home screen. Touching this icon will direct the user to the application details page, as shown below.
* The system uses the label specified in the **app.json5** file as the entry label and displays it on the home screen. * The system uses the label specified in the **app.json5** file as the entry label and displays it on the home screen.
* The application has the privilege to hide its icon from the home screen. * The application has the privilege to hide its icon on the home screen.
* The application information is not returned when the home screen queries the information, and the entry icon and label of the application are not displayed on the home screen. * The application information is not returned when the home screen queries the information, and the entry icon and label of the application are not displayed on the home screen.
2. The HAP file does not contain UIAbility configuration. 2. The HAP file does not contain UIAbility configuration.
* The application does not have the privilege to hide its icon from the home screen. * The application does not have the privilege to hide its icon on the home screen.
* The system uses the icon specified in the **app.json5** file as the entry icon and displays it on the home screen. Touching this icon will direct the user to the application details page, as shown below. * The system uses the icon specified in the **app.json5** file as the entry icon and displays it on the home screen. Touching this icon will direct the user to the application details page, as shown below.
* The system uses the label specified in the **app.json5** file as the entry label and displays it on the home screen. * The system uses the label specified in the **app.json5** file as the entry label and displays it on the home screen.
* The application has the privilege to hide its icon from the home screen. * The application has the privilege to hide its icon on the home screen.
* The application information is not returned when the home screen queries the information, and the entry icon and label of the application are not displayed on the home screen. * The application information is not returned when the home screen queries the information, and the entry icon and label of the application are not displayed on the home screen.
**Figure 2** Application details page **Figure 2** Application details page
![Application details page](figures/application_details.jpg) ![Application details page](figures/application_details.jpg)
- **Configuring application version declaration** - **Configuring application version declaration**
To declare the application version, configure the **versionCode** and **versionName** fields in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory of the project. **versionCode** specifies the version number of the application. The value is a 32-bit non-negative integer. It is used only to determine whether a version is later than another version. A larger value indicates a later version. **versionName** provides the text description of the version number. To declare the application version, configure the **versionCode** and **versionName** fields in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory of the project. **versionCode** specifies the version number of the application. The value is a 32-bit non-negative integer. It is used only to determine whether a version is later than another version. A larger value indicates a later version. **versionName** provides the text description of the version number.
......
...@@ -44,17 +44,17 @@ For details about the APIs, see [API Reference](../reference/apis/js-apis-inner- ...@@ -44,17 +44,17 @@ For details about the APIs, see [API Reference](../reference/apis/js-apis-inner-
} }
``` ```
2. Set the display orientation of the host featureAbility. 2. Set the display orientation of the **featureAbility**.
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
import bundle from '@ohos.bundle'; import bundleManager from '@ohos.bundle.bundleManager';
export default { export default {
onCreate() { onCreate() {
// Obtain the context and call related APIs. // Obtain the context and call related APIs.
let context = featureAbility.getContext(); let context = featureAbility.getContext();
context.setDisplayOrientation(bundle.DisplayOrientation.LANDSCAPE).then(() => { context.setDisplayOrientation(bundleManager.DisplayOrientation.LANDSCAPE).then(() => {
console.info("Set display orientation.") console.info("Set display orientation.")
}) })
console.info('Application onCreate') console.info('Application onCreate')
......
# Context (Stage Model) # Context (Stage Model)
## Overview ## Overview
[Context](../reference/apis/js-apis-inner-application-context.md) is the context of an object in an application. It provides basic information about the application, for example, **resourceManager**, **applicationInfo**, **dir** (application development path), and **area** (encrypted level). It also provides basic methods such as **createBundleContext()** and **getApplicationContext()**. The UIAbility component and ExtensionAbility derived class components have their own **Context** classes, for example, the base class **Context**, **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, **ExtensionContext**, and **ServiceExtensionContext**. [Context](../reference/apis/js-apis-inner-application-context.md) is the context of an object in an application. It provides basic information about the application, for example, **resourceManager**, **applicationInfo**, **dir** (application file path), and **area** (encryption level). It also provides basic methods such as **createBundleContext()** and **getApplicationContext()**. The UIAbility component and ExtensionAbility derived class components have their own **Context** classes, for example, the base class **Context**, **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, **ExtensionContext**, and **ServiceExtensionContext**.
- The figure below illustrates the inheritance relationship of contexts.
- The figure below illustrates the inheritance relationship of contexts.
![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)
The following describes the information provided by different contexts. ![context-holding](figures/context-holding.png)
- 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 an application component, obtain the application component 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
...@@ -67,79 +70,81 @@ The following describes the information provided by different contexts. ...@@ -67,79 +70,81 @@ The following describes the information provided by different contexts.
This topic describes how to use the context in the following scenarios: This topic describes how to use the context in the following scenarios:
- [Obtaining the Application Development Path](#obtaining-the-application-development-path) - [Obtaining Application File Paths](#obtaining-application-file-paths)
- [Obtaining and Modifying Encryption Levels](#obtaining-and-modifying-encryption-levels) - [Obtaining and Modifying Encryption Levels](#obtaining-and-modifying-encryption-levels)
- [Creating Context of Another Application or Module](#creating-context-of-another-application-or-module) - [Creating Context of Another Application or Module](#creating-context-of-another-application-or-module)
- [Subscribing to UIAbility Lifecycle Changes in a Process](#subscribing-to-uiability-lifecycle-changes-in-a-process) - [Subscribing to UIAbility Lifecycle Changes in a Process](#subscribing-to-uiability-lifecycle-changes-in-a-process)
### Obtaining the Application Development Path ### Obtaining Application File Paths
The following table describes the application development paths obtained from context. The base class [Context](../reference/apis/js-apis-inner-application-context.md) provides the capability of obtaining application file paths. **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, and **ExtensionContext** inherit this capability. The application file paths are a type of application sandbox paths. For details, see [Application Sandbox Directory](../file-management/app-sandbox-directory.md).
**Table 1** Application development paths The application file paths obtained by the preceding contexts are different.
| Name| Type| Readable| Writable| Description| - The application file path obtained through **ApplicationContext** is at the application level. This path is recommended for storing global application information, and the files in the path will be deleted when the application is uninstalled.
| -------- | -------- | -------- | -------- | -------- |
| bundleCodeDir | string | Yes | No | Path for storing the application's installation package, that is, installation directory of the application on the internal storage. |
| cacheDir | string | Yes| No| Path for storing the cache files, that is, cache directory of the application on the internal storage.<br>It is the content of **Storage** of an application under **Settings > Apps & services > Apps**.|
| filesDir | string | Yes | No | Path for storing the common files, that is, file directory of the application on the internal storage.<br>Files in this directory may be synchronized to other directories during application migration or backup.|
| preferencesDir | string | Yes | Yes | Path for storing the preference files, that is, preferences directory of the application. |
| tempDir | string | Yes | No | Path for storing the temporary files.<br>Files in this directory are deleted after the application is uninstalled.|
| databaseDir | string | Yes | No | Path for storing the application's database, that is, storage directory of the local database. |
| distributedFilesDir | string | Yes| No| Path for storing the distributed files.|
The capability of obtaining the application development path is provided by the base class **Context**. This capability is also provided by **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, and **ExtensionContext**. However, the paths obtained from different contexts may differ, as shown below. | Name| Path|
**Figure 1** Application development paths obtained from context
![context-dir](figures/context-dir.png)
- Obtain the application-level path through **ApplicationContext**. It is recommended that global application information be stored in this path. Files stored in this path will be deleted only when the application is uninstalled.
| Name| Path|
| -------- | -------- |
| bundleCodeDir | {Path prefix}/el1/bundle/|
| cacheDir | {Path prefix}/{Encryption level}/base/cache/|
| filesDir | {Path prefix}/{Encryption level}/base/files/|
| preferencesDir | {Path prefix}/{Encryption level}/base/preferences/|
| tempDir | {Path prefix}/{Encryption level}/base/temp/|
| databaseDir | {Path prefix}/{Encryption level}/database/|
| distributedFilesDir | {Path prefix}/el2/distributedFiles/|
- Obtain the HAP level path through **AbilityStageContext**, **UIAbilityContext**, and **ExtensionContext**. It is recommended that the HAP information be stored in this path. The file content stored in this path will be deleted when the HAP is uninstalled. The file content in the application-level path will be deleted only after all the HAPs of the application are uninstalled.
| Name| Path|
| -------- | -------- | | -------- | -------- |
| bundleCodeDir | {Path prefix}/el1/bundle/| | bundleCodeDir | <Path prefix>/el1/bundle/|
| cacheDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/cache/| | cacheDir | <Path prefix>/<Encryption level>/base/cache/|
| filesDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/files/| | filesDir | <Path prefix>/<Encryption level>/base/files/|
| preferencesDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/preferences/| | preferencesDir | <Path prefix>/<Encryption level>/base/preferences/|
| tempDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/temp/| | tempDir | <Path prefix>/<Encryption level>/base/temp/|
| databaseDir | {Path prefix}/{Encryption level}/database/**{moduleName}**/| | databaseDir | <Path prefix>/<Encryption level>/database/|
| distributedFilesDir | {Path prefix}/el2/distributedFiles/**{moduleName}**/| | distributedFilesDir | <Path prefix>/el2/distributedFiles/|
The sample code is as follows:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
let applicationContext = this.context.getApplicationContext();
let cacheDir = applicationContext.cacheDir;
let tempDir = applicationContext.tempDir;
let filesDir = applicationContext.filesDir;
let databaseDir = applicationContext.databaseDir;
let bundleCodeDir = applicationContext.bundleCodeDir;
let distributedFilesDir = applicationContext.distributedFilesDir;
let preferencesDir = applicationContext.preferencesDir;
...
}
}
```
The sample code for obtaining the application development paths is as follows: - The application file path obtained through **AbilityStageContext**, **UIAbilityContext**, or **ExtensionContext** is at the HAP level. This path is recommended for storing HAP-related information, and the files in this path are deleted when the HAP is uninstalled. However, the deletion does not affect the files in the application-level path unless all HAPs of the application are uninstalled.
| Name| Path|
| -------- | -------- |
| bundleCodeDir | <Path prefix>/el1/bundle/|
| cacheDir | <Path prefix>/<Encryption level>/base/**haps/\<module-name>**/cache/|
| filesDir | <Path prefix>/<Encryption level>/base/**haps/\<module-name>**/files/|
| preferencesDir | <Path prefix>/<Encryption level>/base/**haps/\<module-name>**/preferences/|
| tempDir | <Path prefix>/<Encryption level>/base/**haps/\<module-name>**/temp/|
| databaseDir | <Path prefix>/<Encryption level>/database/**\<module-name>**/|
| distributedFilesDir | <Path prefix>/el2/distributedFiles/**\<module-name>**/|
```ts The sample code is as follows:
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility { ```ts
onCreate(want, launchParam) { import UIAbility from '@ohos.app.ability.UIAbility';
let cacheDir = this.context.cacheDir;
let tempDir = this.context.tempDir; export default class EntryAbility extends UIAbility {
let filesDir = this.context.filesDir; onCreate(want, launchParam) {
let databaseDir = this.context.databaseDir; let cacheDir = this.context.cacheDir;
let bundleCodeDir = this.context.bundleCodeDir; let tempDir = this.context.tempDir;
let distributedFilesDir = this.context.distributedFilesDir; let filesDir = this.context.filesDir;
let preferencesDir = this.context.preferencesDir; let databaseDir = this.context.databaseDir;
... let bundleCodeDir = this.context.bundleCodeDir;
let distributedFilesDir = this.context.distributedFilesDir;
let preferencesDir = this.context.preferencesDir;
...
}
} }
} ```
```
> **NOTE**
>
> The sample code obtains the sandbox path of the application development path. The absolute path can be obtained by running the **find / -name <fileName>** command in the hdc shell after file creation or modification.
### Obtaining and Modifying Encryption Levels ### Obtaining and Modifying Encryption Levels
...@@ -153,22 +158,23 @@ In practice, you need to select a proper encryption level based on scenario-spec ...@@ -153,22 +158,23 @@ In practice, you need to select a proper encryption level based on scenario-spec
> >
> - AreaMode.EL2: user-level encryption. Directories with this encryption level are accessible only after the device is powered on and the password is entered (for the first time). > - AreaMode.EL2: user-level encryption. Directories with this encryption level are accessible only after the device is powered on and the password is entered (for the first time).
You can obtain and set the encryption level by reading and writing the [area attribute in Context](../reference/apis/js-apis-inner-application-context.md). You can obtain and set the encryption level by reading and writing the **area** attribute in [Context](../reference/apis/js-apis-inner-application-context.md).
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import contextConstant from '@ohos.app.ability.contextConstant';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
// Before storing common information, switch the encryption level to EL1. // Before storing common information, switch the encryption level to EL1.
if (this.context.area === 1) {// Obtain the area. if (this.context.area === contextConstant.AreaMode.EL2) { // Obtain the area.
this.context.area = 0; // Modify the area. this.context.area = contextConstant.AreaMode.EL1; // Modify the area.
} }
// Store common information. // Store common information.
// Before storing sensitive information, switch the encryption level to EL2. // Before storing sensitive information, switch the encryption level to EL2.
if (this.context.area === 0) { // Obtain the area. if (this.context.area === contextConstant.AreaMode.EL1) { // Obtain the area.
this.context.area = 1; // Modify the area. this.context.area = contextConstant.AreaMode.EL2; // Modify the area.
} }
// Store sensitive information. // Store sensitive information.
} }
...@@ -178,7 +184,7 @@ export default class EntryAbility extends UIAbility { ...@@ -178,7 +184,7 @@ export default class EntryAbility extends UIAbility {
### Creating Context of Another Application or Module ### Creating Context of Another Application or Module
The base class **Context** provides [createBundleContext(bundleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatebundlecontext), [createModuleContext(moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext), and [createModuleContext(bundleName:string, moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext-1) to create the context of other applications or modules, so as to obtain the resource information, for example, [obtaining the application development paths](#obtaining-the-application-development-path) of other modules. The base class **Context** provides [createBundleContext(bundleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatebundlecontext), [createModuleContext(moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext), and [createModuleContext(bundleName:string, moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext-1) to create the context of other applications or modules, so as to obtain the resource information, for example, [obtaining application file paths](#obtaining-application-development-paths) of other modules.
- Call **createBundleContext(bundleName:string)** to create the context of another application. - Call **createBundleContext(bundleName:string)** to create the context of another application.
> **NOTE** > **NOTE**
...@@ -188,9 +194,9 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../ ...@@ -188,9 +194,9 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../
> - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Declaring Permissions in the Configuration File](../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.
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';
...@@ -203,7 +209,7 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../ ...@@ -203,7 +209,7 @@ The base class **Context** provides [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**
> >
......
...@@ -32,7 +32,7 @@ Widget-related configuration includes **FormExtensionAbility** configuration and ...@@ -32,7 +32,7 @@ Widget-related configuration includes **FormExtensionAbility** configuration and
} }
``` ```
2. Configure the widget configuration information. In the **metadata** configuration item of FormExtensionAbility, you can specify the resource index of specific configuration information of the widget. For example, if resource is set to **$profile:form_config**, **form_config.json** in the **resources/base/profile/** directory of the development view is used as the profile configuration file of the widget. The following table describes the internal field structure. 2. Configure the widget configuration information. In the **metadata** configuration item of FormExtensionAbility, you can specify the resource index of specific configuration information of the widget. For example, if **resource** is set to **$profile:form_config**, **form_config.json** in the **resources/base/profile/** directory of the development view is used as the profile configuration file of the widget. The following table describes the internal structure of the profile configuration file.
**Table 1** form_config.json file **Table 1** form_config.json file
...@@ -47,8 +47,8 @@ Widget-related configuration includes **FormExtensionAbility** configuration and ...@@ -47,8 +47,8 @@ Widget-related configuration includes **FormExtensionAbility** configuration and
| colorMode | Color mode of the widget.<br>- **auto**: auto-adaptive color mode<br>- **dark**: dark color mode<br>- **light**: light color mode| String| Yes (initial value: **auto**)| | colorMode | Color mode of the widget.<br>- **auto**: auto-adaptive color mode<br>- **dark**: dark color mode<br>- **light**: light color mode| String| Yes (initial value: **auto**)|
| supportDimensions | Grid styles supported by the widget.<br>- **1 * 2**: indicates a grid with one row and two columns.<br>- **2 * 2**: indicates a grid with two rows and two columns.<br>- **2 * 4**: indicates a grid with two rows and four columns.<br>- **4 * 4**: indicates a grid with four rows and four columns.| String array| No| | supportDimensions | Grid styles supported by the widget.<br>- **1 * 2**: indicates a grid with one row and two columns.<br>- **2 * 2**: indicates a grid with two rows and two columns.<br>- **2 * 4**: indicates a grid with two rows and four columns.<br>- **4 * 4**: indicates a grid with four rows and four columns.| String array| No|
| defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String| No| | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String| No|
| updateEnabled | Whether the widget can be updated periodically.<br>- **true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**.<br>- **false**: The widget cannot be updated periodically.| Boolean| No| | updateEnabled | Whether the widget can be updated periodically.<br>- **true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.<br>- **false**: The widget cannot be updated periodically.| Boolean| No|
| scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.<br>**NOTE**<br>**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| String| Yes (initial value: The widget cannot be updated periodically.)| | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.<br>**NOTE**<br>**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| String| Yes (initial value: The widget is not updated at the scheduled time.)|
| updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.<br>If the value is **0**, this field does not take effect.<br>If the value is a positive integer *N*, the interval is calculated by multiplying *N* and 30 minutes.<br>**NOTE**<br>**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number| Yes (initial value: **0**)| | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.<br>If the value is **0**, this field does not take effect.<br>If the value is a positive integer *N*, the interval is calculated by multiplying *N* and 30 minutes.<br>**NOTE**<br>**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number| Yes (initial value: **0**)|
| formConfigAbility | Link to a specific page of the application. The value is a URI.| String| Yes (initial value: left empty)| | formConfigAbility | Link to a specific page of the application. The value is a URI.| String| Yes (initial value: left empty)|
| formVisibleNotify | Whether the widget is allowed to use the widget visibility notification.| String| Yes (initial value: left empty)| | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification.| String| Yes (initial value: left empty)|
......
...@@ -3,9 +3,9 @@ ...@@ -3,9 +3,9 @@
To create an ArkTS widget in an existing application project, perform the following steps: To create an ArkTS widget in an existing application project, perform the following steps:
1. Create a widget. 1. Create a widget.
![WidgetProjectCreate1](figures/WidgetProjectCreate1.png) ![WidgetProjectCreate1](figures/WidgetProjectCreate1.png)
2. Select a widget template based on the actual service scenario. 2. Select a widget template based on the actual service scenario.
![WidgetProjectCreate2](figures/WidgetProjectCreate2.png) ![WidgetProjectCreate2](figures/WidgetProjectCreate2.png)
...@@ -14,6 +14,6 @@ To create an ArkTS widget in an existing application project, perform the follow ...@@ -14,6 +14,6 @@ To create an ArkTS widget in an existing application project, perform the follow
![WidgetProjectCreate3](figures/WidgetProjectCreate3.png) ![WidgetProjectCreate3](figures/WidgetProjectCreate3.png)
After an ArkTS widget is created, the following widget-related files are added to the project directory: **EntryFormAbility.ts** (widget lifecycle management file), **WidgetCard.ets** (widget page file), and **form_config.json** (widget configuration file). After an ArkTS widget is created, the following widget-related files are automatically added to the project directory: **EntryFormAbility.ts** (widget lifecycle management file), **WidgetCard.ets** (widget page file), and **form_config.json** (widget configuration file).
![WidgetProjectView](figures/WidgetProjectView.png) ![WidgetProjectView](figures/WidgetProjectView.png)
\ No newline at end of file
# Launching a UIAbility in the Background Through the call Event # Launching a UIAbility in the Background Through the call Event
There may be cases you want to provide in a widget access to features available in your application when it is running in the foreground, for example, the play, pause, and stop buttons in a music application widget. This is where the **call** capability of the **postCardAction** API comes in handy. This capability, when used in a widget, can start the specified UIAbility of the widget provider in the background. It also allows the widget to call the specified method of the application and transfer data so that the application, while in the background, can behave accordingly in response to touching of the buttons on the widget. There may be cases you want to provide in a widget access to features available in your application running in the foreground, for example, the play, pause, and stop buttons in a music application widget. This is where the **call** capability of the **postCardAction** API comes in handy. This capability, when used in a widget, can start the specified UIAbility of the widget provider in the background. It also allows the widget to call the specified method of the application and transfer data so that the application, while in the background, can behave accordingly in response to touching of the buttons on the widget.
Generally, buttons are used to trigger the **call** event. Below is an example. Typically, the call event is triggered for touching of buttons. Below is an example.
- In this example, two buttons are laid out on the widget page. When one button is clicked, the **postCardAction** API is called to send a **call** event to the target UIAbility. Note that the **method** parameter in the API indicates the method to call in the target UIAbility. It is mandatory and of the string type. - In this example, two buttons are laid out on the widget page. When one button is clicked, the **postCardAction** API is called to send a call event to the target UIAbility. Note that the **method** parameter in the API indicates the method to call in the target UIAbility. It is mandatory and of the string type.
```ts ```ts
@Entry @Entry
...@@ -37,7 +37,7 @@ Generally, buttons are used to trigger the **call** event. Below is an example. ...@@ -37,7 +37,7 @@ Generally, buttons are used to trigger the **call** event. Below is an example.
'abilityName': 'EntryAbility', // Only the UIAbility of the current application is allowed. 'abilityName': 'EntryAbility', // Only the UIAbility of the current application is allowed.
'params': { 'params': {
'method': 'funB', // Set the name of the method to call in the EntryAbility. 'method': 'funB', // Set the name of the method to call in the EntryAbility.
'num': 1 // Set other parameters to be transferred. 'num': 1 // Set other parameters to be passed in.
} }
}); });
}) })
...@@ -48,34 +48,36 @@ Generally, buttons are used to trigger the **call** event. Below is an example. ...@@ -48,34 +48,36 @@ Generally, buttons are used to trigger the **call** event. Below is an example.
} }
``` ```
- The UIAbility receives the **call** event and obtains the transferred parameters. It then executes the target method specified by the **method** parameter. Other data can be obtained in readString mode. Listen for the method required by the **call** event in the **onCreate** callback of the UIAbility. - The UIAbility receives the call event and obtains the transferred parameters. It then executes the target method specified by the **method** parameter. Other data can be obtained in readString mode. Listen for the method required by the call event in the **onCreate** callback of the UIAbility.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
function FunACall(data) { function FunACall(data) {
// Obtain all parameters transferred in the call event. // Obtain all parameters passed in the call event.
console.info('FunACall param:' + JSON.stringify(data.readString())); console.info('FunACall param:' + JSON.stringify(data.readString()));
return null; return null;
} }
function FunBCall(data) { function FunBCall(data) {
console.info('FunACall param:' + JSON.stringify(data.readString())); console.info('FunBCall param:' + JSON.stringify(data.readString()));
return null; return null;
} }
export default class CameraAbility extends UIAbility { export default class CameraAbility extends UIAbility {
// If the UIAbility is started for the first time, the onCreate lifecycle callback is triggered after the call event is received. // If the UIAbility is started for the first time, onCreate is triggered afte the call event is received.
onCreate(want, launchParam) { onCreate(want, launchParam) {
try { try {
// Listen for the method required by the call event. // Listen for the method required by the call event.
this.callee.on('funA', FunACall); this.callee.on('funA', FunACall);
this.callee.on('funB', FunBCall); this.callee.on('funB', FunBCall);
} catch (error) { } catch (err) {
console.error(`Failed to register callee on. Cause: ${JSON.stringify(err)}`); console.error(`Failed to register callee on. Cause: ${JSON.stringify(err)}`);
} }
} }
...
// Deregister the listener when the process exits. // Deregister the listener when the process exits.
onDestroy() { onDestroy() {
try { try {
......
...@@ -5,7 +5,7 @@ On the widget page, the **postCardAction** API can be used to trigger a router o ...@@ -5,7 +5,7 @@ On the widget page, the **postCardAction** API can be used to trigger a router o
## Updating Widget Content Through the router Event ## Updating Widget Content Through the router Event
- On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the **router** event to the FormExtensionAbility. - On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the router event to the FormExtensionAbility.
```ts ```ts
let storage = new LocalStorage(); let storage = new LocalStorage();
...@@ -45,7 +45,7 @@ On the widget page, the **postCardAction** API can be used to trigger a router o ...@@ -45,7 +45,7 @@ On the widget page, the **postCardAction** API can be used to trigger a router o
import formInfo from '@ohos.app.form.formInfo'; import formInfo from '@ohos.app.form.formInfo';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
// If the UIAbility is started for the first time, the onCreate lifecycle callback is triggered after the router event is received. // If the UIAbility is started for the first time, onCreate is triggered after the router event is received.
onCreate(want, launchParam) { onCreate(want, launchParam) {
console.info('Want:' + JSON.stringify(want)); console.info('Want:' + JSON.stringify(want));
if (want.parameters[formInfo.FormParam.IDENTITY_KEY] !== undefined) { if (want.parameters[formInfo.FormParam.IDENTITY_KEY] !== undefined) {
...@@ -63,7 +63,7 @@ On the widget page, the **postCardAction** API can be used to trigger a router o ...@@ -63,7 +63,7 @@ On the widget page, the **postCardAction** API can be used to trigger a router o
}) })
} }
} }
// If the UIAbility is running in the background, the onNewWant lifecycle callback is triggered after the router event is received. // If the UIAbility is running in the background, onNewWant is triggered after the router event is received.
onNewWant(want, launchParam) { onNewWant(want, launchParam) {
console.info('onNewWant Want:' + JSON.stringify(want)); console.info('onNewWant Want:' + JSON.stringify(want));
if (want.parameters[formInfo.FormParam.IDENTITY_KEY] !== undefined) { if (want.parameters[formInfo.FormParam.IDENTITY_KEY] !== undefined) {
...@@ -88,7 +88,7 @@ On the widget page, the **postCardAction** API can be used to trigger a router o ...@@ -88,7 +88,7 @@ On the widget page, the **postCardAction** API can be used to trigger a router o
## Updating Widget Content Through the call Event ## Updating Widget Content Through the call Event
- When using the **call** event of the **postCardAction** API, the value of **formId** must be updated in the **onAddForm** callback of the FormExtensionAbility. - When using the call event of the **postCardAction** API, the value of **formId** must be updated in the **onAddForm** callback of the FormExtensionAbility.
```ts ```ts
import formBindingData from '@ohos.app.form.formBindingData'; import formBindingData from '@ohos.app.form.formBindingData';
...@@ -142,13 +142,12 @@ On the widget page, the **postCardAction** API can be used to trigger a router o ...@@ -142,13 +142,12 @@ On the widget page, the **postCardAction** API can be used to trigger a router o
} }
``` ```
- Listen for the method required by the **call** event in the **onCreate** callback of the UIAbility, and then call the [updateForm](../reference/apis/js-apis-app-form-formProvider.md#updateform) API in the corresponding method to update the widget. - Listen for the method required by the call event in the **onCreate** callback of the UIAbility, and then call the [updateForm](../reference/apis/js-apis-app-form-formProvider.md#updateform) API in the corresponding method to update the widget.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import formBindingData from '@ohos.app.form.formBindingData'; import formBindingData from '@ohos.app.form.formBindingData';
import formProvider from '@ohos.app.form.formProvider'; import formProvider from '@ohos.app.form.formProvider';
import formInfo from '@ohos.app.form.formInfo';
const MSG_SEND_METHOD: string = 'funA'; const MSG_SEND_METHOD: string = 'funA';
...@@ -173,7 +172,7 @@ On the widget page, the **postCardAction** API can be used to trigger a router o ...@@ -173,7 +172,7 @@ On the widget page, the **postCardAction** API can be used to trigger a router o
return null; return null;
} }
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
// If the UIAbility is started for the first time, the onCreate lifecycle callback is triggered after the call event is received. // If the UIAbility is started for the first time, onCreate is triggered after the call event is received.
onCreate(want, launchParam) { onCreate(want, launchParam) {
console.info('Want:' + JSON.stringify(want)); console.info('Want:' + JSON.stringify(want));
try { try {
......
# Widget Data Interaction # Widget Data Interaction
The ArkTS widget framework provides the **updateForm()** and **requestForm()** APIs to proactively trigger widget updates. The ArkTS widget framework provides the **updateForm()** and **requestForm()** APIs to proactively trigger widget updates.
![WidgetLocalStorageProp](figures/WidgetLocalStorageProp.png) ![WidgetLocalStorageProp](figures/WidgetLocalStorageProp.png)
| API| System Capability| Constraints| | API| System Capability| Constraints|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| updateForm | No| 1. Invoked by the provider.<br>2. Allows only the widget provider to update its own widgets. It cannot be used to update widgets by other providers.| | updateForm | No| 1. Invoked by the widget provider.<br>2. Allows only the widget provider to update its own widgets.|
| requestForm | Yes| 1. Invoked by the host.<br>2. Allows only the widget host to update the widgets added to it. It cannot be used to update widgets added to other hosts.| | requestForm | Yes| 1. Invoked by the widget host.<br>2. Allows only the widget host to update the widgets added to it.|
The following describes the typical use cases of widget updates: The following are the typical use cases of widget updates:
- [Configuring a Widget to Update Periodically](arkts-ui-widget-update-by-time.md) - [Configuring a Widget to Update Periodically](arkts-ui-widget-update-by-time.md)
- [Updating Widget Content Through a Proxy](arkts-ui-widget-update-by-proxy.md)
- [Updating Local and Online Images](arkts-ui-widget-image-update.md) - [Updating Local and Online Images](arkts-ui-widget-image-update.md)
- [Updating Widget Content by State](arkts-ui-widget-update-by-status.md) - [Updating Widget Content by State](arkts-ui-widget-update-by-status.md)
- [Updating Widget Content by Widget Host (for System Applications Only)](arkts-ui-widget-content-update.md) - [Updating Widget Content by Widget Host (for System Applications Only)](arkts-ui-widget-content-update.md)
# Widget Page Capability Overview # Widget Page Capability Overview
You can leverage the ArkUI declarative paradigm to develop ArkTS widget pages. The following widget pages are automatically generated by a DevEco Studio template. You can adjust the pages based on the real-world service scenarios. You can leverage the ArkUI declarative paradigm to develop ArkTS widget pages. The following widget pages are automatically generated by a DevEco Studio template. You can adjust the pages based on the real-world service scenarios.
![WidgetPreviewPage](figures/WidgetPreviewPage.png) ![WidgetPreviewPage](figures/WidgetPreviewPage.png)
ArkTS widgets have full capabilities of JS widgets, with added animation and custom drawing capabilities plus partial support for components, events, animations, data management, and state management capabilities of the [declarative paradigm](../reference/arkui-ts/ts-components-summary.md). For details, see [Page Capabilities Supported by ArkTS Widgets](#page-capabilities-supported-by-arkts-widgets). ArkTS widgets have full capabilities of JS widgets, with added animation and custom drawing capabilities plus partial support for components, events, animations, data management, and state management capabilities of the [declarative paradigm](../reference/arkui-ts/ts-components-summary.md).
## Page Capabilities Supported by ArkTS Widgets
For details about the page capabilities supported by ArkTS widgets, see [Learning ArkTS](../quick-start/arkts-create-custom-components.md) and [ArkTS-based Declarative Development Paradigm](../reference/arkui-ts/ts-components-summary.md). For details about the capabilities supported by ArkTS widgets, see [Learning ArkTS](../quick-start/arkts-create-custom-components.md) and [ArkTS-based Declarative Development Paradigm](../reference/arkui-ts/ts-components-summary.md).
Only the APIs marked with "supported in ArkTS widgets" can be used for ArkTS widgets. Pay special attention to the capability differences with applications. Only the APIs marked with "supported in ArkTS widgets" can be used for ArkTS widgets. Pay special attention to the differences from applications.
For example, the following description indicates that the @Component decorator can be used in ArkTS widgets. For example, the following description indicates that the @Component decorator can be used in ArkTS widgets.
![WidgetSupportApi](figures/WidgetSupportApi.png) ![WidgetSupportApi](figures/WidgetSupportApi.png)
\ No newline at end of file
# Updating Widget Content Through a Proxy
A widget can be updated through a proxy – a system application that has data sharing enabled – when the widget provider is not running.
## Implementation Principles
**Figure 1** Updating widget content through a proxy
![UpdateWidgetByProxyPrinciple](figures/UpdateWidgetByProxyPrinciple.png)
Compared with the [implementation of the ArkTS widget](../application-models/arkts-ui-widget-working-principles.md#implementation-principles) alone, updating through a proxy involves the data management service and data provider.
- Data management service: provides a mechanism for data sharing among multiple applications.
- Data provider: must be a system application that has data sharing enabled. The shared data is identified through the defined **key** + **subscriberId** combination.
Processing flow of the widget provider (indicated by the blue arrows in the figure):
1. The widget provider sets the **dataProxyEnabled** field to **true** in the **form_config.json** file to enable the update-through-proxy feature.
> **NOTE**
>
> After the update-through-proxy feature is enabled, the settings for [updating periodically](../application-models/arkts-ui-widget-update-by-time.md) do not work.
2. In the [onAddForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) callback, the widget provider returns the **key** + **subscriberId** combination defined by the data provider to the Widget Manager.
3. Widget Manager parses the subscription information of the widget provider and registers a subscription instance with the data management service.
Processing flow of the widget update proxy (indicated by the red arrows in the figure):
1. The data provider uses the **key** + **subscriberId** combination as the data ID to store data to the database.
2. The data management service detects the change in the database and publishes the new data to all currently registered subscription instances.
3. The Widget Manager parses data from the subscription instance and sends the data to the widget rendering service.
4. The widget rendering service runs the widget page code **widgets.abc**, renders based on the new data, and sends the rendered data to the widget component (../reference/arkui-ts/ts-basic-components-formcomponent.md) corresponding to the widget host.
There are two types of shared data provided by the data provider:
- Ephemeral data: data that exists only for a specific period of time and can be subscribed to by system and non-system applications alike.
- Persistent data: data that persists over time and can only be subscribed to by system applications.
The update-through-proxy configuration varies by the type of shared data.
## Widget Provider Development (Ephemeral Data)
- Set the **dataProxyEnabled** field to **true** in the **form_config.json** file to enable the update-through-proxy feature.
```json
{
"forms": [
{
"name": "widget",
"description": "This is a service widget.",
"src": "./ets/widget/pages/WidgetCard.ets",
"uiSyntax": "arkts",
"window": {
"designWidth": 720,
"autoDesignWidth": true
},
"colorMode": "auto",
"isDefault": true,
"updateEnabled": true,
"scheduledUpdateTime": "10:30",
"defaultDimension": "2*2",
"supportDimensions": ["2*2"],
"dataProxyEnabled": true // Enable the update-through-proxy feature.
}
]
}
```
- Configure the subscription information [proxies](../reference/apis/js-apis-app-form-formBindingData.md#proxydata) in the [onAddForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) callback and return the information to the Widget Manager through [formBinding](../reference/apis/js-apis-app-form-formBindingData.md#formbindingdata). In this example, **key** is set to **detail** and **subscriberId** is set to **11**.
> **NOTE**
>
> The value of **key** can be a URI or a simple string. The default value of **subscriberId** is the value of **formId**. The actual value depends on the definition of the data provider.
```ts
import formBindingData from '@ohos.app.form.formBindingData';
let dataShareHelper;
onAddForm(want) {
let formData = {};
let proxies = [
{
"key": "detail",
"subscriberId": "11"
}
]
let formBinding = formBindingData.createFormBindingData(formData);
formBinding["proxies"] = proxies;
return formBinding;
}
```
- In the widget page code file **widgets.abc**, use the variable in LocalStorage to obtain the subscribed data. In this example, the subscribed data is obtained through **'detail'** and displayed in the **\<Text>** component.
```ts
let storage = new LocalStorage();
@Entry(storage)
@Component
struct Index {
@LocalStorageProp('detail') detail: string = 'Loading...';
build() {
Row() {
Column() {
Text(this.detail)
.fontSize('12vp')
.textAlign(TextAlign.Center)
.width('100%')
.height('15%')
}
.width('100%')
}
.height('100%')
}
}
```
## Widget Provider Development (Persistent Data; for System Applications Only)
- Set the **dataProxyEnabled** field to **true** in the **form_config.json** file to enable the update-through-proxy feature.
```json
{
"forms": [
{
"name": "widget",
"description": "This is a service widget.",
"src": "./ets/widget/pages/WidgetCard.ets",
"uiSyntax": "arkts",
"window": {
"designWidth": 720,
"autoDesignWidth": true
},
"colorMode": "auto",
"isDefault": true,
"updateEnabled": true,
"scheduledUpdateTime": "10:30",
"defaultDimension": "2*2",
"supportDimensions": ["2*2"],
"dataProxyEnabled": true // Enable the update-through-proxy feature.
}
]
}
```
- Add a subscription template ([addTemplate]([../reference/apis/js-apis-data-dataShare.md#addtemplate10)) to the [onAddForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) callback and use the template predicates to notify the database of the subscribed data conditions. Then, configure the subscription information [proxies](../reference/apis/js-apis-app-form-formBindingData.md#proxydata) and return it to the Widget Manager through [formBinding](../reference/apis/js-apis-app-form-formBindingData.md#formbindingdata). In the example, the predicate is set to **"list": "select type from TBL00 limit 0,1"**, indicating that the first data record in the **type** column is obtained from the **TBL00** database. The data is returned to the widget page code file **widgets.abc** in {"list":[{"type":"value0"}]} format.
> **NOTE**
>
> - The value of **key** is a URI, which depends on the definition of the data release party.
> - The value of **subscriberId** can be customized. Ensure that the value of **subscriberId** in **addTemplate** is the same as that of **proxies.subscriberId**.
```ts
import formBindingData from '@ohos.app.form.formBindingData';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import dataShare from '@ohos.data.dataShare'
let dataShareHelper;
onAddForm(want) {
let template = {
predicates : {
"list" : "select type from TBL00 limit 0,1"
},
scheduler: ""
}
let subscriberId = "111";
dataShare.createDataShareHelper(this.context, "datashareproxy://com.example.myapplication", {isProxy : true}).then((data) => {
dataShareHelper = data;
dataShareHelper.addTemplate("datashareproxy://com.example.myapplication/test", subscriberId, template);
})
let formData = {};
let proxies = [
{
"key": "datashareproxy://com.example.myapplication/test",
"subscriberId": subscriberId
}
]
let formBinding = formBindingData.createFormBindingData(formData);
formBinding["proxies"] = proxies;
return formBinding;
}
```
- In the widget page code file **widgets.abc**, use the variable in LocalStorage to obtain the subscribed data. In the example, the subscribed data is obtained through **'list'**, and the value of the first element is displayed on the **\<Text>** component.
```ts
let storage = new LocalStorage();
@Entry(storage)
@Component
struct WidgetCard {
readonly ACTION_TYPE: string = 'router';
readonly ABILITY_NAME: string = 'EntryAbility';
readonly MESSAGE: string = 'add detail';
readonly FULL_WIDTH_PERCENT: string = '100%';
readonly FULL_HEIGHT_PERCENT: string = '100%';
@LocalStorageProp('list') list: Array<object> = [{"type": "a"}];
build() {
Row() {
Column() {
Text((this.list[0]["type"]))
.fontSize($r('app.float.font_size'))
}
.width(this.FULL_WIDTH_PERCENT)
}
.height(this.FULL_HEIGHT_PERCENT)
.onClick(() => {
postCardAction(this, {
"action": this.ACTION_TYPE,
"abilityName": this.ABILITY_NAME,
"params": {
"message": this.MESSAGE
}
})
})
}
}
```
## Data Provider Development
For details, see [Data Management](../database/data-mgmt-overview.md).
<!--no_check-->
\ No newline at end of file
# Updating Widget Content by State # Updating Widget Content by State
There are cases where multiple copies of the same widget are added to the home screen to accommodate different needs. In these cases, the widget content needs to be dynamically updated based on the state. This topic exemplifies how this is implemented.
There are cases where multiple copies of the same widget are added to the home screen to accommodate different needs. In these cases, the widget content needs to be dynamically updated based on the state. This topic exemplifies how this is implemented. In the following example, two weather widgets are added to the home screen: one for displaying the weather of London, and the other Beijing, both configured to be updated at 07:00 every morning. The widget provider detects the target city, and then displays the city-specific weather information on the widgets. In the following example, two copies of the weather widget are added to the home screen: one for displaying the weather of London, and the other Beijing, both configured to be updated at 07:00 every morning. The widget provider detects the target city, and then displays the city-specific weather information on the widgets.
- Widget configuration file: Configure the widget to be updated at 07:00 every morning. - Widget configuration file: Configure the widget to be updated at 07:00 every morning.
...@@ -94,7 +95,7 @@ There are cases where multiple copies of the same widget are added to the home s ...@@ -94,7 +95,7 @@ There are cases where multiple copies of the same widget are added to the home s
import formProvider from '@ohos.app.form.formProvider'; import formProvider from '@ohos.app.form.formProvider';
import formBindingData from '@ohos.app.form.formBindingData'; import formBindingData from '@ohos.app.form.formBindingData';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import dataStorage from '@ohos.data.storage' import dataPreferences from '@ohos.data.preferences';
export default class EntryFormAbility extends FormExtensionAbility { export default class EntryFormAbility extends FormExtensionAbility {
onAddForm(want) { onAddForm(want) {
...@@ -102,10 +103,10 @@ There are cases where multiple copies of the same widget are added to the home s ...@@ -102,10 +103,10 @@ There are cases where multiple copies of the same widget are added to the home s
let isTempCard: boolean = want.parameters[formInfo.FormParam.TEMPORARY_KEY]; let isTempCard: boolean = want.parameters[formInfo.FormParam.TEMPORARY_KEY];
if (isTempCard === false) {// If the widget is a normal one, the widget information is persisted. if (isTempCard === false) {// If the widget is a normal one, the widget information is persisted.
console.info('Not temp card, init db for:' + formId); console.info('Not temp card, init db for:' + formId);
let storeDB = dataStorage.getStorageSync(this.context.filesDir + 'myStore') let storeDB = dataPreferences.getPreferences(this.context, 'mystore')
storeDB.putSync('A' + formId, 'false'); storeDB.put('A' + formId, 'false');
storeDB.putSync('B' + formId, 'false'); storeDB.put('B' + formId, 'false');
storeDB.flushSync(); storeDB.flush();
} }
let formData = {}; let formData = {};
return formBindingData.createFormBindingData(formData); return formBindingData.createFormBindingData(formData);
...@@ -113,24 +114,24 @@ There are cases where multiple copies of the same widget are added to the home s ...@@ -113,24 +114,24 @@ There are cases where multiple copies of the same widget are added to the home s
onRemoveForm(formId) { onRemoveForm(formId) {
console.info('onRemoveForm, formId:' + formId); console.info('onRemoveForm, formId:' + formId);
let storeDB = dataStorage.getStorageSync(this.context.filesDir + 'myStore') let storeDB = dataPreferences.getPreferences(this.context, 'mystore')
storeDB.deleteSync('A' + formId); storeDB.delete('A' + formId);
storeDB.deleteSync('B' + formId); storeDB.delete('B' + formId);
} }
// If the widget is a temporary one, it is recommended that the widget information be persisted when the widget is converted to a normal one. // If the widget is a temporary one, it is recommended that the widget information be persisted when the widget is converted to a normal one.
onCastToNormalForm(formId) { onCastToNormalForm(formId) {
console.info('onCastToNormalForm, formId:' + formId); console.info('onCastToNormalForm, formId:' + formId);
let storeDB = dataStorage.getStorageSync(this.context.filesDir + 'myStore') let storeDB = dataPreferences.getPreferences(this.context, 'myStore')
storeDB.putSync('A' + formId, 'false'); storeDB.put('A' + formId, 'false');
storeDB.putSync('B' + formId, 'false'); storeDB.put('B' + formId, 'false');
storeDB.flushSync(); storeDB.flush();
} }
onUpdateForm(formId) { onUpdateForm(formId) {
let storeDB = dataStorage.getStorageSync(this.context.filesDir + 'myStore') let storeDB = dataPreferences.getPreferences(this.context, 'myStore')
let stateA = storeDB.getSync('A' + formId, 'false').toString() let stateA = storeDB.get('A' + formId, 'false').toString()
let stateB = storeDB.getSync('B' + formId, 'false').toString() let stateB = storeDB.get('B' + formId, 'false').toString()
// Update textA in state A. // Update textA in state A.
if (stateA === 'true') { if (stateA === 'true') {
let formInfo = formBindingData.createFormBindingData({ let formInfo = formBindingData.createFormBindingData({
...@@ -150,17 +151,17 @@ There are cases where multiple copies of the same widget are added to the home s ...@@ -150,17 +151,17 @@ There are cases where multiple copies of the same widget are added to the home s
onFormEvent(formId, message) { onFormEvent(formId, message) {
// Store the widget state. // Store the widget state.
console.info('onFormEvent formId:' + formId + 'msg:' + message); console.info('onFormEvent formId:' + formId + 'msg:' + message);
let storeDB = dataStorage.getStorageSync(this.context.filesDir + 'myStore') let storeDB = dataPreferences.getPreferences(this.context, 'myStore')
let msg = JSON.parse(message) let msg = JSON.parse(message)
if (msg.selectA != undefined) { if (msg.selectA != undefined) {
console.info('onFormEvent selectA info:' + msg.selectA); console.info('onFormEvent selectA info:' + msg.selectA);
storeDB.putSync('A' + formId, msg.selectA); storeDB.put('A' + formId, msg.selectA);
} }
if (msg.selectB != undefined) { if (msg.selectB != undefined) {
console.info('onFormEvent selectB info:' + msg.selectB); console.info('onFormEvent selectB info:' + msg.selectB);
storeDB.putSync('B' + formId, msg.selectB); storeDB.put('B' + formId, msg.selectB);
} }
storeDB.flushSync(); storeDB.flush();
} }
}; };
``` ```
...@@ -168,4 +169,4 @@ There are cases where multiple copies of the same widget are added to the home s ...@@ -168,4 +169,4 @@ There are cases where multiple copies of the same widget are added to the home s
> **NOTE** > **NOTE**
> >
> When the local database is used for widget information persistence, it is recommended that [TEMPORARY_KEY](../reference/apis/js-apis-app-form-formInfo.md#formparam) be used to determine whether the currently added widget is a normal one in the [onAddForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) lifecycle callback. If the widget is a normal one, the widget information is directly persisted. If the widget is a temporary one, the widget information is persisted when the widget is converted to a normal one ([onCastToNormalForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#oncasttonormalform)). In addition, the persistent widget information needs to be deleted when the widget is destroyed ([onRemoveForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onremoveform)), preventing the database size from continuously increasing due to repeated widget addition and deletion. > When the local database is used for widget information persistence, it is recommended that [TEMPORARY_KEY](../reference/apis/js-apis-app-form-formInfo.md#formparam) be used in the [onAddForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) lifecycle callback to determine whether the currently added widget is a normal one. If the widget is a normal one, the widget information is directly persisted. If the widget is a temporary one, the widget information is persisted when the widget is converted to a normal one ([onCastToNormalForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#oncasttonormalform)). In addition, the persistent widget information needs to be deleted when the widget is destroyed ([onRemoveForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onremoveform)), preventing the database size from continuously increasing due to repeated widget addition and deletion.
...@@ -5,12 +5,12 @@ Before configuring a widget to update periodically, enable the periodic update f ...@@ -5,12 +5,12 @@ Before configuring a widget to update periodically, enable the periodic update f
The widget framework provides the following modes of updating widgets periodically: The widget framework provides the following modes of updating widgets periodically:
- Set the update interval: The widget will be updated at the specified interval by calling [onUpdateForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onupdateform). You can specify the interval by setting the [updateDuration](arkts-ui-widget-configuration.md) field in the **form_config.json** file. For example, you can configure the widget to update once an hour. - Setting the update interval: The widget will be updated at the specified interval by calling [onUpdateForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onupdateform). You can specify the interval by setting the [updateDuration](arkts-ui-widget-configuration.md) field in the **form_config.json** file. For example, you can configure the widget to update once an hour.
> **NOTE** > **NOTE**
> >
> **updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used. > **updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.
```json ```json
{ {
"forms": [ "forms": [
...@@ -26,22 +26,22 @@ The widget framework provides the following modes of updating widgets periodical ...@@ -26,22 +26,22 @@ The widget framework provides the following modes of updating widgets periodical
"colorMode": "auto", "colorMode": "auto",
"isDefault": true, "isDefault": true,
"updateEnabled": true, // Enable the periodic update feature. "updateEnabled": true, // Enable the periodic update feature.
"scheduledUpdateTime": "10:30", "scheduledUpdateTime": "10:30",
"updateDuration": 2, // Set the interval to update the widget. The value is a natural number, in the unit of 30 minutes. "updateDuration": 2, // Set the update interval. The value is a natural number, in the unit of 30 minutes.
"defaultDimension": "2*2", "defaultDimension": "2*2",
"supportDimensions": ["2*2"] "supportDimensions": ["2*2"]
} }
] ]
} }
``` ```
- Set the scheduled update time: The widget will be updated at the scheduled time every day. You can specify the time by setting the [scheduledUpdateTime](arkts-ui-widget-configuration.md) field in the **form_config.json** file. For example, you can configure the widget to update at 10:30 a.m. every day. - Setting the scheduled update time: The widget will be updated at the scheduled time every day. You can specify the time by setting the [scheduledUpdateTime](arkts-ui-widget-configuration.md) field in the **form_config.json** file. For example, you can configure the widget to update at 10:30 a.m. every day.
> **NOTE** > **NOTE**
> >
> **updateDuration** takes precedence over **scheduledUpdateTime**. For the **scheduledUpdateTime** settings to take effect, set **updateDuration** to **0**. > **updateDuration** takes precedence over **scheduledUpdateTime**. For the **scheduledUpdateTime** settings to take effect, set **updateDuration** to **0**.
```json ```json
{ {
"forms": [ "forms": [
...@@ -65,12 +65,12 @@ The widget framework provides the following modes of updating widgets periodical ...@@ -65,12 +65,12 @@ The widget framework provides the following modes of updating widgets periodical
] ]
} }
``` ```
- Set the next update time: The widget will be updated next time at the specified time. You can specify the time by calling the [setFormNextRefreshTime()](../reference/apis/js-apis-app-form-formProvider.md#setformnextrefreshtime) API. The minimum update interval is 5 minutes. For example, you can configure the widget to update within 5 minutes after the API is called. - Setting the next update time: The widget will be updated next time at the specified time. You can specify the time by calling the [setFormNextRefreshTime()](../reference/apis/js-apis-app-form-formProvider.md#setformnextrefreshtime) API. The minimum update interval is 5 minutes. For example, you can configure the widget to update within 5 minutes after the API is called.
```ts ```ts
import formProvider from '@ohos.app.form.formProvider'; import formProvider from '@ohos.app.form.formProvider';
let formId = '123456789'; // Use the actual widget ID in real-world scenarios. let formId = '123456789'; // Use the actual widget ID in real-world scenarios.
try { try {
// Configure the widget to update in 5 minutes. // Configure the widget to update in 5 minutes.
...@@ -88,12 +88,10 @@ The widget framework provides the following modes of updating widgets periodical ...@@ -88,12 +88,10 @@ The widget framework provides the following modes of updating widgets periodical
``` ```
When periodic update is triggered, the system calls the [onUpdateForm()](../reference/apis/js-apis-app-form-formExtensionAbility.md#onupdateform) lifecycle callback of the FormExtensionAbility. In the callback, [updateForm()](../reference/apis/js-apis-app-form-formProvider.md#updateform) can be used to update the widget by the provider. For details about how to use **onUpdateForm()**, see [Updating Widget Content Through FormExtensionAbility](arkts-ui-widget-event-formextensionability.md). When periodic update is triggered, the system calls the [onUpdateForm()](../reference/apis/js-apis-app-form-formExtensionAbility.md#onupdateform) lifecycle callback of the FormExtensionAbility. In the callback, [updateForm()](../reference/apis/js-apis-app-form-formProvider.md#updateform) can be used to update the widget. For details about how to use **onUpdateForm()**, see [Updating Widget Content Through FormExtensionAbility](arkts-ui-widget-event-formextensionability.md).
> **NOTE** > **NOTE**
> 1. Each widget can be updated at the specified interval for a maximum of 50 times every day, including updates triggered by setting [updateDuration](arkts-ui-widget-configuration.md) or calling [setFormNextRefreshTime()](../reference/apis/js-apis-app-form-formProvider.md#setformnextrefreshtime). When the limit is reached, the widget cannot be updated in this mode again. The number of update times is reset at 00:00 every day. > - Each widget can be updated at the specified interval for a maximum of 50 times every day, including updates triggered by setting [updateDuration](arkts-ui-widget-configuration.md) or calling [setFormNextRefreshTime()](../reference/apis/js-apis-app-form-formProvider.md#setformnextrefreshtime). When the limit is reached, the widget cannot be updated in this mode again. The number of update times is reset at 00:00 every day.
> >- A single timer is used for timing updates at the specified interval. Therefore, if a widget is configured to update at scheduled intervals, the first scheduled update may have a maximum deviation of 30 minutes. For example, if widget A (updated every half an hour) is added at 03:20 and widget B (also updated every half an hour) is added at 03:40, the first update of widget B has a deviation of 10 minutes to the expected time: The timer starts at 03:20 when widget A is added, triggers an update for widget A at 03:50, and triggers another update for widget B at 04:20 (instead of 04:10 as expected).
> 2. The same timer is used for timing updates at the specified interval. Therefore, the first scheduled update of widgets may have a maximum deviation of 30 minutes. For example, the first widget A (updated every half an hour) is added at 03:20. The timer starts and triggers an update every half an hour. The second widget B (updated every half an hour) is added at 03:40. When the timer event is triggered at 03:50, widget A is updated, and widget B will be updated at 04:20 next time. > - Updates at the specified interval and updates at the scheduled time are triggered only when the screen is on. The update action is merely recorded when the screen is off and is performed once the screen is on.
>
> 3. Updates at the specified interval and updates at the scheduled time are triggered only when the screen is on. When the screen is off, the update action is merely recorded. When the screen is on, the update action is performed.
...@@ -3,42 +3,45 @@ ...@@ -3,42 +3,45 @@
## Implementation Principles ## Implementation Principles
**Figure 1** ArkTS widget implementation principles **Figure 1** ArkTS widget implementation principles
![WidgetPrinciple](figures/WidgetPrinciple.png) ![WidgetPrinciple](figures/WidgetPrinciple.png)
- Widget host: an application that displays the widget content and controls the widget location. Only the system application can function as a widget host. - Widget host: an application that displays the widget content and controls the widget location. Only the system application can function as a widget host.
- Widget provider: an application that provides the widget content to display and controls how widget components are laid out and how they interact with users. - Widget provider: an application that provides the widget content to display and controls how widget components are laid out and how they interact with users.
- Widget Manager: a resident agent that manages widgets in the system. It provides the [formProvider](../reference/apis/js-apis-app-form-formProvider.md) and [formHost](../reference/apis/js-apis-app-form-formHost.md) APIs as well as widget management, usage, and periodic updates. - Widget Manager: a resident agent that manages widgets in the system. It provides the [formProvider](../reference/apis/js-apis-app-form-formProvider.md) and [formHost](../reference/apis/js-apis-app-form-formHost.md) APIs as well as the APIs for widget management, usage, and periodic updates.
- Widget rendering service: a service that manages widget rendering instances. Widget rendering instances are bound to the [widget components](../reference/arkui-ts/ts-basic-components-formcomponent.md) on the widget host on a one-to-one basis. The widget rendering service runs the widget page code **widgets.abc** for rendering, and sends the rendered data to the corresponding widget component on the widget host. - Widget rendering service: a service that manages widget rendering instances. Widget rendering instances are bound to the [widget components](../reference/arkui-ts/ts-basic-components-formcomponent.md) on the widget host on a one-to-one basis. The widget rendering service runs the widget page code **widgets.abc** for rendering, and sends the rendered data to the corresponding widget component on the widget host.
**Figure 2** Working principles of the ArkTS widget rendering service **Figure 2** Working principles of the ArkTS widget rendering service
![WidgetRender](figures/WidgetRender.png) ![WidgetRender](figures/WidgetRender.png)
Unlike JS widgets, ArkTS widgets support logic code running. To avoid potential ArkTS widget issues from affecting the use of applications, the widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of an application provider run in the same virtual machine operating environment, and rendering instances of different application providers run in different virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different application providers. During development, pay attention to the use of the [globalThis](uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-page) object. Use one **globalThis** object for widgets by the same application provider, and different **globalThis** objects for widgets by different application providers. Unlike JS widgets, ArkTS widgets support logic code running. The widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of a widget provider run in the same virtual machine operating environment, and rendering instances of different widget providers run in different virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different widget providers. During development, pay attention to the use of the [globalThis](uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-page) object. Use one **globalThis** object for widgets from the same widget provider, and different **globalThis** objects for widgets from different widget providers.
## Advantages of ArkTS Widgets ## Advantages of ArkTS Widgets
As a quick entry to applications, ArkTS widgets have the following advantages over JS widgets: As a quick entry to applications, ArkTS widgets outperform JS widgets in the following aspects:
- Improved development experience and efficiency, thanks to the unified development paradigm - Improved development experience and efficiency, thanks to the unified development paradigm
ArkTS widgets share the same declarative UI development framework as application pages. This means that the page layouts can be directly reused in widgets, improving development experience and efficiency. ArkTS widgets share the same declarative UI development framework as application pages. This means that the page layouts can be directly reused in widgets, improving development experience and efficiency.
**Figure 3** Comparison of widget project structures **Figure 3** Comparison of widget project structures
![WidgetProject](figures/WidgetProject.png) ![WidgetProject](figures/WidgetProject.png)
- More widget features - More widget features
- Animation: The ArkTS widget supports the [attribute animation](../reference/arkui-ts/ts-animatorproperty.md) and [explicit animation](../reference/arkui-ts/ts-explicit-animation.md) capabilities, which can be leveraged to deliver a more engaging experience. - Animation: ArkTS widgets support the [attribute animation](../reference/arkui-ts/ts-animatorproperty.md) and [explicit animation](../reference/arkui-ts/ts-explicit-animation.md) capabilities, which can be leveraged to deliver a more engaging experience.
- Custom drawing: The ArkTS widget allows you to draw graphics with the [Canvas](../reference/arkui-ts/ts-components-canvas-canvas.md) component to present information more vividly. - Custom drawing: ArkTS widgets allow you to draw graphics with the [\<Canvas>](../reference/arkui-ts/ts-components-canvas-canvas.md) component to present information more vividly.
- Logic code execution: The capability to run logic code in widgets means that service logic can be self-closed in widgets, expanding the service application scenarios of widgets. - Logic code execution: The capability to run logic code in widgets means that service logic can be self-closed in widgets, expanding the use cases of widgets.
## Constraints on ArkTS Widgets ## Constraints on ArkTS Widgets
Compared with JS widgets, ArkTS widgets provide more capabilities, but they are also more prone to malicious behavior. The ArkTS widget is displayed in the widget host, which is usually the home screen. To ensure user experience and power consumption, the ArkTS widget capability is restricted as follows: Compared with JS widgets, ArkTS widgets provide more capabilities, but they are also more prone to malicious behavior. To account for the impact on the widget host – typically the home screen, ArkTS widgets are subject to the following restrictions:
- The .so file cannot be loaded. - The .so file cannot be loaded.
...@@ -46,12 +49,14 @@ Compared with JS widgets, ArkTS widgets provide more capabilities, but they are ...@@ -46,12 +49,14 @@ Compared with JS widgets, ArkTS widgets provide more capabilities, but they are
- Only [partial](arkts-ui-widget-page-overview.md) components, events, animations, data management, state management, and API capabilities of the declarative paradigm are supported. - Only [partial](arkts-ui-widget-page-overview.md) components, events, animations, data management, state management, and API capabilities of the declarative paradigm are supported.
- The event processing of the widget is independent of that of the widget host. It is recommended that you do not use the left and right sliding components when the widget host supports left and right swipes to prevent gesture conflicts. - The event processing of the widget is independent of that of the widget host. To prevent gesture conflicts, avoid using swipers in the widget when the widget host supports left and right swipes.
The following features are coming to ArkTS widgets in later versions: In addition, ArkTS widgets do not support the following features:
- Breakpoint debugging - Importing modules
- import statements
- Instant preview - Instant preview
- Breakpoint debugging.
- Hot reload
# Setting Atomic Services to Support Sharing
By means of sharing, users can quickly access atomic services and use their features.
## How to Develop
In the sharing scenario, there are two parties involved: a target application that shares data and an application that obtains the shared data. The two can be physically the same. The target application uses the **onShare()** lifecycle callback to set the data to share. After the target application is started, you can run the **hdc shell aa dump -a** command to check the started services and processes and find its mission ID. After the current application is started, call the **abilityManager.acquireShareData()** API with the mission ID passed in to obtain the shared data.
> **NOTE**
>
> The mission ID of the target application can also be obtained by calling [missionManager.getMissionInfos()](../reference/apis/js-apis-app-ability-missionManager.md#getmissioninfos).
1. The target application calls **UIAbility.onShare()** provided by the UIAbility component to set the data to share. **ohos.extra.param.key.contentTitle** indicates the title of the content to share in the sharing box, **ohos.extra.param.key.shareAbstract** provides an abstract description of the content, and **ohos.extra.param.key.shareUrl** indicates the online address of the service. You need to set these three items as objects, with the key set to **title**, **abstract**, and **url**, respectively.
```ts
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
class MyUIAbility extends UIAbility {
onShare(wantParams) {
console.log('onShare');
wantParams['ohos.extra.param.key.contentTitle'] = {title: "W3"};
wantParams['ohos.extra.param.key.shareAbstract'] = {abstract: "communication for huawei employee"};
wantParams['ohos.extra.param.key.shareUrl'] = {url: "w3.huawei.com"};
}
}
```
2. The current application calls **abilityManager.acquireShareData()** to obtain the data shared by the target application. **missionId** indicates the target application's mission ID, which can be obtained by running the **hdc shell aa dump -a** command or calling the **missionManager.getMissionInfos()** API after the target application is started. **wantParam** indicates the data shared by the target application through the **UIAbility.onShare()** lifecycle callback.
```ts
import abilityManager from '@ohos.app.ability.abilityManager';
try {
abilityManager.acquireShareData(1, (err, wantParam) => {
if (err) {
console.error(`acquireShareData fail, err: ${JSON.stringify(err)}`);
} else {
console.log(`acquireShareData success, data: ${JSON.stringify(wantParam)}`);
}
});
} catch (paramError) {
console.error(`error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}`);
}
```
...@@ -12,7 +12,7 @@ Component startup refers to the behavior of starting or connecting to an applica ...@@ -12,7 +12,7 @@ Component startup refers to the behavior of starting or connecting to an applica
To deliver a better user experience, OpenHarmony restricts the following behavior: To deliver a better user experience, OpenHarmony restricts the following behavior:
- A background application randomly displays a dialog box, such as an ads pop-up. - A background application randomly displays a dialog box, such as an ad pop-up.
- Background applications wake up each other. This type of behavior occupies system resources and increases power consumption, or even causes system frozen. - Background applications wake up each other. This type of behavior occupies system resources and increases power consumption, or even causes system frozen.
...@@ -34,14 +34,14 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol ...@@ -34,14 +34,14 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol
- **Before starting the ServiceAbility or DataAbility component of an application, verify the AssociateWakeUp field of the target application.** - **Before starting the ServiceAbility or DataAbility component of an application, verify the AssociateWakeUp field of the target application.**
- This rule applies only to cross-application scenarios. - This rule applies only to cross-application scenarios.
- This rule is valid only when the target component is ServiceAbility or DataAbility. - This rule is valid only when the target component is ServiceAbility or DataAbility.
- The ServiceAbility and DataAbility of an application can be accessed by others only when **AssociateWakeUp** of the target application is set to **true**. - The ServiceAbility and DataAbility of an application can be accessed by other applications only when **AssociateWakeUp** of the target application is set to **true**.
- The **AssociateWakeUp** field can be configured only for preset applications. For other applications, this field is set to **false** by default. - The **AssociateWakeUp** field can be configured only for preset applications. For other applications, this field is set to **false** by default.
> **NOTE** > **NOTE**
> 1. Component startup control has been implemented since OpenHarmony v3.2 Release. > 1. Component startup control has been implemented since OpenHarmony v3.2 Release.
> >
> 2. The new component startup rules are more strict than the original ones. You must be familiar with the new startup rules to prevent service exceptions. > 2. The new component startup rules are more strict than the original ones. Get familiar with the new startup rules to prevent service exceptions.
......
...@@ -4,8 +4,8 @@ ...@@ -4,8 +4,8 @@
The FA model uses the [config.json file](../quick-start/application-configuration-file-overview-fa.md) to describe the basic information about an application. An application can have multiple modules, and each module has a **config.json** file. The **config.json** file consists of three parts: **app**, **deviceConfig**, and **module**. The **app** tag is used to configure application-level attributes. If an application has multiple modules, the **app** configuration in each **config.json** file must be consistent. The FA model uses the [config.json file](../quick-start/application-configuration-file-overview-fa.md) to describe the basic information about an application. An application can have multiple modules, and each module has a **config.json** file. The **config.json** file consists of three parts: **app**, **deviceConfig**, and **module**. The **app** tag is used to configure application-level attributes. If an application has multiple modules, the **app** configuration in each **config.json** file must be consistent.
The stage model uses the [app.json5](../quick-start/app-configuration-file.md) and [module.json](../quick-start/module-configuration-file.md) files to describe the basic information about an application. An application can have multiple modules but only one **app.json5** file. This file is used to configure application-level attributes and takes effect for all the modules. Each module has a **module.json5** file, which is used to configure module-level attributes and takes effect only for the current module. The stage model uses the [app.json5](../quick-start/app-configuration-file.md) and [module.json](../quick-start/module-configuration-file.md) files to describe the basic information about an application. An application can have multiple modules but only one **app.json5** file. This file is used to configure application-level attributes and the configuration applies to all the modules. Each module has a **module.json5** file, which is used to configure module-level attributes and the configuration applies only for the current module.
**Figure 1** Configuration file differences **Figure 1** Configuration file differences
![comparison-of-configuration-file](figures/comparison-of-configuration-file.png)
![comparison-of-configuration-file](figures/comparison-of-configuration-file.png)
\ No newline at end of file
...@@ -16,14 +16,14 @@ The following sample code enables the PageAbility to create connection callback ...@@ -16,14 +16,14 @@ The following sample code enables the PageAbility to create connection callback
```ts ```ts
import rpc from "@ohos.rpc" import rpc from "@ohos.rpc"
import prompt from '@system.prompt' import promptAction from '@ohos.promptAction'
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
let option = { let option = {
onConnect: function onConnectCallback(element, proxy) { onConnect: function onConnectCallback(element, proxy) {
console.info(`onConnectLocalService onConnectDone`) console.info(`onConnectLocalService onConnectDone`)
if (proxy === null) { if (proxy === null) {
prompt.showToast({ promptAction.showToast({
message: "Connect service failed" message: "Connect service failed"
}) })
return return
...@@ -33,19 +33,19 @@ let option = { ...@@ -33,19 +33,19 @@ let option = {
let option = new rpc.MessageOption() let option = new rpc.MessageOption()
data.writeInterfaceToken("connect.test.token") data.writeInterfaceToken("connect.test.token")
proxy.sendRequest(0, data, reply, option) proxy.sendRequest(0, data, reply, option)
prompt.showToast({ promptAction.showToast({
message: "Connect service success" message: "Connect service success"
}) })
}, },
onDisconnect: function onDisconnectCallback(element) { onDisconnect: function onDisconnectCallback(element) {
console.info(`onConnectLocalService onDisconnectDone element:${element}`) console.info(`onConnectLocalService onDisconnectDone element:${element}`)
prompt.showToast({ promptAction.showToast({
message: "Disconnect service success" message: "Disconnect service success"
}) })
}, },
onFailed: function onFailedCallback(code) { onFailed: function onFailedCallback(code) {
console.info(`onConnectLocalService onFailed errCode:${code}`) console.info(`onConnectLocalService onFailed errCode:${code}`)
prompt.showToast({ promptAction.showToast({
message: "Connect local service onFailed" message: "Connect local service onFailed"
}) })
} }
......
# Context Switching # Context Switching
| API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API or Field in the Stage Model| | API in the FA Model| Corresponding .d.ts File in the Stage Model| Corresponding API or Field in the Stage Model|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| [getOrCreateLocalDir(callback:AsyncCallback&lt;string&gt;):void;](../reference/apis/js-apis-inner-app-context.md#contextgetorcreatelocaldir7)<br>[getOrCreateLocalDir():Promise&lt;string&gt;;](../reference/apis/js-apis-inner-app-context.md#contextgetorcreatelocaldir7-1) | There is no corresponding API in the stage model.| Applications developed on the stage model do not have the operation permission in the application root directory. Therefore, no corresponding API is provided.| | [getOrCreateLocalDir(callback:AsyncCallback&lt;string&gt;):void;](../reference/apis/js-apis-inner-app-context.md#contextgetorcreatelocaldir7)<br>[getOrCreateLocalDir():Promise&lt;string&gt;;](../reference/apis/js-apis-inner-app-context.md#contextgetorcreatelocaldir7-1) | There is no corresponding API in the stage model.| Applications developed on the stage model do not have the operation permission in the application root directory. Therefore, no corresponding API is provided.|
| [verifyPermission(permission:string,options:PermissionOptions,callback:AsyncCallback&lt;number&gt;):void;](../reference/apis/js-apis-inner-app-context.md#contextverifypermission7)<br>[verifyPermission(permission:string,callback:AsyncCallback&lt;number&gt;):void;](../reference/apis/js-apis-inner-app-context.md#contextverifypermission7-1)<br>[verifyPermission(permission:string,options?:PermissionOptions):Promise&lt;number&gt;;](../reference/apis/js-apis-inner-app-context.md#contextverifypermission7-2) | \@ohos.abilityAccessCtrl.d.ts | [verifyAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus;](../reference/apis/js-apis-abilityAccessCtrl.md#verifyaccesstokensync9)<br>[verifyAccessToken(tokenID: number, permissionName: Permissions): Promise&lt;GrantStatus&gt;;](../reference/apis/js-apis-abilityAccessCtrl.md#verifyaccesstoken9) | | [verifyPermission(permission:string,options:PermissionOptions,callback:AsyncCallback&lt;number&gt;):void;](../reference/apis/js-apis-inner-app-context.md#contextverifypermission7)<br>[verifyPermission(permission:string,callback:AsyncCallback&lt;number&gt;):void;](../reference/apis/js-apis-inner-app-context.md#contextverifypermission7-1)<br>[verifyPermission(permission:string,options?:PermissionOptions):Promise&lt;number&gt;;](../reference/apis/js-apis-inner-app-context.md#contextverifypermission7-2) | \@ohos.abilityAccessCtrl.d.ts | [verifyAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus;](../reference/apis/js-apis-abilityAccessCtrl.md#verifyaccesstokensync9)<br>[verifyAccessToken(tokenID: number, permissionName: Permissions): Promise&lt;GrantStatus&gt;;](../reference/apis/js-apis-abilityAccessCtrl.md#verifyaccesstoken9) |
| [requestPermissionsFromUser(permissions:Array&lt;string&gt;,requestCode:number,resultCallback:AsyncCallback&lt;PermissionRequestResult&gt;):void;](../reference/apis/js-apis-inner-app-context.md#contextrequestpermissionsfromuser7)<br/>[requestPermissionsFromUser(permissions:Array&lt;string&gt;,requestCode:number):Promise&lt;PermissionRequestResult&gt;;](../reference/apis/js-apis-inner-app-context.md#contextrequestpermissionsfromuser7-1) | \@ohos.abilityAccessCtrl.d.ts | [requestPermissionsFromUser(context: Context, permissionList: Array&lt;Permissions&gt;, requestCallback: AsyncCallback&lt;PermissionRequestResult&gt;) : void;](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9)<br/>[requestPermissionsFromUser(context: Context, permissionList: Array&lt;Permissions&gt;) : Promise&lt;PermissionRequestResult&gt;;](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9-1) | | [requestPermissionsFromUser(permissions:Array&lt;string&gt;,requestCode:number,resultCallback:AsyncCallback&lt;PermissionRequestResult&gt;):void;](../reference/apis/js-apis-inner-app-context.md#contextrequestpermissionsfromuser7)<br>[requestPermissionsFromUser(permissions:Array&lt;string&gt;,requestCode:number):Promise&lt;PermissionRequestResult&gt;;](../reference/apis/js-apis-inner-app-context.md#contextrequestpermissionsfromuser7-1) | \@ohos.abilityAccessCtrl.d.ts | [requestPermissionsFromUser(context: Context, permissionList: Array&lt;Permissions&gt;, requestCallback: AsyncCallback&lt;PermissionRequestResult&gt;) : void;](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9)<br>[requestPermissionsFromUser(context: Context, permissionList: Array&lt;Permissions&gt;) : Promise&lt;PermissionRequestResult&gt;;](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9-1) |
| [getApplicationInfo(callback:AsyncCallback&lt;ApplicationInfo&gt;):void;](../reference/apis/js-apis-inner-app-context.md#contextgetapplicationinfo7)<br>[getApplicationInfo():Promise&lt;ApplicationInfo&gt;;](../reference/apis/js-apis-inner-app-context.md#contextgetapplicationinfo7-1) | application\Context.d.ts | [applicationInfo: ApplicationInfo;](../reference/apis/js-apis-inner-application-context.md#attributes)| | [getApplicationInfo(callback:AsyncCallback&lt;ApplicationInfo&gt;):void;](../reference/apis/js-apis-inner-app-context.md#contextgetapplicationinfo7)<br>[getApplicationInfo():Promise&lt;ApplicationInfo&gt;;](../reference/apis/js-apis-inner-app-context.md#contextgetapplicationinfo7-1) | application\Context.d.ts | [applicationInfo: ApplicationInfo;](../reference/apis/js-apis-inner-application-context.md#attributes)|
| [getBundleName(callback : AsyncCallback&lt;string&gt;): void;](../reference/apis/js-apis-inner-app-context.md#contextgetbundlename7)<br>[getBundleName(): Promise&lt;string&gt;;](../reference/apis/js-apis-inner-app-context.md#contextgetbundlename7-1) | application\UIAbilityContext.d.ts | [abilityInfo.bundleName: string;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#attributes)| | [getBundleName(callback : AsyncCallback&lt;string&gt;): void;](../reference/apis/js-apis-inner-app-context.md#contextgetbundlename7)<br>[getBundleName(): Promise&lt;string&gt;;](../reference/apis/js-apis-inner-app-context.md#contextgetbundlename7-1) | application\UIAbilityContext.d.ts | [abilityInfo.bundleName: string;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#attributes)|
| [getDisplayOrientation(callback : AsyncCallback&lt;bundle.DisplayOrientation&gt;): void;](../reference/apis/js-apis-inner-app-context.md#contextgetdisplayorientation7)<br>[getDisplayOrientation(): Promise&lt;bundle.DisplayOrientation&gt;;](../reference/apis/js-apis-inner-app-context.md#contextgetdisplayorientation7-1) | \@ohos.screen.d.ts | [readonly orientation: Orientation;](../reference/apis/js-apis-screen.md#orientation) | | [getDisplayOrientation(callback : AsyncCallback&lt;bundle.DisplayOrientation&gt;): void;](../reference/apis/js-apis-inner-app-context.md#contextgetdisplayorientation7)<br>[getDisplayOrientation(): Promise&lt;bundle.DisplayOrientation&gt;;](../reference/apis/js-apis-inner-app-context.md#contextgetdisplayorientation7-1) | \@ohos.screen.d.ts | [readonly orientation: Orientation;](../reference/apis/js-apis-screen.md#orientation) |
...@@ -26,3 +26,5 @@ ...@@ -26,3 +26,5 @@
| [getAbilityInfo(callback:AsyncCallback&lt;AbilityInfo&gt;):void;](../reference/apis/js-apis-inner-app-context.md#contextgetabilityinfo7)<br>[getAbilityInfo():Promise&lt;AbilityInfo&gt;;](../reference/apis/js-apis-inner-app-context.md#contextgetabilityinfo7-1) | application\UIAbilityContext.d.ts | [abilityInfo: AbilityInfo;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#attributes)| | [getAbilityInfo(callback:AsyncCallback&lt;AbilityInfo&gt;):void;](../reference/apis/js-apis-inner-app-context.md#contextgetabilityinfo7)<br>[getAbilityInfo():Promise&lt;AbilityInfo&gt;;](../reference/apis/js-apis-inner-app-context.md#contextgetabilityinfo7-1) | application\UIAbilityContext.d.ts | [abilityInfo: AbilityInfo;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#attributes)|
| [isUpdatingConfigurations(callback:AsyncCallback&lt;boolean&gt;):void;](../reference/apis/js-apis-inner-app-context.md#contextisupdatingconfigurations7)<br>[isUpdatingConfigurations():Promise&lt;boolean&gt;;](../reference/apis/js-apis-inner-app-context.md#contextisupdatingconfigurations7-1) | There is no corresponding API in the stage model.| OpenHarmony applications do not restart when the system environment changes. The **onConfigurationUpdated** callback is invoked to notify the applications of the changes. This API provides an empty implementation in the FA model, and the stage model does not provide a corresponding API.| | [isUpdatingConfigurations(callback:AsyncCallback&lt;boolean&gt;):void;](../reference/apis/js-apis-inner-app-context.md#contextisupdatingconfigurations7)<br>[isUpdatingConfigurations():Promise&lt;boolean&gt;;](../reference/apis/js-apis-inner-app-context.md#contextisupdatingconfigurations7-1) | There is no corresponding API in the stage model.| OpenHarmony applications do not restart when the system environment changes. The **onConfigurationUpdated** callback is invoked to notify the applications of the changes. This API provides an empty implementation in the FA model, and the stage model does not provide a corresponding API.|
| [printDrawnCompleted(callback:AsyncCallback&lt;void&gt;):void;](../reference/apis/js-apis-inner-app-context.md#contextprintdrawncompleted7)<br>[printDrawnCompleted():Promise&lt;void&gt;;](../reference/apis/js-apis-inner-app-context.md#contextprintdrawncompleted7-1) | There is no corresponding API in the stage model.| This API provides an empty implementation in the FA model. The stage model does not provide a corresponding API.| | [printDrawnCompleted(callback:AsyncCallback&lt;void&gt;):void;](../reference/apis/js-apis-inner-app-context.md#contextprintdrawncompleted7)<br>[printDrawnCompleted():Promise&lt;void&gt;;](../reference/apis/js-apis-inner-app-context.md#contextprintdrawncompleted7-1) | There is no corresponding API in the stage model.| This API provides an empty implementation in the FA model. The stage model does not provide a corresponding API.|
<!--no_check-->
\ No newline at end of file
...@@ -9,18 +9,18 @@ The following sample code shows how to create a DataAbility: ...@@ -9,18 +9,18 @@ The following sample code shows how to create a DataAbility:
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
import dataAbility from '@ohos.data.dataAbility' import dataAbility from '@ohos.data.dataAbility'
import dataRdb from '@ohos.data.rdb' import relationalStore from '@ohos.data.relationalStore'
const TABLE_NAME = 'book' const TABLE_NAME = 'book'
const STORE_CONFIG = { name: 'book.db' } const STORE_CONFIG = { name: 'book.db' }
const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS book(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, introduction TEXT NOT NULL)' const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS book(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, introduction TEXT NOT NULL)'
let rdbStore: dataRdb.RdbStore = undefined let rdbStore: relationalStore.RdbStore = undefined
export default { export default {
onInitialized(abilityInfo) { onInitialized(abilityInfo) {
console.info('DataAbility onInitialized, abilityInfo:' + abilityInfo.bundleName) console.info('DataAbility onInitialized, abilityInfo:' + abilityInfo.bundleName)
let context = featureAbility.getContext() let context = featureAbility.getContext()
dataRdb.getRdbStore(context, STORE_CONFIG, 1, (err, store) => { relationalStore.getRdbStore(context, STORE_CONFIG, (err, store) => {
console.info('DataAbility getRdbStore callback') console.info('DataAbility getRdbStore callback')
store.executeSql(SQL_CREATE_TABLE, []) store.executeSql(SQL_CREATE_TABLE, [])
rdbStore = store rdbStore = store
......
...@@ -7,9 +7,9 @@ The DataAbility component in the FA model corresponds to the DataShareExtensionA ...@@ -7,9 +7,9 @@ The DataAbility component in the FA model corresponds to the DataShareExtensionA
The DataShareExtensionAbility class provides system APIs. Only system applications can create DataShareExtensionAbility instances. Therefore, DataAbility switching adopts different policies for system applications and third-party applications. The DataShareExtensionAbility class provides system APIs. Only system applications can create DataShareExtensionAbility instances. Therefore, DataAbility switching adopts different policies for system applications and third-party applications.
## Switching a DataAbility of a System Application ## Switching a DataAbility for a System Application
The procedure for switching a DataAbility of a system application is similar to the procedure of PageAbility switching. The procedure for switching a DataAbility for a system application is similar to the procedure of PageAbility switching.
1. Create a DataShareExtensionAbility in the stage model. 1. Create a DataShareExtensionAbility in the stage model.
...@@ -34,7 +34,7 @@ The procedure for switching a DataAbility of a system application is similar to ...@@ -34,7 +34,7 @@ The procedure for switching a DataAbility of a system application is similar to
| call?(method: string, arg: string, extras: PacMap, callback: AsyncCallback&lt;PacMap&gt;): void | NA | This method is not provided in the stage model. You need to implement the functionality based on service functions.| | call?(method: string, arg: string, extras: PacMap, callback: AsyncCallback&lt;PacMap&gt;): void | NA | This method is not provided in the stage model. You need to implement the functionality based on service functions.|
## Switching a DataAbility of a Third-Party Application ## Switching a DataAbility for a Third-Party Application
In the stage model, third-party applications cannot provide data services for other third-party applications. You can select a switching solution based on your service requirements. In the stage model, third-party applications cannot provide data services for other third-party applications. You can select a switching solution based on your service requirements.
......
# DataAbilityHelper Switching # DataAbilityHelper Switching
| API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| | API in the FA Model| Corresponding .d.ts File in the Stage Model| Corresponding API in the Stage Model|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| [openFile(uri: string, mode: string, callback: AsyncCallback&lt;number&gt;): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperopenfile)<br>[openFile(uri: string, mode: string): Promise&lt;number&gt;;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperopenfile-1) | \@ohos.data.fileAccess.d.ts | [openFile(uri: string, flags: OPENFLAGS) : Promise&lt;number&gt;;](../reference/apis/js-apis-fileAccess.md#fileaccesshelperopenfile)<br>[openFile(uri: string, flags: OPENFLAGS, callback: AsyncCallback&lt;number&gt;) : void;](../reference/apis/js-apis-fileAccess.md#fileaccesshelperopenfile) | | [openFile(uri: string, mode: string, callback: AsyncCallback&lt;number&gt;): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperopenfile)<br>[openFile(uri: string, mode: string): Promise&lt;number&gt;;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperopenfile-1) | \@ohos.data.fileAccess.d.ts | [openFile(uri: string, flags: OPENFLAGS) : Promise&lt;number&gt;;](../reference/apis/js-apis-fileAccess.md#fileaccesshelperopenfile)<br>[openFile(uri: string, flags: OPENFLAGS, callback: AsyncCallback&lt;number&gt;) : void;](../reference/apis/js-apis-fileAccess.md#fileaccesshelperopenfile) |
| [on(type: 'dataChange', uri: string, callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperon) | \@ohos.data.dataShare.d.ts | [on(type: 'dataChange', uri: string, callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-data-dataShare.md#ondatachange) | | [on(type: 'dataChange', uri: string, callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperon) | \@ohos.data.dataShare.d.ts | [on(type: 'dataChange', uri: string, callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-data-dataShare.md#ondatachange) |
......
# EnterpriseAdminExtensionAbility Development # EnterpriseAdminExtensionAbility
## Introduction to EnterpriseAdminExtensionAbility ## Introduction to EnterpriseAdminExtensionAbility
...@@ -8,34 +8,35 @@ EnterpriseAdminExtensionAbility is a mandatory component for Mobile Device Manag ...@@ -8,34 +8,35 @@ EnterpriseAdminExtensionAbility is a mandatory component for Mobile Device Manag
EnterpriseAdminExtensionAbility is applicable only to enterprise administrator applications. EnterpriseAdminExtensionAbility is applicable only to enterprise administrator applications.
## Observing Activation/Deactivation of a Device Administrator Application and Installation/Removal of an Application
## Observing Activation/Deactivation of a Device Administrator Application and Installation/Uninstallation of an Application
### Overview ### Overview
**onAdminEnabled**: When an enterprise administrator or employee deploys an MDM application and activates the device administrator application, this callback is invoked to notify the MDM application that the DeviceAdmin permission is activated. The initialization policy of the MDM application can set in **onAdminEnabled**. **onAdminEnabled**: called when an enterprise administrator or employee deploys an MDM application and enables the DeviceAdmin permission for the application. The MDM application can set the initialization policy in the **onAdminEnabled** callback.
**onAdminDisabled**: When the device administrator application is deactivated, the callback is invoked to notify the MDM application that the DeviceAdmin permission is deactivated. **onAdminDisabled**: called when the system or employee disables the DeviceAdmin permission to notify the enterprise administrator that the device is no longer managed.
**onBundleAdded**: The enterprise administrator can subscribe to application installation and uninstallation events. When an application is installed on an enterprise device, the MDM application reports the event in this callback to notify the enterprise administrator. **onBundleAdded**: The enterprise administrator can subscribe to application installation events. When an application is installed on an enterprise device, the MDM application reports the event in this callback to notify the enterprise administrator.
**onBundleRemoved**: When an application is removed from an enterprise device, the MDM application reports the event in this callback to notify the enterprise administrator. **onBundleRemoved**: The enterprise administrator can subscribe to application uninstallation events. When an application is uninstalled on an enterprise device, the MDM application reports the event in this callback to notify the enterprise administrator.
### Available APIs ### Available APIs
| Class | API | Description | | Class | API | Description |
| ------------------------------ | ----------------------------------------- | ---------------------------- | | ------------------------------ | ----------------------------------------- | ---------------------------- |
| EnterpriseAdminExtensionAbility | onAdminEnabled(): void | Called when a device administrator application is activated. | | EnterpriseAdminExtensionAbility | onAdminEnabled(): void | Called when the device administrator application is disabled. |
| EnterpriseAdminExtensionAbility | onAdminDisabled(): void | Called when a device administrator application is deactivated.| | EnterpriseAdminExtensionAbility | onAdminDisabled(): void | Called when the device administrator application is enabled.|
| EnterpriseAdminExtensionAbility | onBundleAdded(bundleName: string): void | Called when an application is installed on a device. | | EnterpriseAdminExtensionAbility | onBundleAdded(bundleName: string): void | Called when the MDM application is installed. |
| EnterpriseAdminExtensionAbility | onBundleRemoved(bundleName: string): void | Called when an application is removed from a device. | | EnterpriseAdminExtensionAbility | onBundleRemoved(bundleName: string): void | Called when the MDM application is uninstalled. |
### How to Develop ### How to Develop
To implement EnterpriseAdminExtensionAbility, you need to activate the device administrator application and create **ExtensionAbility** in the code directory of the device administrator application. The procedure is as follows: To implement EnterpriseAdminExtensionAbility, you need to activate the device administrator application and create **ExtensionAbility** in the code directory of the device administrator application. The procedure is as follows:
1. In the **ets** directory of the target module, right-click and choose **New > Directory** to create a directory named **EnterpriseExtAbility**. 1. In the **ets** directory of the target module, right-click and choose **New > Directory** to create a directory named **EnterpriseExtAbility**.
2. Right-click the **EnterpriseExtAbility** directory, and choose **New > TypeScript File** to create a file named **EnterpriseExtAbility.ts**. 2. Right-click the **EnterpriseExtAbility** directory and choose **New > TypeScript File** to create a file named **EnterpriseExtAbility.ts**.
3. Open the **EnterpriseExtAbility.ts** file and import the **EnterpriseAdminExtensionAbility** module. Inherit the **EnterpriseAdminExtensionAbility** module to the custom class and add application notification callbacks, such as **onAdminEnabled()** and **onAdminDisabled()**. When the device administrator application is activated or deactivated, the device administrator can receive notifications. 3. Open the **EnterpriseExtAbility.ts** file and import the **EnterpriseAdminExtensionAbility** module. Customize a class that inherits from **EnterpriseAdminExtensionAbility** and add the required callbacks, such as **onAdminEnabled()** and **onAdminDisabled()**, When the device administrator application is activated or deactivated, the device administrator can receive notifications.
```ts ```ts
import EnterpriseAdminExtensionAbility from '@ohos.enterprise.EnterpriseAdminExtensionAbility'; import EnterpriseAdminExtensionAbility from '@ohos.enterprise.EnterpriseAdminExtensionAbility';
......
# ExtensionAbility Component Overview # ExtensionAbility Overview
The ExtensionAbility component is used for specific scenarios such as widgets and input methods. The ExtensionAbility component is used for specific scenarios such as widget development and input method development.
An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionabilitytype) is provided for every specific scenario. All types of ExtensionAbility components are managed by the corresponding system services in a unified manner. For example, the InputMethodExtensionAbility component is managed by the input method management service. The following ExtensionAbility types are supported: An [ExtensionAbility type](../reference/apis/js-apis-bundleManager.md#extensionabilitytype) is provided for every specific scenario. All types of ExtensionAbility components are managed by the corresponding system services in a unified manner. For example, the InputMethodExtensionAbility component is managed by the input method management service. The following ExtensionAbility types are supported:
- [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md): ExtensionAbility component of the form type, which provides APIs related to widgets. - [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md): ExtensionAbility component of the form type, which provides APIs related to widgets.
...@@ -13,7 +13,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab ...@@ -13,7 +13,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab
- [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md): ExtensionAbility component of the input_method type, which is used to develop input method applications. - [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md): ExtensionAbility component of the input_method type, which is used to develop input method applications.
- [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md): ExtensionAbility component of the service type, which provides APIs related to background service scenarios. - [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md): ExtensionAbility component of the service type, which provides APIs related to background services.
- [AccessibilityExtensionAbility](../reference/apis/js-apis-application-accessibilityExtensionAbility.md): ExtensionAbility component of the accessibility type, which provides APIs related to the accessibility feature. - [AccessibilityExtensionAbility](../reference/apis/js-apis-application-accessibilityExtensionAbility.md): ExtensionAbility component of the accessibility type, which provides APIs related to the accessibility feature.
...@@ -26,16 +26,15 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab ...@@ -26,16 +26,15 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab
- [EnterpriseAdminExtensionAbility](../reference/apis/js-apis-EnterpriseAdminExtensionAbility.md): ExtensionAbility component of the enterprise_admin type, which provides APIs for processing enterprise management events, such as application installation events on devices and events indicating too many incorrect screen-lock password attempts. - [EnterpriseAdminExtensionAbility](../reference/apis/js-apis-EnterpriseAdminExtensionAbility.md): ExtensionAbility component of the enterprise_admin type, which provides APIs for processing enterprise management events, such as application installation events on devices and events indicating too many incorrect screen-lock password attempts.
> **NOTE** > **NOTE**
> >
> 1. Third-party applications cannot implement ServiceExtensionAbility, DataShareExtensionAbility, StaticSubscriberExtensionAbility, or WindowExtensionAbility. >- Third-party applications cannot implement ServiceExtensionAbility, DataShareExtensionAbility, StaticSubscriberExtensionAbility, or WindowExtensionAbility. They can use other types of ExtensionAbility components that have been defined.
> >
> 2. To implement transaction processing in the background for a third-party application, use background tasks rather than ServiceExtensionAbility. For details, see [Background Task](../task-management/background-task-overview.md). >- To implement transaction processing in the background for a third-party application, use background tasks rather than ServiceExtensionAbility. For details, see [Background Task](../task-management/background-task-overview.md).
>
> 3. Third-party applications can use other types of ExtensionAbility components that have been defined.
## Using ExtensionAbility of the Specified Type ## Using ExtensionAbility of the Specified Type
All types of ExtensionAbility components are started by the corresponding system management service, rather than applications, so that their lifecycles are under control by the system. The caller of the ExtensionAbility component does not need to care about its lifecycle. Each type of ExtensionAbility component is started by the corresponding system management service, rather than applications, so that its lifecycle is under system control. The caller of the ExtensionAbility component does not need to care about its lifecycle.
The following uses [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md) as an example. As shown in the figure below, when an application calls the InputMethodExtensionAbility component, the input method management service is called first. The input method management service starts the InputMethodExtensionAbility component, returns the component to the application, and starts to manage its lifecycle. The following uses [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md) as an example. As shown in the figure below, when an application calls the InputMethodExtensionAbility component, the input method management service is called first. The input method management service starts the InputMethodExtensionAbility component, returns the component to the application, and starts to manage its lifecycle.
...@@ -46,18 +45,18 @@ The following uses [InputMethodExtensionAbility](../reference/apis/js-apis-input ...@@ -46,18 +45,18 @@ The following uses [InputMethodExtensionAbility](../reference/apis/js-apis-input
## Implementing ExtensionAbility of the Specified Type ## Implementing ExtensionAbility of the Specified Type
The following uses [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md) as an example. The widget framework provides the base class [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md). You derive this base class to create your own class (such as **MyFormExtensionAbility**), implement the callbacks, such as **onCreate()** and **onUpdateForm()**, to provide specific widget functionalities. For details, see [FormExtensionAbility](service-widget-overview.md). The following uses [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md) as an example. The widget framework provides the base class [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md). You can derive this base class to create your own class (for example, **MyFormExtensionAbility**) and implement the callbacks, such as **onCreate()** and **onUpdateForm()**, to provide specific widget features. For details, see [FormExtensionAbility](service-widget-overview.md).
You do not need to care when to add or delete a widget. The lifecycle of the FormExtensionAbility instance and the lifecycle of the ExtensionAbility process where the FormExtensionAbility instance is located are scheduled and managed by FormManagerService. You do not need to care when to add or delete a widget. The lifecycle of the FormExtensionAbility instance and the lifecycle of the ExtensionAbility process where the FormExtensionAbility instance is located are managed by FormManagerService.
![form_extension](figures/form_extension.png) ![form_extension](figures/form_extension.png)
> **NOTE** > **NOTE**
> >
> For an application, all ExtensionAbility components of the same type run in an independent process, whereas UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility run in another independent process. For details, see [Process Model (Stage Model)](process-model-stage.md). > For an application, all ExtensionAbility components of the same type run in an independent process, whereas the UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components run in another independent process. For details, see [Process Model (Stage Model)](process-model-stage.md).
> >
> For example, an application has one UIAbility component, one ServiceExtensionAbility, one DataShareExtensionAbility, two FormExtensionAbility, and one ImeExtensionAbility. When the application is running, there are three processes: > For example, if an application has one UIAbility component, one ServiceExtensionAbility component, one DataShareExtensionAbility component, two FormExtensionAbility components, and one ImeExtensionAbility component, there will be three processes when the application is running.
> >
> - UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility run in an independent process. > - UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility run in an independent process.
> >
......
...@@ -4,22 +4,23 @@ ...@@ -4,22 +4,23 @@
The FA model is supported by API version 8 and earlier versions, and the stage model is recommended since API version 9. The FA model and stage model have their respective components. The FA model provides three types of application components: PageAbility, ServiceAbility, and DataAbility. The stage model provides two types of application components: UIAbility and ExtensionAbility. The FA model is supported by API version 8 and earlier versions, and the stage model is recommended since API version 9. The FA model and stage model have their respective components. The FA model provides three types of application components: PageAbility, ServiceAbility, and DataAbility. The stage model provides two types of application components: UIAbility and ExtensionAbility.
You cannot use both models for the development of an application (see the figure below). However, a device (system) can contain applications developed on both models (scenario 3 in the figure below). In this case, their components may interact with each other. You cannot use both models for the development of an application (see the figure below). However, a device (system) can contain applications developed on different models (scenario 3 in the figure below). In this case, their components may interact with each other.
**Figure 1** Coexistent application components of the FA model and stage model
Figure 1 Coexistent application components of the FA model and stage model
![coexistence-of-FAandStage](figures/coexistence-of-FAandStage.png) ![coexistence-of-FAandStage](figures/coexistence-of-FAandStage.png)
The following table lists the possible interaction scenarios. You must pay attention to the concerns listed below during your application development. The following table lists the possible interaction scenarios and the concerns of each scenario.
Table 1 Application component interaction scenarios **Table 1** Application component interaction scenarios
| Interaction Scenario| Concerns| | Interaction Scenario| Concerns|
| -------- | -------- | | -------- | -------- |
| [Starting a UIAbility from the FA Model](start-uiability-from-fa.md) | Set **bundleName** and **abilityName** in the **want** parameter to the bundle name and ability name of the UIAbility in the stage model.| | [Starting a UIAbility from the FA Model](start-uiability-from-fa.md)| Set **bundleName** and **abilityName** in the **want** parameter to the bundle name and ability name of the UIAbility in the stage model.|
| [Connecting to a ServiceExtensionAbility from the FA Model](bind-serviceextensionability-from-fa.md) | Set **bundleName** and **abilityName** in the **want** parameter to the bundle name and ability name of the ServiceExtensionAbility in the stage model.| | [Connecting to a ServiceExtensionAbility from the FA Model](bind-serviceextensionability-from-fa.md)| Set **bundleName** and **abilityName** in the **want** parameter to the bundle name and ability name of the ServiceExtensionAbility in the stage model.|
| [Accessing a DataShareExtensionAbility from the FA Model](access-datashareextensionability-from-fa.md) | No code modification is required. However, you need to understand the API compatibility of **DataShareHelper** and **DataAbilityHelper**.| | [Accessing a DataShareExtensionAbility from the FA Model](access-datashareextensionability-from-fa.md)| No code modification is required. However, you need to understand the API compatibility of **DataShareHelper** and **DataAbilityHelper**.|
| [Starting a PageAbility from the Stage Model](start-pageability-from-stage.md) | Set **bundleName** and **abilityName** in the **want** parameter to the bundle name and ability name of the PageAbility in the FA model.| | [Starting a PageAbility from the Stage Model](start-pageability-from-stage.md)| Set **bundleName** and **abilityName** in the **want** parameter to the bundle name and ability name of the PageAbility in the FA model.|
| [Connecting to a ServiceAbility from the Stage Model](bind-serviceability-from-stage.md) | Set **bundleName** and **abilityName** in the **want** parameter to the bundle name and ability name of the ServiceAbility in the FA model.| | [Connecting to a ServiceAbility from the Stage Model](bind-serviceability-from-stage.md)| Set **bundleName** and **abilityName** in the **want** parameter to the bundle name and ability name of the ServiceAbility in the FA model.|
| Accessing a DataAbility from the Stage Model | This type of access is not supported.| | Accessing a DataAbility from the Stage Model| This type of access is not supported.|
# featureAbility Switching # featureAbility Switching
| API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| | API in the FA Model| Corresponding .d.ts File in the Stage Model| Corresponding API in the Stage Model|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| [getWant(callback: AsyncCallback&lt;Want&gt;): void;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitygetwant)<br>[getWant(): Promise&lt;Want&gt;;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitygetwant-1) | \@ohos.app.ability.UIAbility.d.ts | [launchWant: Want;](../reference/apis/js-apis-app-ability-uiAbility.md#attributes)| | [getWant(callback: AsyncCallback&lt;Want&gt;): void;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitygetwant)<br>[getWant(): Promise&lt;Want&gt;;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitygetwant-1) | \@ohos.app.ability.UIAbility.d.ts | [launchWant: Want;](../reference/apis/js-apis-app-ability-uiAbility.md#attributes)|
| [startAbility(parameter: StartAbilityParameter, callback: AsyncCallback&lt;number&gt;): void;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitystartability)<br>[startAbility(parameter: StartAbilityParameter): Promise&lt;number&gt;;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitystartability-1) | application\UIAbilityContext.d.ts | [startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartability)<br>[startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartability-1)<br>[startAbility(want: Want, options?: StartOptions): Promise&lt;void&gt;;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartability-2) | | [startAbility(parameter: StartAbilityParameter, callback: AsyncCallback&lt;number&gt;): void;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitystartability)<br>[startAbility(parameter: StartAbilityParameter): Promise&lt;number&gt;;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitystartability-1) | application\UIAbilityContext.d.ts | [startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartability)<br>[startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartability-1)<br>[startAbility(want: Want, options?: StartOptions): Promise&lt;void&gt;;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartability-2) |
| [getContext(): Context;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitygetcontext) | \@ohos.app.ability.UIAbility.d.ts | [context: UIAbilityContext;](../reference/apis/js-apis-app-ability-uiAbility.md#attributes)| | [getContext(): Context;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitygetcontext) | \@ohos.app.ability.UIAbility.d.ts | [context: UIAbilityContext;](../reference/apis/js-apis-app-ability-uiAbility.md#attributes)|
| [startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback&lt;AbilityResult&gt;): void;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitystartabilityforresult7)<br>[startAbilityForResult(parameter: StartAbilityParameter): Promise&lt;AbilityResult&gt;;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitystartabilityforresult7-1) | application\UIAbilityContext.d.ts | [startAbilityForResult(want: Want, callback: AsyncCallback&lt;AbilityResult&gt;): void;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilityforresult)<br>[startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback&lt;AbilityResult&gt;): void;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilityforresult-1)<br>[startAbilityForResult(want: Want, options?: StartOptions): Promise&lt;AbilityResult&gt;;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilityforresult-2) | | [startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback&lt;AbilityResult&gt;): void;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitystartabilityforresult7)<br>[startAbilityForResult(parameter: StartAbilityParameter): Promise&lt;AbilityResult&gt;;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitystartabilityforresult7-1) | application\UIAbilityContext.d.ts | [startAbilityForResult(want: Want, callback: AsyncCallback&lt;AbilityResult&gt;): void;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilityforresult)<br>[startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback&lt;AbilityResult&gt;): void;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilityforresult-1)<br>[startAbilityForResult(want: Want, options?: StartOptions): Promise&lt;AbilityResult&gt;;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilityforresult-2) |
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
## When to Use ## When to Use
The main task of cross-device migration is to migrate the current task (including the page control status) of an application to the target device so that the task can continue on it. Cross-device migration supports the following functionalities: The main task of cross-device migration is to migrate the current task (including the page control status) of an application to the target device so that the task can continue on it. Cross-device migration supports the following features:
- Storage and restoration of custom data - Storage and restoration of custom data
...@@ -16,7 +16,8 @@ The main task of cross-device migration is to migrate the current task (includin ...@@ -16,7 +16,8 @@ The main task of cross-device migration is to migrate the current task (includin
The following figure shows the cross-device migration process. The following figure shows the cross-device migration process.
**Figure 1** Cross-device migration process **Figure 1** Cross-device migration process
![hop-cross-device-migration](figures/hop-cross-device-migration.png) ![hop-cross-device-migration](figures/hop-cross-device-migration.png)
...@@ -49,7 +50,7 @@ The table below describes the main APIs used for cross-device migration. For det ...@@ -49,7 +50,7 @@ The table below describes the main APIs used for cross-device migration. For det
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization). 2. Display a dialog box to ask for authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization).
3. Configure the fields related to cross-device migration in the configuration file. 3. Configure the fields related to cross-device migration in the configuration file.
...@@ -79,7 +80,7 @@ The table below describes the main APIs used for cross-device migration. For det ...@@ -79,7 +80,7 @@ The table below describes the main APIs used for cross-device migration. For det
- Checking application compatibility: You can obtain the version number of the target application from **wantParam** and check the compatibility between the target application and the current application. - Checking application compatibility: You can obtain the version number of the target application from **wantParam** and check the compatibility between the target application and the current application.
- Making a migration decision: You can determine whether to support the migration based on the return value of **onContinue()**. For details about the return value, see [Available APIs](#available-apis). - Making a migration decision: You can determine whether to support the migration based on the return value of **onContinue()**. For details about the return values, see [Available APIs](#available-apis).
The sample code is as follows: The sample code is as follows:
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
## When to Use ## When to Use
Multi-device coordination involves the following scenarios: Multi-device collaboration involves the following scenarios:
- [Starting UIAbility or ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-or-serviceextensionability-across-devices-no-data-returned) - [Starting UIAbility or ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-or-serviceextensionability-across-devices-no-data-returned)
...@@ -18,13 +18,14 @@ Multi-device coordination involves the following scenarios: ...@@ -18,13 +18,14 @@ Multi-device coordination involves the following scenarios:
The figure below shows the multi-device collaboration process. The figure below shows the multi-device collaboration process.
**Figure 1** Multi-device collaboration process **Figure 1** Multi-device collaboration process
![hop-multi-device-collaboration](figures/hop-multi-device-collaboration.png) ![hop-multi-device-collaboration](figures/hop-multi-device-collaboration.png)
## Constraints ## Constraints
- Since multi-device collaboration task management is not available, you can obtain the device list by developing system applications. Access to third-party applications is not supported. - Since multi-device collaboration task management is not available, you can obtain the device list by developing system applications. Third-party applications cannot access the device list.
- Multi-device collaboration must comply with [Inter-Device Component Startup Rules](component-startup-rules.md#inter-device-component-startup-rules). - Multi-device collaboration must comply with [Inter-Device Component Startup Rules](component-startup-rules.md#inter-device-component-startup-rules).
...@@ -51,7 +52,7 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -51,7 +52,7 @@ On device A, touch the **Start** button provided by the initiator application to
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization). 2. Display a dialog box to ask for authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization).
3. Obtain the device ID of the target device. 3. Obtain the device ID of the target device.
...@@ -119,7 +120,7 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -119,7 +120,7 @@ On device A, touch the **Start** button provided by the initiator application to
## Starting UIAbility Across Devices (Data Returned) ## Starting UIAbility Across Devices (Data Returned)
On device A, touch the **Start** button provided by the initiator application to start a specified UIAbility on device B. When the UIAbility on device B exits, a value is sent back to the initiator application. On device A, touch the **Start** button provided by the initiator application to start a specified UIAbility on device B. When the UIAbility on device B exits, a value is returned to the initiator application.
### Available APIs ### Available APIs
...@@ -137,7 +138,7 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -137,7 +138,7 @@ On device A, touch the **Start** button provided by the initiator application to
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization). 2. Display a dialog box to ask for authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization).
3. Set the target component parameters on the initiator, and call **startAbilityForResult()** to start the target UIAbility. **data** in the asynchronous callback is used to receive the information returned by the target UIAbility to the initiator UIAbility after the target UIAbility terminates itself. For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility or ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-or-serviceextensionability-across-devices-no-data-returned). 3. Set the target component parameters on the initiator, and call **startAbilityForResult()** to start the target UIAbility. **data** in the asynchronous callback is used to receive the information returned by the target UIAbility to the initiator UIAbility after the target UIAbility terminates itself. For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility or ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-or-serviceextensionability-across-devices-no-data-returned).
...@@ -156,7 +157,7 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -156,7 +157,7 @@ On device A, touch the **Start** button provided by the initiator application to
}) })
``` ```
4. After the UIAbility task at the target device is complete, call **terminateSelfWithResult()** to return the data to the initiator UIAbility. 4. After the UIAbility task on the target device is complete, call **terminateSelfWithResult()** to return the data to the initiator UIAbility.
```ts ```ts
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
...@@ -214,7 +215,7 @@ A system application can connect to a service on another device by calling [conn ...@@ -214,7 +215,7 @@ A system application can connect to a service on another device by calling [conn
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization). 2. Display a dialog box to ask for authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization).
3. (Optional) [Implement a background service](serviceextensionability.md#implementing-a-background-service). Perform this operation only if no background service is available. 3. (Optional) [Implement a background service](serviceextensionability.md#implementing-a-background-service). Perform this operation only if no background service is available.
...@@ -223,7 +224,7 @@ A system application can connect to a service on another device by calling [conn ...@@ -223,7 +224,7 @@ A system application can connect to a service on another device by calling [conn
- Set the target component parameters, including the target device ID, bundle name, and ability name. - Set the target component parameters, including the target device ID, bundle name, and ability name.
- Call **connectServiceExtensionAbility** to initiate a connection. - Call **connectServiceExtensionAbility** to initiate a connection.
- Receive the service handle returned by the target device when the connection is successful. - Receive the service handle returned by the target device when the connection is successful.
- Perform cross-device invoking and obtain the result returned by the target service. - Perform cross-device call and obtain the result returned by the target service.
```ts ```ts
import rpc from '@ohos.rpc'; import rpc from '@ohos.rpc';
...@@ -311,7 +312,7 @@ The following describes how to implement multi-device collaboration through cros ...@@ -311,7 +312,7 @@ The following describes how to implement multi-device collaboration through cros
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization). 2. Display a dialog box to ask for authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization).
3. Create the CalleeAbility. 3. Create the CalleeAbility.
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
## When to Use ## When to Use
As the all-scenario, multi-device lifestyle becomes popular, users have an increasing number of devices. Each device provides users with what they need in a certain scenario. For example, watches allow users to view information in a timely manner, and smart TVs bring them an immersive watching experience. However, each device has its limitation, for example, typing text on a smart TV is frustrating as it is much more difficult than on a mobile device. If multiple devices can sense each other through a distributed OS and together form a super device, the strengths of each device can be fully exerted to provide a more natural and smoother distributed experience for users. As the all-scenario, multi-device lifestyle becomes popular, users have an increasing number of devices. Each device provides users with what they need in a certain scenario. For example, watches allow users to view information in a timely manner, and smart TVs bring them an immersive watching experience. However, each device has its limitations, for example, typing text on a smart TV is frustrating as it is much more difficult than on a mobile device. If multiple devices can sense each other through a distributed OS and together form a super device, the strengths of each device can be fully exerted to provide a more natural and smoother distributed experience for users.
In OpenHarmony, distributed operations across devices are called continuation (previously named hopping), which is further classified into [cross-device migration](hop-cross-device-migration.md) and [multi-device collaboration](hop-multi-device-collaboration.md). To implement continuation, cross-device interaction capabilities of application components are required. Currently, these capabilities are open only to system applications. In OpenHarmony, distributed operations across devices are called continuation (previously named hopping), which is further classified into [cross-device migration](hop-cross-device-migration.md) and [multi-device collaboration](hop-multi-device-collaboration.md). To implement continuation, cross-device interaction capabilities of application components are required. Currently, these capabilities are open only to system applications.
...@@ -20,7 +20,7 @@ In OpenHarmony, distributed operations across devices are called continuation (p ...@@ -20,7 +20,7 @@ In OpenHarmony, distributed operations across devices are called continuation (p
- **Multi-device collaboration** - **Multi-device collaboration**
Multi-device collaboration enables collaboration between multiple devices, providing users with more efficient and immersive experience than with a single device. A typical multi-device collaboration scenario is as follows: Application A on the tablet is used as the answer board, and application B on the smart TV is used for live broadcast, delivering a better online class experience. From the perspective of application development, multi-device collaboration enables different UIAbility or ServiceExtensionAbility components to run simultaneously or alternately on multiple devices to provide a complete service, or enables the same UIAbility and ServiceExtensionAbility component to run simultaneously on multiple devices to provide a complete service. Multi-device collaboration provides users with more efficient and immersive experience than with a single device. A typical multi-device collaboration scenario is as follows: Application A on the tablet is used as the answer board, and application B on the smart TV is used for live broadcast, delivering a better online class experience. From the perspective of application development, multi-device collaboration enables different UIAbility or ServiceExtensionAbility components to run simultaneously or alternately on multiple devices to provide a complete service, or enables the same UIAbility and ServiceExtensionAbility component to run simultaneously on multiple devices to provide a complete service.
## Continuation Architecture ## Continuation Architecture
...@@ -35,9 +35,9 @@ OpenHarmony provides a set of APIs for you to implement continuation in your app ...@@ -35,9 +35,9 @@ OpenHarmony provides a set of APIs for you to implement continuation in your app
The following figure shows the continuation architecture. The following figure shows the continuation architecture.
**Figure 1** Continuation architecture **Figure 1** Continuation architecture
![hop-structure](figures/hop-structure.png) ![hop-structure](figures/hop-structure.png)
- Cross-device migration task management: The initiator accepts a migration request from the user, provides a migration entry, and displays the migration result. (This capability is unavailable yet.) - Cross-device migration task management: The initiator accepts a migration request from the user, provides a migration entry, and displays the migration result. (This capability is unavailable yet.)
...@@ -47,4 +47,4 @@ The following figure shows the continuation architecture. ...@@ -47,4 +47,4 @@ The following figure shows the continuation architecture.
- Distributed security authentication: provides an E2E encrypted channel for cross-device transmission between applications to ensure that the right person uses the right data through the right device. - Distributed security authentication: provides an E2E encrypted channel for cross-device transmission between applications to ensure that the right person uses the right data through the right device.
- DSoftBus: functions as a unified communication base for a wide range of devices such as tablets, wearables, and smart TVs, and enables unified distributed communication between these devices. - DSoftBus: functions as a unified communication base for a wide range of devices, such as tablets, wearables, and smart TVs, and enables unified distributed communication between these devices.
...@@ -16,13 +16,13 @@ The widget host consists of the following modules: ...@@ -16,13 +16,13 @@ The widget host consists of the following modules:
- Widget usage: provides operations such as creating, deleting, or updating a widget. - Widget usage: provides operations such as creating, deleting, or updating a widget.
- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It sends widget-related operations to the Widget Manager. - Communication adapter: provided by the SDK for communication with the Widget Manager. It sends widget-related operations to the Widget Manager.
The Widget Manager consists of the following modules: The Widget Manager consists of the following modules:
- Periodic updater: starts a scheduled task based on the update policy to periodically update a widget after it is added to the Widget Manager. - Periodic updater: starts a scheduled task based on the update policy to periodically update a widget after it is added to the Widget Manager.
- Cache manager: caches view information of a widget after it is added to the Widget Manager to directly return the cached data when the widget is obtained next time. This reduces the latency greatly. - Cache manager: caches view information of a widget after it is added to the Widget Manager. This enables the cached data to be directly returned when the widget is obtained next time, greatly reducing the latency.
- Lifecycle manager: suspends update when a widget is switched to the background or is blocked, and updates and/or clears widget data during upgrade and deletion. - Lifecycle manager: suspends update when a widget is switched to the background or is blocked, and updates and/or clears widget data during upgrade and deletion.
...@@ -36,9 +36,10 @@ The widget provider consists of the following modules: ...@@ -36,9 +36,10 @@ The widget provider consists of the following modules:
- Instance manager: implemented by the widget provider developer for persistent management of widget instances allocated by the Widget Manager. - Instance manager: implemented by the widget provider developer for persistent management of widget instances allocated by the Widget Manager.
- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It pushes update data to the Widget Manager. - Communication adapter: provided by the SDK for communication with the Widget Manager. It pushes update data to the Widget Manager.
> **NOTE** > **NOTE**
>
> You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager. > You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager.
...@@ -48,14 +49,14 @@ The **FormExtensionAbility** class has the following APIs. For details, see [For ...@@ -48,14 +49,14 @@ The **FormExtensionAbility** class has the following APIs. For details, see [For
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onAddForm(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a widget has been created.| | onAddForm(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a widget is being created.|
| onCastToNormalForm(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| | onCastToNormalForm(formId: string): void | Called to notify the widget provider that a temporary widget is being converted to a normal one.|
| onUpdateForm(formId: string): void | Called to notify the widget provider that a widget has been updated.| | onUpdateForm(formId: string): void | Called to notify the widget provider that a widget is being updated.|
| onChangeFormVisibility(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility.| | onChangeFormVisibility(newStatus: { [key: string]: number }): void | Called to notify the widget provider that the widget visibility status is being changed.|
| onFormEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event.| | onFormEvent(formId: string, message: string): void | Called to instruct the widget provider to process a widget event.|
| onRemoveForm(formId: string): void | Called to notify the widget provider that a widget has been destroyed.| | onRemoveForm(formId: string): void | Called to notify the widget provider that a widget is being destroyed.|
| onConfigurationUpdate(config: Configuration): void | Called when the configuration of the environment where the widget is running is updated.| | onConfigurationUpdate(config: Configuration): void | Called when the configuration of the environment where the widget is running is being updated.|
| onShareForm?(formId: string): { [key: string]: any } | Called by the widget provider to receive shared widget data.| | onShareForm?(formId: string): { [key: string]: any } | Called to notify the widget provider that the widget host is sharing the widget data.|
The **FormProvider** class has the following APIs. For details, see [FormProvider](../reference/apis/js-apis-app-form-formProvider.md). The **FormProvider** class has the following APIs. For details, see [FormProvider](../reference/apis/js-apis-app-form-formProvider.md).
...@@ -79,11 +80,11 @@ The widget provider development based on the [stage model](stage-model-developme ...@@ -79,11 +80,11 @@ The widget provider development based on the [stage model](stage-model-developme
- [Creating a FormExtensionAbility Instance](#creating-a-formextensionability-instance): Develop the lifecycle callback functions of FormExtensionAbility. - [Creating a FormExtensionAbility Instance](#creating-a-formextensionability-instance): Develop the lifecycle callback functions of FormExtensionAbility.
- [Configuring the Widget Configuration Files](#configuring-the-widget-configuration-files): 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): This operation is a form of widget data exchange. - [Persistently Storing Widget Data](#persistently-storing-widget-data): Manage widget data persistence.
- [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 in a widget.
- [Developing the Widget UI Page](#developing-the-widget-ui-page): Use HML+CSS+JSON to develop a JS widget UI page. - [Developing the Widget UI Page](#developing-the-widget-ui-page): Use HML+CSS+JSON to develop a JS widget UI page.
...@@ -92,7 +93,7 @@ The widget provider development based on the [stage model](stage-model-developme ...@@ -92,7 +93,7 @@ The widget provider development based on the [stage model](stage-model-developme
### Creating a FormExtensionAbility Instance ### Creating a FormExtensionAbility Instance
To create a widget in the stage model, implement the lifecycle callbacks of **FormExtensionAbility**. Generate a widget template by referring to [Developing a Service Widget](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-development-service-widget-0000001263280425). To create a widget in the stage model, you need to implement the lifecycle callbacks of FormExtensionAbility. Generate a widget template and then perform the following:
1. Import related modules to **EntryFormAbility.ts**. 1. Import related modules to **EntryFormAbility.ts**.
...@@ -102,7 +103,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo ...@@ -102,7 +103,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo
import formBindingData from '@ohos.app.form.formBindingData'; import formBindingData from '@ohos.app.form.formBindingData';
import formInfo from '@ohos.app.form.formInfo'; import formInfo from '@ohos.app.form.formInfo';
import formProvider from '@ohos.app.form.formProvider'; import formProvider from '@ohos.app.form.formProvider';
import dataStorage from '@ohos.data.storage'; import dataPreferences from '@ohos.data.preferences';
``` ```
2. Implement the FormExtension lifecycle callbacks in **EntryFormAbility.ts**. 2. Implement the FormExtension lifecycle callbacks in **EntryFormAbility.ts**.
...@@ -121,7 +122,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo ...@@ -121,7 +122,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo
return formData; return formData;
} }
onCastToNormalForm(formId) { onCastToNormalForm(formId) {
// Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. // Called when a temporary widget is being converted into a normal one. The widget provider should respond to the conversion.
console.info('[EntryFormAbility] onCastToNormalForm'); console.info('[EntryFormAbility] onCastToNormalForm');
} }
onUpdateForm(formId) { onUpdateForm(formId) {
...@@ -158,6 +159,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo ...@@ -158,6 +159,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo
``` ```
> **NOTE** > **NOTE**
>
> FormExtensionAbility cannot reside in the background. Therefore, continuous tasks cannot be processed in the widget lifecycle callbacks. > FormExtensionAbility cannot reside in the background. Therefore, continuous tasks cannot be processed in the widget lifecycle callbacks.
...@@ -190,7 +192,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo ...@@ -190,7 +192,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo
} }
``` ```
2. Configure the widget configuration information. In the **metadata** configuration item of FormExtensionAbility, you can specify the resource index of specific configuration information of the widget. For example, if resource is set to **$profile:form_config**, **form_config.json** in the **resources/base/profile/** directory of the development view is used as the profile configuration file of the widget. The following table describes the internal field structure. 2. Configure the widget configuration information. In the **metadata** configuration item of FormExtensionAbility, you can specify the resource index of specific configuration information of the widget. For example, if **resource** is set to **$profile:form_config**, **form_config.json** in the **resources/base/profile/** directory of the development view is used as the profile configuration file of the widget. The following table describes the internal structure of the profile configuration file.
**Table 1** Widget profile configuration file **Table 1** Widget profile configuration file
...@@ -204,7 +206,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo ...@@ -204,7 +206,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo
| colorMode | Color mode of the widget.<br>- **auto**: auto-adaptive color mode<br>- **dark**: dark color mode<br>- **light**: light color mode| String| Yes (initial value: **auto**)| | colorMode | Color mode of the widget.<br>- **auto**: auto-adaptive color mode<br>- **dark**: dark color mode<br>- **light**: light color mode| String| Yes (initial value: **auto**)|
| supportDimensions | Grid styles supported by the widget.<br>- **1 * 2**: indicates a grid with one row and two columns.<br>- **2 * 2**: indicates a grid with two rows and two columns.<br>- **2 * 4**: indicates a grid with two rows and four columns.<br>- **4 * 4**: indicates a grid with four rows and four columns.| String array| No| | supportDimensions | Grid styles supported by the widget.<br>- **1 * 2**: indicates a grid with one row and two columns.<br>- **2 * 2**: indicates a grid with two rows and two columns.<br>- **2 * 4**: indicates a grid with two rows and four columns.<br>- **4 * 4**: indicates a grid with four rows and four columns.| String array| No|
| defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String| No| | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String| No|
| updateEnabled | Whether the widget can be updated periodically.<br>- **true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**.<br>- **false**: The widget cannot be updated periodically.| Boolean| No| | updateEnabled | Whether the widget can be updated periodically.<br>- **true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.<br>- **false**: The widget cannot be updated periodically.| Boolean| No|
| scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.<br>**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| String| Yes (initial value: **0:0**)| | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.<br>**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| String| Yes (initial value: **0:0**)|
| updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.<br>If the value is **0**, this field does not take effect.<br>If the value is a positive integer *N*, the interval is calculated by multiplying *N* and 30 minutes.<br>**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number| Yes (initial value: **0**)| | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.<br>If the value is **0**, this field does not take effect.<br>If the value is a positive integer *N*, the interval is calculated by multiplying *N* and 30 minutes.<br>**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number| Yes (initial value: **0**)|
| formConfigAbility | Link to a specific page of the application. The value is a URI.| String| Yes (initial value: left empty)| | formConfigAbility | Link to a specific page of the application. The value is a URI.| String| Yes (initial value: left empty)|
...@@ -255,7 +257,7 @@ async function storeFormInfo(formId: string, formName: string, tempFlag: boolean ...@@ -255,7 +257,7 @@ async function storeFormInfo(formId: string, formName: string, tempFlag: boolean
"updateCount": 0 "updateCount": 0
}; };
try { try {
const storage = await dataStorage.getStorage(DATA_STORAGE_PATH); const storage = await dataPreferences.getPreferences(this.context, DATA_STORAGE_PATH);
// put form info // put form info
await storage.put(formId, JSON.stringify(formInfo)); await storage.put(formId, JSON.stringify(formInfo));
console.info(`[EntryFormAbility] storeFormInfo, put form info successfully, formId: ${formId}`); console.info(`[EntryFormAbility] storeFormInfo, put form info successfully, formId: ${formId}`);
...@@ -294,8 +296,8 @@ You should override **onRemoveForm** to implement widget data deletion. ...@@ -294,8 +296,8 @@ You should override **onRemoveForm** to implement widget data deletion.
const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store"; const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store";
async function deleteFormInfo(formId: string) { async function deleteFormInfo(formId: string) {
try { try {
const storage = await dataStorage.getStorage(DATA_STORAGE_PATH); const storage = await dataPreferences.getPreferences(this.context, DATA_STORAGE_PATH);
// del form info // Delete the widget information.
await storage.delete(formId); await storage.delete(formId);
console.info(`[EntryFormAbility] deleteFormInfo, del form info successfully, formId: ${formId}`); console.info(`[EntryFormAbility] deleteFormInfo, del form info successfully, formId: ${formId}`);
await storage.flush(); await storage.flush();
...@@ -317,7 +319,7 @@ export default class EntryFormAbility extends FormExtension { ...@@ -317,7 +319,7 @@ export default class EntryFormAbility extends FormExtension {
} }
``` ```
For details about how to implement persistent data storage, see [Persisting Preferences Data](../database/data-persistence-by-preferences.md). For details about how to implement persistent data storage, see [Application Data Persistence](../database/app-data-persistence-overview.md).
The **Want** object passed in by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary. The **Want** object passed in by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary.
...@@ -449,14 +451,14 @@ The key steps are as follows: ...@@ -449,14 +451,14 @@ The key steps are as follows:
- **action**: **"router"**, which indicates a router event. - **action**: **"router"**, which indicates a router event.
- **abilityName**: name of the UIAbility to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default UIAbility name of the stage model created by DevEco Studio is EntryAbility. - **abilityName**: name of the UIAbility to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default UIAbility name of the stage model created by DevEco Studio is EntryAbility.
- **params**: custom parameters passed to the target UIAbility. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target UIAbility. For example, in the lifecycle function **onCreate** of the main ability in the stage model, you can obtain **want** and its **parameters** field. - **params**: custom parameters passed to the target UIAbility. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target UIAbility. For example, in the lifecycle function **onCreate** of the MainAbility in the stage model, you can obtain **want** and its **parameters** field.
3. Set the message event. 3. Set the message event.
- **action**: **"message"**, which indicates a message event. - **action**: **"message"**, which indicates a message event.
- **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onFormEvent()**. - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onFormEvent()**.
The following is an example: The following are examples:
- HML file: - HML file:
...@@ -545,7 +547,7 @@ The following is an example: ...@@ -545,7 +547,7 @@ The following is an example:
} }
``` ```
- Receive the router event and obtain parameters in UIAbility. - Receive the router event in UIAbility and obtain parameters.
```ts ```ts
......
# LifecycleApp Switching # LifecycleApp Switching
| API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| | API in the FA Model| Corresponding .d.ts File in the Stage Model| Corresponding API in the Stage Model|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| onShow?(): void; | \@ohos.window.d.ts | [on(eventType: 'windowStageEvent', callback: Callback&lt;WindowStageEventType&gt;): void;](../reference/apis/js-apis-window.md#onwindowstageevent9)<br>Listens for the switching to the [foreground](../reference/apis/js-apis-window.md#windowstageeventtype9).| | onShow?(): void; | \@ohos.window.d.ts | [on(eventType: 'windowStageEvent', callback: Callback&lt;WindowStageEventType&gt;): void;](../reference/apis/js-apis-window.md#onwindowstageevent9)<br>Listens for the switching to the [foreground](../reference/apis/js-apis-window.md#windowstageeventtype9).|
| onHide?(): void; | \@ohos.window.d.ts | [on(eventType: 'windowStageEvent', callback: Callback&lt;WindowStageEventType&gt;): void;](../reference/apis/js-apis-window.md#onwindowstageevent9)<br>Listens for the switching to the [background](../reference/apis/js-apis-window.md#windowstageeventtype9).| | onHide?(): void; | \@ohos.window.d.ts | [on(eventType: 'windowStageEvent', callback: Callback&lt;WindowStageEventType&gt;): void;](../reference/apis/js-apis-window.md#onwindowstageevent9)<br>Listens for the switching to the [background](../reference/apis/js-apis-window.md#windowstageeventtype9).|
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
| onRestoreData?(data: Object): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)<br>[onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)<br>In multiton or singleton mode, the target ability completes data restoration in the **onCreate()** callback. In the callback, **launchParam.launchReason** is used to determine whether it is a continuation-based launch scenario. If it is, the data saved before continuation can be obtained from the **want** parameter.| | onRestoreData?(data: Object): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)<br>[onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)<br>In multiton or singleton mode, the target ability completes data restoration in the **onCreate()** callback. In the callback, **launchParam.launchReason** is used to determine whether it is a continuation-based launch scenario. If it is, the data saved before continuation can be obtained from the **want** parameter.|
| onRemoteTerminated?(): void; | application\ContinueCallback.d.ts | [onContinueDone(result: number): void;](../reference/apis/js-apis-distributedMissionManager.md#continuecallback) | | onRemoteTerminated?(): void; | application\ContinueCallback.d.ts | [onContinueDone(result: number): void;](../reference/apis/js-apis-distributedMissionManager.md#continuecallback) |
| onSaveAbilityState?(outState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}): AbilityConstant.OnSaveResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonsavestate) | | onSaveAbilityState?(outState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}): AbilityConstant.OnSaveResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonsavestate) |
| onRestoreAbilityState?(inState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)<br>After the application is restarted, the **onCreate()** callback is triggered. In the callback, **launchParam.launchReason** is used to determine whether it is a self-recovery scenario. If it is, the data saved before the restart can be obtained from the **want** parameter.| | onRestoreAbilityState?(inState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)<br>After an application is restarted, the **onCreate()** callback is triggered. In the callback, **launchParam.launchReason** is used to determine whether it is a self-recovery scenario. If it is, the data saved before the restart can be obtained from the **want** parameter.|
| onInactive?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onBackground(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonbackground) | | onInactive?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onBackground(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonbackground) |
| onActive?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onForeground(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonforeground) | | onActive?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onForeground(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonforeground) |
| onNewWant?(want: Want): void; | \@ohos.app.ability.UIAbility.d.ts | [onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) | | onNewWant?(want: Want): void; | \@ohos.app.ability.UIAbility.d.ts | [onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) |
......
# LifecycleData Switching # LifecycleData Switching
| API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| | API in the FA Model| Corresponding .d.ts File in the Stage Model| Corresponding API in the Stage Model|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| update?(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback&lt;number&gt;): void; | \@ohos.application.DataShareExtensionAbility.d.ts | [update?(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueBucket: ValuesBucket, callback: AsyncCallback&lt;number&gt;): void;](../reference/apis/js-apis-application-dataShareExtensionAbility.md#update) | | update?(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback&lt;number&gt;): void; | \@ohos.application.DataShareExtensionAbility.d.ts | [update?(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueBucket: ValuesBucket, callback: AsyncCallback&lt;number&gt;): void;](../reference/apis/js-apis-application-dataShareExtensionAbility.md#update) |
| query?(uri: string, columns: Array&lt;string&gt;, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback&lt;ResultSet&gt;): void; | \@ohos.application.DataShareExtensionAbility.d.ts | [query?(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;Object&gt;): void;](../reference/apis/js-apis-application-dataShareExtensionAbility.md#query) | | query?(uri: string, columns: Array&lt;string&gt;, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback&lt;ResultSet&gt;): void; | \@ohos.application.DataShareExtensionAbility.d.ts | [query?(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;Object&gt;): void;](../reference/apis/js-apis-application-dataShareExtensionAbility.md#query) |
......
# LifecycleForm Switching # LifecycleForm Switching
| API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| | API in the FA Model| Corresponding .d.ts File in the Stage Model| Corresponding API in the Stage Model|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| onCreate?(want: Want): formBindingData.FormBindingData; | \@ohos.app.form.FormExtensionAbility.d.ts | [onAddForm(want: Want): formBindingData.FormBindingData;](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) | | onCreate?(want: Want): formBindingData.FormBindingData; | \@ohos.app.form.FormExtensionAbility.d.ts | [onAddForm(want: Want): formBindingData.FormBindingData;](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) |
| onCastToNormal?(formId: string): void; | \@ohos.app.form.FormExtensionAbility.d.ts | [onCastToNormalForm(formId: string): void;](../reference/apis/js-apis-app-form-formExtensionAbility.md#oncasttonormalform) | | onCastToNormal?(formId: string): void; | \@ohos.app.form.FormExtensionAbility.d.ts | [onCastToNormalForm(formId: string): void;](../reference/apis/js-apis-app-form-formExtensionAbility.md#oncasttonormalform) |
......
# LifecycleService Switching # LifecycleService Switching
| API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| | API in the FA Model| Corresponding .d.ts File in the Stage Model| Corresponding API in the Stage Model|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| onStart?(): void; | \@ohos.app.ability.ServiceExtensionAbility.d.ts | [onCreate(want: Want): void;](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityoncreate) | | onStart?(): void; | \@ohos.app.ability.ServiceExtensionAbility.d.ts | [onCreate(want: Want): void;](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityoncreate) |
| onCommand?(want: Want, startId: number): void; | \@ohos.app.ability.ServiceExtensionAbility.d.ts | [onRequest(want: Want, startId: number): void;](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonrequest) | | | onCommand?(want: Want, startId: number): void; | \@ohos.app.ability.ServiceExtensionAbility.d.ts | [onRequest(want: Want, startId: number): void;](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonrequest) | |
......
# mediaLibrary Switching # mediaLibrary Switching
| API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| | API in the FA Model| Corresponding .d.ts File in the Stage Model| Corresponding API in the Stage Model|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| [getMediaLibrary(): MediaLibrary;](../reference/apis/js-apis-medialibrary.md#medialibrarygetmedialibrary) | \@ohos.multimedia.mediaLibrary.d.ts | [getMediaLibrary(context: Context): MediaLibrary;](../reference/apis/js-apis-medialibrary.md#medialibrarygetmedialibrary8) | | [getMediaLibrary(): MediaLibrary;](../reference/apis/js-apis-medialibrary.md#medialibrarygetmedialibrary) | \@ohos.multimedia.mediaLibrary.d.ts | [getMediaLibrary(context: Context): MediaLibrary;](../reference/apis/js-apis-medialibrary.md#medialibrarygetmedialibrary8) |
...@@ -17,11 +17,13 @@ This document describes the following operations: ...@@ -17,11 +17,13 @@ This document describes the following operations:
## Setting a Mission Snapshot Icon (for System Applications Only) ## Setting a Mission Snapshot Icon (for System Applications Only)
Call [UIAbilityContext.setMissionIcon()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionicon) to set the icon of a mission snapshot. The icon is an object of the [PixelMap](../reference/apis/js-apis-image.md#pixelmap7) type. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). Call [UIAbilityContext.setMissionIcon()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionicon) to set the icon of a mission snapshot. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). For details about how to obtain the PixelMap information in the example, see [Image Decoding](../media/image-decoding.md).
```ts ```ts
let imagePixelMap: PixelMap = undefined; // Obtain the PixelMap information. let context = ...; // UIAbilityContext
let pixelMap: PixelMap =...; // PixelMap information of the image.
context.setMissionIcon(imagePixelMap, (err) => { context.setMissionIcon(pixelMap, (err) => {
if (err.code) { if (err.code) {
console.error(`Failed to set mission icon. Code is ${err.code}, message is ${err.message}`); console.error(`Failed to set mission icon. Code is ${err.code}, message is ${err.message}`);
} }
...@@ -31,7 +33,6 @@ context.setMissionIcon(imagePixelMap, (err) => { ...@@ -31,7 +33,6 @@ context.setMissionIcon(imagePixelMap, (err) => {
The display effect is shown below. The display effect is shown below.
Figure 2 Mission snapshot icon Figure 2 Mission snapshot icon
![](figures/mission-set-task-snapshot-icon.png) ![](figures/mission-set-task-snapshot-icon.png)
## Setting a Mission Snapshot Name ## Setting a Mission Snapshot Name
...@@ -39,7 +40,9 @@ Figure 2 Mission snapshot icon ...@@ -39,7 +40,9 @@ Figure 2 Mission snapshot icon
Call [UIAbilityContext.setMissionLabel()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionlabel) to set the name of a mission snapshot. Call [UIAbilityContext.setMissionLabel()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionlabel) to set the name of a mission snapshot.
```ts ```ts
this.context.setMissionLabel('test').then(() => { let context = ...; // UIAbilityContext
context.setMissionLabel('test').then(() => {
console.info('Succeeded in seting mission label.'); console.info('Succeeded in seting mission label.');
}).catch((err) => { }).catch((err) => {
console.error(`Failed to set mission label. Code is ${err.code}, message is ${err.message}`); console.error(`Failed to set mission label. Code is ${err.code}, message is ${err.message}`);
...@@ -49,5 +52,4 @@ this.context.setMissionLabel('test').then(() => { ...@@ -49,5 +52,4 @@ this.context.setMissionLabel('test').then(() => {
The display effect is shown below. The display effect is shown below.
Figure 3 Mission snapshot name Figure 3 Mission snapshot name
![](figures/mission-set-task-snapshot-label.png) ![](figures/mission-set-task-snapshot-label.png)
...@@ -5,19 +5,23 @@ Perform the following operations to switch a declarative paradigm-based applicat ...@@ -5,19 +5,23 @@ Perform the following operations to switch a declarative paradigm-based applicat
- Project switch: Create an application project of the stage model. - Project switch: Create an application project of the stage model.
![model-switch-overview1](figures/model-switch-overview1.png) ![model-switch-overview1](figures/model-switch-overview1.png)
- [Configuration file switch](configuration-file-diff.md): Switch **config.json** to **app.json5** and **module.json5**. - [Configuration file switch](configuration-file-diff.md): Switch **config.json** to **app.json5** and **module.json5**.
![model-switch-overview2](figures/model-switch-overview2.png) ![model-switch-overview2](figures/model-switch-overview2.png)
- [Component switch](pageability-switch.md): Switch the PageAbility, ServiceAbility, and DataAbility components of the FA model to the UIAbility and ExtensionAbility components of the stage model. The figure below shows only the switching from PageAbility to UIAbility. The left part is the FA model, and **app.ets** is the PageAbility component. The right part is the stage model, and **EntryAbility.ts** is the UIAbility component. - [Component switch](pageability-switch.md): Switch the PageAbility, ServiceAbility, and DataAbility components of the FA model to the UIAbility and ExtensionAbility components of the stage model. The figure below shows only the switching from PageAbility to UIAbility. The left part is the FA model, and **app.ets** is the PageAbility component. The right part is the stage model, and **EntryAbility.ts** is the UIAbility component.
![model-switch-overview3](figures/model-switch-overview3.png) ![model-switch-overview3](figures/model-switch-overview3.png)
- [Widget switch](widget-switch.md): Switch the FormAbility component of the FA model to the FormExtensionAbility component of the stage model. In the figure below, **Service Widget** is FormAbility in the FA model and FormExtensionAbility in the stage model. - [Widget switch](widget-switch.md): Switch the FormAbility component of the FA model to the FormExtensionAbility component of the stage model. In the figure below, **Service Widget** is FormAbility in the FA model and FormExtensionAbility in the stage model.
![model-switch-overview4](figures/model-switch-overview4.png) ![model-switch-overview4](figures/model-switch-overview4.png)
![model-switch-overview5](figures/model-switch-overview5.png) ![model-switch-overview5](figures/model-switch-overview5.png)
- [API switch](api-switch-overview.md): Switch the APIs with the **FAModelOnly** tag used in the FA model to the recommended APIs in the stage model. - [API switch](api-switch-overview.md): Switch the APIs with the **FAModelOnly** tag used in the FA model to the recommended APIs in the stage model.
![model-switch-overview6](figures/model-switch-overview6.png) ![model-switch-overview6](figures/model-switch-overview6.png)
# Switching of module # Switching of module
When switching an application from the FA model to the stage model, you must migrate the configurations under the **module** tag in the **config.json** file to the **module** tag in the **module.json5** file. When switching an application from the FA model to the stage model, migrate the configurations under **module** in the **config.json** file to **module** in the **module.json5** file.
**Table 1** module comparison **Table 1** module comparison
...@@ -60,7 +60,7 @@ When switching an application from the FA model to the stage model, you must mig ...@@ -60,7 +60,7 @@ When switching an application from the FA model to the stage model, you must mig
| deviceCapability | Device capabilities required to run the ability.| / | This configuration is not supported in the stage model.| | deviceCapability | Device capabilities required to run the ability.| / | This configuration is not supported in the stage model.|
| metaData | Metadata of the ability.| metadata | For details, see Table 2.| | metaData | Metadata of the ability.| metadata | For details, see Table 2.|
| type | Ability type.| / | This configuration is not supported in the stage model.| | type | Ability type.| / | This configuration is not supported in the stage model.|
| grantPermission | Whether permissions can be granted for any data in the ability.| / | The stage model does not support such a configuration under **abilities**.| | grantPermission | Whether permissions can be granted to any data in the ability.| / | The stage model does not support such a configuration under **abilities**.|
| readPermission | Permission required for reading data in the ability. This field applies only to the ability using the Data template.| / | In the stage model, this configuration is available under **extensionAbilities**, but not **abilities**.| | readPermission | Permission required for reading data in the ability. This field applies only to the ability using the Data template.| / | In the stage model, this configuration is available under **extensionAbilities**, but not **abilities**.|
| writePermission | Permission required for writing data to the ability.| / | In the stage model, this configuration is available under **extensionAbilities**, but not **abilities**.| | writePermission | Permission required for writing data to the ability.| / | In the stage model, this configuration is available under **extensionAbilities**, but not **abilities**.|
| configChanges | System configurations that the ability concerns.| / | This configuration is not supported in the stage model.| | configChanges | System configurations that the ability concerns.| / | This configuration is not supported in the stage model.|
......
...@@ -27,7 +27,7 @@ The PageAbility lifecycle is basically the same as the UIAbility lifecycle. The ...@@ -27,7 +27,7 @@ The PageAbility lifecycle is basically the same as the UIAbility lifecycle. The
3. Adjust the migrated code, since the methods of loading pages are different. 3. Adjust the migrated code, since the methods of loading pages are different.
- In the FA model, you can configure the page to be loaded by setting page information in **config.json**. - In the FA model, you can configure the page to be loaded by setting page information in **config.json**.
- In the stage model, you must call **windowStage.loadContent** in the **onWindowStageCreate** callback to load a page. - In the stage model, call **windowStage.loadContent** in the **onWindowStageCreate** callback to load a page.
For example, to load the **pages/Index** page after the ability is started, use the following code in the **config.json** file in the FA model: For example, to load the **pages/Index** page after the ability is started, use the following code in the **config.json** file in the FA model:
......
# particleAbility Switching # particleAbility Switching
| API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| | API in the FA Model| Corresponding .d.ts File in the Stage Model| Corresponding API in the Stage Model|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| [startAbility(parameter: StartAbilityParameter, callback: AsyncCallback&lt;number&gt;): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartability)<br>[startAbility(parameter: StartAbilityParameter): Promise&lt;number&gt;;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartability-1) | application\ServiceExtensionContext.d.ts | [startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartability)<br>[startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartability-2)<br>[startAbility(want: Want, options?: StartOptions): Promise&lt;void&gt;;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartability-1)<br>[startServiceExtensionAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartserviceextensionability)<br>[startServiceExtensionAbility(want: Want): Promise&lt;void&gt;;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartserviceextensionability-1) | | [startAbility(parameter: StartAbilityParameter, callback: AsyncCallback&lt;number&gt;): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartability)<br>[startAbility(parameter: StartAbilityParameter): Promise&lt;number&gt;;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartability-1) | application\ServiceExtensionContext.d.ts | [startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartability)<br>[startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartability-2)<br>[startAbility(want: Want, options?: StartOptions): Promise&lt;void&gt;;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartability-1)<br>[startServiceExtensionAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartserviceextensionability)<br>[startServiceExtensionAbility(want: Want): Promise&lt;void&gt;;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartserviceextensionability-1) |
| [terminateSelf(callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilityterminateself)<br>[terminateSelf(): Promise&lt;void&gt;;](../reference/apis/js-apis-ability-particleAbility.md#particleabilityterminateself-1) | application\ServiceExtensionContext.d.ts | [terminateSelf(callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself)<br>[terminateSelf(): Promise&lt;void&gt;;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself-1) | | [terminateSelf(callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilityterminateself)<br>[terminateSelf(): Promise&lt;void&gt;;](../reference/apis/js-apis-ability-particleAbility.md#particleabilityterminateself-1) | application\ServiceExtensionContext.d.ts | [terminateSelf(callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself)<br>[terminateSelf(): Promise&lt;void&gt;;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself-1) |
...@@ -10,3 +10,5 @@ ...@@ -10,3 +10,5 @@
| [acquireDataAbilityHelper(uri: string): DataAbilityHelper;](../reference/apis/js-apis-ability-particleAbility.md#particleabilityacquiredataabilityhelper) | \@ohos.data.dataShare.d.ts<br>[\@ohos.data.fileAccess.d.ts | [createDataShareHelper(context: Context, uri: string, callback: AsyncCallback&lt;DataShareHelper&gt;): void;](../reference/apis/js-apis-data-dataShare.md#datasharecreatedatasharehelper)<br>[createDataShareHelper(context: Context, uri: string): Promise&lt;DataShareHelper&gt;;](../reference/apis/js-apis-data-dataShare.md#datasharecreatedatasharehelper-1)<br>[createFileAccessHelper(context: Context): FileAccessHelper;](../reference/apis/js-apis-fileAccess.md#fileaccesscreatefileaccesshelper-1)<br>[createFileAccessHelper(context: Context, wants: Array&lt;Want&gt;): FileAccessHelper;](../reference/apis/js-apis-fileAccess.md#fileaccesscreatefileaccesshelper) | | [acquireDataAbilityHelper(uri: string): DataAbilityHelper;](../reference/apis/js-apis-ability-particleAbility.md#particleabilityacquiredataabilityhelper) | \@ohos.data.dataShare.d.ts<br>[\@ohos.data.fileAccess.d.ts | [createDataShareHelper(context: Context, uri: string, callback: AsyncCallback&lt;DataShareHelper&gt;): void;](../reference/apis/js-apis-data-dataShare.md#datasharecreatedatasharehelper)<br>[createDataShareHelper(context: Context, uri: string): Promise&lt;DataShareHelper&gt;;](../reference/apis/js-apis-data-dataShare.md#datasharecreatedatasharehelper-1)<br>[createFileAccessHelper(context: Context): FileAccessHelper;](../reference/apis/js-apis-fileAccess.md#fileaccesscreatefileaccesshelper-1)<br>[createFileAccessHelper(context: Context, wants: Array&lt;Want&gt;): FileAccessHelper;](../reference/apis/js-apis-fileAccess.md#fileaccesscreatefileaccesshelper) |
| [startBackgroundRunning(id: number, request: NotificationRequest, callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartbackgroundrunning)<br>[startBackgroundRunning(id: number, request: NotificationRequest): Promise&lt;void&gt;;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartbackgroundrunning-1) | \@ohos.resourceschedule.backgroundTaskManager.d.ts | [startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback): void;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunningcallback)<br>[startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise&lt;void&gt;;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunningpromise) | | [startBackgroundRunning(id: number, request: NotificationRequest, callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartbackgroundrunning)<br>[startBackgroundRunning(id: number, request: NotificationRequest): Promise&lt;void&gt;;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartbackgroundrunning-1) | \@ohos.resourceschedule.backgroundTaskManager.d.ts | [startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback): void;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunningcallback)<br>[startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise&lt;void&gt;;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunningpromise) |
| [cancelBackgroundRunning(callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitycancelbackgroundrunning)<br>[cancelBackgroundRunning(): Promise&lt;void&gt;;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitycancelbackgroundrunning-1) | \@ohos.resourceschedule.backgroundTaskManager.d.ts | [stopBackgroundRunning(context: Context, callback: AsyncCallback): void;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunningcallback)<br>[stopBackgroundRunning(context: Context): Promise&lt;void&gt;;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunningpromise) | | [cancelBackgroundRunning(callback: AsyncCallback&lt;void&gt;): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitycancelbackgroundrunning)<br>[cancelBackgroundRunning(): Promise&lt;void&gt;;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitycancelbackgroundrunning-1) | \@ohos.resourceschedule.backgroundTaskManager.d.ts | [stopBackgroundRunning(context: Context, callback: AsyncCallback): void;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunningcallback)<br>[stopBackgroundRunning(context: Context): Promise&lt;void&gt;;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunningpromise) |
<!--no_check-->
\ No newline at end of file
...@@ -8,9 +8,9 @@ The OpenHarmony process model is shown below. ...@@ -8,9 +8,9 @@ The OpenHarmony process model is shown below.
- WebView has an independent rendering process, which is **Render process** in yellow in the figure. - WebView has an independent rendering process, which is **Render process** in yellow in the figure.
**Figure 1** Process model **Figure 1** Process model
![process-model-fa](figures/process-model-fa.png) ![process-model-fa](figures/process-model-fa.png)
OpenHarmony provides two inter-process communication (IPC) mechanisms. OpenHarmony provides two inter-process communication (IPC) mechanisms.
...@@ -19,4 +19,3 @@ OpenHarmony provides two inter-process communication (IPC) mechanisms. ...@@ -19,4 +19,3 @@ OpenHarmony provides two inter-process communication (IPC) mechanisms.
- [Common Events](common-event-fa.md): This mechanism is used in one-to-many communication scenarios. Multiple subscribers may receive events at the same time. - [Common Events](common-event-fa.md): This mechanism is used in one-to-many communication scenarios. Multiple subscribers may receive events at the same time.
- [Background Services](rpc.md): This mechanism is implemented through [ServiceAbility](serviceability-overview.md). - [Background Services](rpc.md): This mechanism is implemented through [ServiceAbility](serviceability-overview.md).
...@@ -5,12 +5,11 @@ The OpenHarmony process model is shown below. ...@@ -5,12 +5,11 @@ The OpenHarmony process model is shown below.
- All UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components of an application (with the same bundle name) run in an independent process, which is **Main process** in green in the figure. - All UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components of an application (with the same bundle name) run in an independent process, which is **Main process** in green in the figure.
- All ExtensionAbility components of the same type (except ServiceExtensionAbility and DataShareExtensionAbility) of an application (with the same bundle name) run in an independent process, which is **FormExtensionAbility process**, **InputMethodExtensionAbility process**, and other **ExtensionAbility process** in blue in the figure.
- The ExtensionAbility components of the same type (except ServiceExtensionAbility and DataShareExtensionAbility) of an application (with the same bundle name) run in an independent process, which is **FormExtensionAbility process**, **InputMethodExtensionAbility process**, and other **ExtensionAbility process** in blue in the figure.
- WebView has an independent rendering process, which is **Render process** in yellow in the figure. - WebView has an independent rendering process, which is **Render process** in yellow in the figure.
**Figure 1** Process model **Figure 1** Process model
![process-model](figures/process-model.png) ![process-model](figures/process-model.png)
> NOTE > NOTE
...@@ -20,7 +19,8 @@ The OpenHarmony process model is shown below. ...@@ -20,7 +19,8 @@ The OpenHarmony process model is shown below.
A system application can apply for multi-process permissions (as shown in the following figure) and configure a custom process for an HAP. UIAbility, DataShareExtensionAbility, and ServiceExtensionAbility in the HAP run in the custom process. Different HAPs run in different processes by configuring different process names. A system application can apply for multi-process permissions (as shown in the following figure) and configure a custom process for an HAP. UIAbility, DataShareExtensionAbility, and ServiceExtensionAbility in the HAP run in the custom process. Different HAPs run in different processes by configuring different process names.
**Figure 2** Multi-process **Figure 2** Multi-process
![multi-process](figures/multi-process.png) ![multi-process](figures/multi-process.png)
......
# request Switching # request Switching
| API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| | API in the FA Model| Corresponding .d.ts File in the Stage Model| Corresponding API in the Stage Model|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| [download(config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): void;](../reference/apis//js-apis-request.md#requestdownload-1)<br>[download(config: DownloadConfig): Promise&lt;DownloadTask&gt;;](../reference/apis/js-apis-request.md#requestdownload) | \@ohos.request.d.ts | [downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): void;](../reference/apis/js-apis-request.md#requestdownloadfile9-1)<br>[downloadFile(context: BaseContext, config: DownloadConfig): Promise&lt;DownloadTask&gt;;](../reference/apis/js-apis-request.md#requestdownloadfile9) | | [download(config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): void;](../reference/apis//js-apis-request.md#requestdownload-1)<br>[download(config: DownloadConfig): Promise&lt;DownloadTask&gt;;](../reference/apis/js-apis-request.md#requestdownload) | \@ohos.request.d.ts | [downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): void;](../reference/apis/js-apis-request.md#requestdownloadfile9-1)<br>[downloadFile(context: BaseContext, config: DownloadConfig): Promise&lt;DownloadTask&gt;;](../reference/apis/js-apis-request.md#requestdownloadfile9) |
| [upload(config: UploadConfig, callback: AsyncCallback&lt;UploadTask&gt;): void;](../reference/apis/js-apis-request.md#requestupload-1)<br>[upload(config: UploadConfig): Promise&lt;UploadTask&gt;;](../reference/apis/js-apis-request.md#requestupload) | \@ohos.request.d.ts | [uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback&lt;UploadTask&gt;): void;](../reference/apis/js-apis-request.md#requestuploadfile9-1)<br>[uploadFile(context: BaseContext, config: UploadConfig): Promise&lt;UploadTask&gt;;](../reference/apis/js-apis-request.md#requestuploadfile9) | | [upload(config: UploadConfig, callback: AsyncCallback&lt;UploadTask&gt;): void;](../reference/apis/js-apis-request.md#requestupload-1)<br>[upload(config: UploadConfig): Promise&lt;UploadTask&gt;;](../reference/apis/js-apis-request.md#requestupload) | \@ohos.request.d.ts | [uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback&lt;UploadTask&gt;): void;](../reference/apis/js-apis-request.md#requestuploadfile9-1)<br>[uploadFile(context: BaseContext, config: UploadConfig): Promise&lt;UploadTask&gt;;](../reference/apis/js-apis-request.md#requestuploadfile9) |
# resourceManager Switching # resourceManager Switching
| API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding Field in the Stage Model| | API in the FA Model| Corresponding .d.ts File in the Stage Model| Corresponding Field in the Stage Model|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| [getResourceManager(callback: AsyncCallback&lt;ResourceManager&gt;): void;](../reference/apis/js-apis-resource-manager.md#resourcemanagergetresourcemanager)<br>[getResourceManager(bundleName: string, callback: AsyncCallback&lt;ResourceManager&gt;): void;](../reference/apis/js-apis-resource-manager.md#resourcemanagergetresourcemanager-1)<br>[getResourceManager(): Promise&lt;ResourceManager&gt;;](../reference/apis/js-apis-resource-manager.md#resourcemanagergetresourcemanager-2)<br>[getResourceManager(bundleName: string): Promise&lt;ResourceManager&gt;;](../reference/apis/js-apis-resource-manager.md#resourcemanagergetresourcemanager-3) | application\Context.d.ts | [resourceManager: resmgr.ResourceManager;](../reference/apis/js-apis-inner-application-context.md#attributes)| | [getResourceManager(callback: AsyncCallback&lt;ResourceManager&gt;): void;](../reference/apis/js-apis-resource-manager.md#resourcemanagergetresourcemanager)<br>[getResourceManager(bundleName: string, callback: AsyncCallback&lt;ResourceManager&gt;): void;](../reference/apis/js-apis-resource-manager.md#resourcemanagergetresourcemanager-1)<br>[getResourceManager(): Promise&lt;ResourceManager&gt;;](../reference/apis/js-apis-resource-manager.md#resourcemanagergetresourcemanager-2)<br>[getResourceManager(bundleName: string): Promise&lt;ResourceManager&gt;;](../reference/apis/js-apis-resource-manager.md#resourcemanagergetresourcemanager-3) | application\Context.d.ts | [resourceManager: resmgr.ResourceManager;](../reference/apis/js-apis-inner-application-context.md#attributes)|
...@@ -4,9 +4,9 @@ ...@@ -4,9 +4,9 @@
The ServiceAbility component in the FA model corresponds to the ServiceExtensionAbility component in the stage model. The ServiceExtensionAbility class provides system APIs. Only system applications can create ServiceExtensionAbility instances. Therefore, ServiceAbility switching adopts different policies for system applications and third-party applications. The ServiceAbility component in the FA model corresponds to the ServiceExtensionAbility component in the stage model. The ServiceExtensionAbility class provides system APIs. Only system applications can create ServiceExtensionAbility instances. Therefore, ServiceAbility switching adopts different policies for system applications and third-party applications.
## Switching a ServiceAbility of a System Application ## Switching a ServiceAbility for a System Application
The procedure for switching a ServiceAbility of a system application is similar to the procedure of PageAbility switching. The procedure for switching a ServiceAbility for a system application is similar to the procedure of PageAbility switching.
1. [Create a ServiceExtensionAbility](serviceextensionability.md) in the stage model. 1. [Create a ServiceExtensionAbility](serviceextensionability.md) in the stage model.
...@@ -24,7 +24,7 @@ The table below describes the lifecycle comparison of the ServiceAbility and Ser ...@@ -24,7 +24,7 @@ The table below describes the lifecycle comparison of the ServiceAbility and Ser
| onStop(): void | onDestroy(): void | The two methods have the same meaning, invoking time, and parameters.| | onStop(): void | onDestroy(): void | The two methods have the same meaning, invoking time, and parameters.|
## Switching a ServiceAbility of a Third-Party Application ## Switching a ServiceAbility for a Third-Party Application
In the stage model, third-party applications cannot provide services for other third-party applications. You can select a switching solution based on your service requirements. In the stage model, third-party applications cannot provide services for other third-party applications. You can select a switching solution based on your service requirements.
......
# Storage Switching # Storage Switching
| API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| | API in the FA Model| Corresponding .d.ts File in the Stage Model| Corresponding API in the Stage Model|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| GetStorageOptions | There is no corresponding API in the stage model.| The stage model uses **Prefereces** to replace **Storage** and has redesigned the input parameters.| | GetStorageOptions | There is no corresponding API in the stage model.| The stage model uses **Prefereces** to replace **Storage** and has redesigned the input parameters.|
| SetStorageOptions | There is no corresponding API in the stage model.| The stage model uses **Prefereces** to replace **Storage** and has redesigned the input parameters.| | SetStorageOptions | There is no corresponding API in the stage model.| The stage model uses **Prefereces** to replace **Storage** and has redesigned the input parameters.|
......
# Subscribing to System Environment Variable Changes # Subscribing to System Environment Variable Changes
System environment variables are system settings (for example, the system language or screen direction) of a device that may change during the running of an application. System environment variables are system settings (for example, the system language or screen orientation) of a device that may change during the running of an application.
By subscribing to the changes of system environment variables, the application can detect the changes in a timely manner and process the changes accordingly, providing better user experience. For example, when the system language changes, the application can display the UI in the new language; when the user rotates the device to landscape or portrait mode, the application can re-arrange the UI to adapt to the new screen orientation and size. By subscribing to the changes of system environment variables, the application can detect the changes in a timely manner and process the changes accordingly, providing better user experience. For example, when the system language changes, the application can display the UI in the new language; when the user rotates the device to landscape or portrait mode, the application can re-arrange the UI to adapt to the new screen orientation and size.
......
# Thread Model Overview (FA Model) # Thread Model Overview (FA Model)
There are three types of threads in the FA model: There are three types of threads in the FA model:
- Main thread - Main thread
Manages other threads. Manages other threads.
...@@ -14,8 +16,8 @@ There are three types of threads in the FA model: ...@@ -14,8 +16,8 @@ There are three types of threads in the FA model:
- Receives messages sent by the worker thread. - Receives messages sent by the worker thread.
- Worker thread - Worker thread
Performs time-consuming operations Performs time-consuming operations.
Based on the OpenHarmony thread model, different services run on different threads. Service interaction requires inter-thread communication. Threads can communicate with each other in Emitter or Worker mode. Emitter is mainly used for event synchronization between threads, and Worker is mainly used to execute time-consuming tasks. Based on the OpenHarmony thread model, different services run on different threads. Service interaction requires inter-thread communication. Threads can communicate with each other in Emitter or Worker mode. Emitter is mainly used for event synchronization between threads, and Worker is mainly used to execute time-consuming tasks.
......
...@@ -4,19 +4,18 @@ For an OpenHarmony application, each process has a main thread to provide the fo ...@@ -4,19 +4,18 @@ For an OpenHarmony application, each process has a main thread to provide the fo
- Draw the UI. - Draw the UI.
- Manage the ArkTS engine instance of the main thread so that multiple UIAbility components can run on it. - Manage the ArkTS engine instance of the main thread so that multiple UIAbility components can run on it.
- Manage ArkTS engine instances of other threads (such as the worker thread), for example, starting and terminating other threads. - Manage ArkTS engine instances of other threads, for example, starting and terminating other threads.
- Distribute interaction events. - Distribute interaction events.
- Process application code callbacks (event processing and lifecycle management). - Process application code callbacks (event processing and lifecycle management).
- Receive messages sent by the worker thread. - Receive messages sent by the worker thread.
In addition to the main thread, there is an independent thread, named worker. The worker thread is mainly used to perform time-consuming operations. The worker thread is created in the main thread and is independent from the main thread. It cannot directly operate the UI. A maximum of seven worker threads can be created. In addition to the main thread, there is an independent thread, named worker. The worker thread is mainly used to perform time-consuming operations. The worker thread is created in the main thread and is independent from the main thread. It cannot directly operate the UI. A maximum of seven worker threads can be created.
![thread-model-stage](figures/thread-model-stage.png) ![thread-model-stage](figures/thread-model-stage.png)
Based on the OpenHarmony thread model, different services run on different threads. Service interaction requires inter-thread communication. In the same process, threads can communicate with each other in Emitter or Worker mode. Emitter is mainly used for event synchronization between threads, and Worker is mainly used to execute time-consuming tasks. Based on the OpenHarmony thread model, different services run on different threads. Service interaction requires inter-thread communication. In the same process, threads can communicate with each other in Emitter or Worker mode. Emitter is mainly used for event synchronization between threads, and Worker is mainly used to execute time-consuming tasks.
> **NOTE** > **NOTE**
> >
> - The stage model provides only the main thread and worker thread. Emitter is mainly used for event synchronization within the worker thread or between the main thread and worker thread. > - The stage model provides only the main thread and worker thread. Emitter is mainly used for event synchronization within the worker thread or between the main thread and worker thread.
> - The UIAbility and UI are in the main thread. For details about data synchronization between them, see [Data Synchronization Between UIAbility and UI](uiability-data-sync-with-ui.md). > - The UIAbility and UI are in the main thread. For details about data synchronization between them, see [Data Synchronization Between UIAbility and UI](uiability-data-sync-with-ui.md).
> - To view thread information about an application process, run the **hdc shell** command to enter the shell CLI of the device, and then run the **ps -p *<pid>* -T command**, where *<pid>* indicates the [process ID](process-model-stage.md) of the application. > - To view thread information about an application process, run the **hdc shell** command to enter the shell CLI of the device, and then run the **ps -p *<pid>* -T command**, where *<pid>* indicates the [process ID](process-model-stage.md) of the application.
# Data Synchronization Between UIAbility and UI # Data Synchronization Between UIAbility and UI Page
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 UIAbility components and UI pages:
- [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 EventHub for Data Synchronization](#using-eventhub-for-data-synchronization): The **EventHub** object is provided by the base class **Context**. It allows events to be 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. - [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 UI page.
- [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. - [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.
...@@ -12,7 +12,7 @@ Based on the OpenHarmony application model, you can use any of the following way ...@@ -12,7 +12,7 @@ Based on the OpenHarmony application model, you can use any of the following way
[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. [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 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. 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).
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**.
...@@ -40,7 +40,7 @@ Before using the APIs provided by **EventHub**, you must obtain an **EventHub** ...@@ -40,7 +40,7 @@ Before using the APIs provided by **EventHub**, you must obtain an **EventHub**
} }
``` ```
2. Call [eventHub.emit()](../reference/apis/js-apis-inner-application-eventHub.md#eventhubemit) on the UI to trigger the event, and pass the parameters as required. 2. Call [eventHub.emit()](../reference/apis/js-apis-inner-application-eventHub.md#eventhubemit) on the UI page to trigger the event, and pass in the parameters as required.
```ts ```ts
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
...@@ -60,14 +60,14 @@ Before using the APIs provided by **EventHub**, you must obtain an **EventHub** ...@@ -60,14 +60,14 @@ Before using the APIs provided by **EventHub**, you must obtain an **EventHub**
// You can design the parameters based on your service requirements. // You can design the parameters based on your service requirements.
} }
// Page display. // UI page display.
build() { build() {
... ...
} }
} }
``` ```
3. Obtain the event trigger result from the subscription callback of UIAbility. The run log result is as follows: 3. Obtain the event trigger result from the subscription callback of the UIAbility. The run log result is as follows:
```ts ```ts
[] []
...@@ -77,7 +77,7 @@ Before using the APIs provided by **EventHub**, you must obtain an **EventHub** ...@@ -77,7 +77,7 @@ Before using the APIs provided by **EventHub**, you must obtain an **EventHub**
[2,'test'] [2,'test']
``` ```
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. When **event1** is not needed, call [eventHub.off()](../reference/apis/js-apis-inner-application-eventHub.md#eventhuboff) to unsubscribe from the event.
```ts ```ts
// context is the AbilityContext of the UIAbility instance. // context is the AbilityContext of the UIAbility instance.
...@@ -87,7 +87,7 @@ Before using the APIs provided by **EventHub**, you must obtain an **EventHub** ...@@ -87,7 +87,7 @@ Before using the APIs provided by **EventHub**, you must obtain an **EventHub**
## 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 UI 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)
...@@ -95,16 +95,16 @@ Before using the APIs provided by **EventHub**, you must obtain an **EventHub** ...@@ -95,16 +95,16 @@ Before using the APIs provided by **EventHub**, you must obtain an **EventHub**
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 UI Page](#using-globalthis-between-uiability-and-ui-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) - [Using 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 UI Page
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. To implement data synchronization between the UIAbility component and UI page, you can bind attributes or methods to **globalThis**. For example, if you bind the **want** parameter in the UIAbility component, you can use the **want** parameter information on the UI page corresponding to the UIAbility component.
1. When [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called to start a UIAbility instance, the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) 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()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) callback is invoked, and the **want** parameter can be passed in the callback. Bind the **want** parameter to **globalThis**.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
...@@ -119,7 +119,7 @@ By binding attributes or methods to **globalThis**, you can implement data synch ...@@ -119,7 +119,7 @@ By binding attributes or methods to **globalThis**, you can implement data synch
} }
``` ```
2. Use **globalThis** on the UI to obtain the **want** parameter information. 2. Use **globalThis** on the UI page to obtain the **want** parameter information.
```ts ```ts
let entryAbilityWant; let entryAbilityWant;
...@@ -131,7 +131,7 @@ By binding attributes or methods to **globalThis**, you can implement data synch ...@@ -131,7 +131,7 @@ By binding attributes or methods to **globalThis**, you can implement data synch
entryAbilityWant = globalThis.entryAbilityWant; entryAbilityWant = globalThis.entryAbilityWant;
} }
// Page display. // UI page display.
build() { build() {
... ...
} }
...@@ -143,7 +143,7 @@ By binding attributes or methods to **globalThis**, you can implement data synch ...@@ -143,7 +143,7 @@ By binding attributes or methods to **globalThis**, you can implement data synch
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. 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. UIAbilityA stores a string and binds it to globalThis. 1. Save data in UIAbilityA and bind it to **globalThis**.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
...@@ -175,7 +175,7 @@ To implement data synchronization between two UIAbility components in the same a ...@@ -175,7 +175,7 @@ To implement data synchronization between two UIAbility components in the same a
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. 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. UIAbilityA stores a string and binds it to globalThis. 1. Save data in UIAbilityA and bind it to **globalThis**.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
...@@ -206,18 +206,18 @@ To implement data synchronization between the UIAbility and ExtensionAbility com ...@@ -206,18 +206,18 @@ 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 using 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 UIAbilityA and UIAbilityB 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.
- The lifecycle of an object bound to **globalThis** is the same as that of the ArkTS engine instance. You are advised to assign the value **null** after using the object to minimize memory usage. - The lifecycle of an object bound to **globalThis** is the same as that of the ArkTS engine instance. To minimize memory usage, you are advised to assign the value **null** to the object when it is not in use.
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 UIAbilityA file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis**. 1. In the UIAbilityA file, use **globalThis** to store [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md).
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
...@@ -230,7 +230,7 @@ The following provides an example to describe the object overwritten problem in ...@@ -230,7 +230,7 @@ The following provides an example to describe the object overwritten problem in
} }
``` ```
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. 2. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the UI page of UIAbilityA. When the UIAbilityA instance is not in use, switch it to the background.
```ts ```ts
@Entry @Entry
...@@ -239,14 +239,14 @@ The following provides an example to describe the object overwritten problem in ...@@ -239,14 +239,14 @@ The following provides an example to describe the object overwritten problem in
onPageShow() { onPageShow() {
let ctx = globalThis.context; // Obtain the context from globalThis and use it. let ctx = globalThis.context; // Obtain the context from globalThis and use it.
} }
// Page display. // UI page display.
build() { build() {
... ...
} }
} }
``` ```
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. 3. In the UIAbilityB file, use **globalThis** to store [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md), which is named the same as that in the UIAbilityA file.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
...@@ -260,7 +260,7 @@ The following provides an example to describe the object overwritten problem in ...@@ -260,7 +260,7 @@ The following provides an example to describe the object overwritten problem in
} }
``` ```
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. 4. Obtain [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) from the UI page of UIAbilityB and use it. The obtained **globalThis.context** is the value of [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) in UIAbilityB.
```ts ```ts
@Entry @Entry
...@@ -269,7 +269,7 @@ The following provides an example to describe the object overwritten problem in ...@@ -269,7 +269,7 @@ The following provides an example to describe the object overwritten problem in
onPageShow() { onPageShow() {
let ctx = globalThis.context; // Obtain the context from globalThis and use it. let ctx = globalThis.context; // Obtain the context from globalThis and use it.
} }
// Page display. // UI page display.
build() { build() {
... ...
} }
...@@ -289,7 +289,7 @@ The following provides an example to describe the object overwritten problem in ...@@ -289,7 +289,7 @@ The following provides an example to describe the object overwritten problem in
} }
``` ```
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. 6. When the UI page of UIAbilityA is displayed, the obtained **globalThis.context** is the value of [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) of UIAbilityB instead of UIAbilityA. An error occurs.
```ts ```ts
@Entry @Entry
...@@ -298,7 +298,7 @@ The following provides an example to describe the object overwritten problem in ...@@ -298,7 +298,7 @@ The following provides an example to describe the object overwritten problem in
onPageShow() { onPageShow() {
let ctx = globalThis.context; // The context in globalThis is the context of UIAbilityB. let ctx = globalThis.context; // The context in globalThis is the context of UIAbilityB.
} }
// Page display. // UI page display.
build() { build() {
... ...
} }
...@@ -307,4 +307,4 @@ The following provides an example to describe the object overwritten problem in ...@@ -307,4 +307,4 @@ The following provides an example to describe the object overwritten problem in
## Using AppStorage or LocalStorage for Data Synchronization ## 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-application-state-management-overview.md). 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 that manages state data shared among multiple UIAbilities. 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-application-state-management-overview.md).
# UIAbility Component Launch Type # UIAbility Launch Type
The launch type of the UIAbility component refers to the state of the UIAbility instance at startup. The system provides three launch types: The launch type of the UIAbility component refers to the state of the UIAbility instance at startup. Three launch types are available:
- [Singleton](#singleton) - [Singleton](#singleton)
...@@ -15,7 +15,7 @@ The launch type of the UIAbility component refers to the state of the UIAbility ...@@ -15,7 +15,7 @@ The launch type of the UIAbility component refers to the state of the UIAbility
**singleton** is the default launch type. **singleton** is the default launch type.
Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, if a UIAbility instance of this type already exists in the application process, the instance is reused. Therefore, only one UIAbility instance of this type exists in the system, that is, displayed in **Recents**. Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, if a UIAbility instance of this type already exists in the application process, the instance is reused. In other words, UIAbility of this type can have only one instance in the system, meaning that only one mission is displayed in the system application Recents.
**Figure 1** Demonstration effect in singleton mode **Figure 1** Demonstration effect in singleton mode
...@@ -23,9 +23,9 @@ Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbility ...@@ -23,9 +23,9 @@ Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbility
> **NOTE** > **NOTE**
> >
> Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **singleton**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not. > If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called to start an existing UIAbility instance in singleton mode, that instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not.
To use the singleton mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **singleton**. To use the singleton mode, set **launchType** in the [module.json5 file](../quick-start/module-configuration-file.md) to **singleton**.
```json ```json
...@@ -45,7 +45,7 @@ To use the singleton mode, set **launchType** in the [module.json5 configuration ...@@ -45,7 +45,7 @@ To use the singleton mode, set **launchType** in the [module.json5 configuration
## Multiton ## Multiton
In multiton mode, each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, a new UIAbility instance of this type is created in the application process. Multiple UIAbility instances of this type are displayed in **Recents**. In multiton mode, each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, a new UIAbility instance is created in the application process. Multiple missions are displayed for UIAbility of this type in Recents.
**Figure 2** Demonstration effect in multiton mode **Figure 2** Demonstration effect in multiton mode
...@@ -71,15 +71,15 @@ To use the multiton mode, set **launchType** in the [module.json5 file](../quick ...@@ -71,15 +71,15 @@ To use the multiton mode, set **launchType** in the [module.json5 file](../quick
## Specified ## Specified
The **specified** mode is used in some special scenarios. For example, in a document application, you want a document instance to be created each time you create a document, but you want to use the same document instance when you repeatedly open an existing document. The **specified** mode is used in some special scenarios. For example, in a document application, you may want a document instance to be created each time you create a document, and you may also want to use the same document instance when you open an existing document.
**Figure 3** Demonstration effect in specified mode **Figure 3** Demonstration effect in specified mode
![uiability-launch-type3](figures/uiability-launch-type3.gif) ![uiability-launch-type3](figures/uiability-launch-type3.gif)
For example, there are two UIAbility components: EntryAbility and SpecifiedAbility (with the launch type **specified**). You are required to start SpecifiedAbility from EntryAbility. In the following example, there are two UIAbility components: EntryAbility and SpecifiedAbility (with the launch type **specified**). To start SpecifiedAbility from EntryAbility, proceed as follows:
1. In SpecifiedAbility, set the **launchType** field in the [module.json5 file](../quick-start/module-configuration-file.md) to **specified**. 1. In SpecifiedAbility, set **launchType** in the [module.json5 file](../quick-start/module-configuration-file.md) to **specified**.
```json ```json
{ {
...@@ -95,10 +95,10 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili ...@@ -95,10 +95,10 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili
} }
``` ```
2. Create a unique string key for the instance. Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, the application, based on the key, identifies the UIAbility instance used to respond to the request. In EntryAbility, add a custom parameter, for example, **instanceKey**, to the **want** parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to distinguish the UIAbility instance. 2. Create a unique string key for the SpecifiedAbility instance. Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, the application, based on the key, identifies the UIAbility instance used to respond to the request. In EntryAbility, add a custom parameter, for example, **instanceKey**, to the **want** parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to distinguish the UIAbility instances.
```ts ```ts
// Configure an independent key for each UIAbility instance. // Configure a unique key for each UIAbility instance.
// For example, in the document usage scenario, use the document path as the key. // For example, in the document usage scenario, use the document path as the key.
function getInstance() { function getInstance() {
... ...
...@@ -122,16 +122,16 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili ...@@ -122,16 +122,16 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili
}) })
``` ```
3. Before SpecifiedAbility is started, the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of the corresponding AbilityStage instance is invoked to obtain the key of the UIAbility, because the launch type of SpecifiedAbility is set to **specified**. If a UIAbility instance matching the key exists, the system starts the UIAbility instance and invokes its [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback. Otherwise, the system creates a new UIAbility instance and invokes its [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks. 3. Before SpecifiedAbility is started, the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of the corresponding AbilityStage instance is invoked to obtain the key of the target UIAbility. If a UIAbility instance matching the key exists, the system starts the UIAbility instance and invokes its [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback. Otherwise, the system creates a new UIAbility instance and invokes its [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks.
In the sample code, the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback parses the **want** parameter to obtain the custom parameter **instanceKey**. The service logic returns a key string based on **instanceKey** parameter to identify the UIAbility instance. If the returned key maps to a started UIAbility instance, the system pulls the UIAbility instance back to the foreground and obtains the focus. If the returned key does not map to a started UIAbility instance, the system creates a new UIAbility instance and starts it. In the sample code, the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback uses the passed **want** parameter to obtain the custom parameter **instanceKey**. The service logic returns a key string based on the **instanceKey** parameter to identify the UIAbility instance. If the returned key maps to a started UIAbility instance, the system pulls the UIAbility instance back to the foreground and gives it the focus. If the returned key does not map to a started UIAbility instance, the system creates a new UIAbility instance and starts it.
```ts ```ts
import AbilityStage from '@ohos.app.ability.AbilityStage'; import AbilityStage from '@ohos.app.ability.AbilityStage';
export default class MyAbilityStage extends AbilityStage { export default class MyAbilityStage extends AbilityStage {
onAcceptWant(want): string { onAcceptWant(want): string {
// In the AbilityStage instance of the callee, a key value corresponding to a UIAbility instance is returned for UIAbility whose launch type is specified. // In the AbilityStage instance of the callee, a key string corresponding to a UIAbility instance is returned for UIAbility whose launch type is specified.
// In this example, SpecifiedAbility of module1 is returned. // In this example, SpecifiedAbility of module1 is returned.
if (want.abilityName === 'SpecifiedAbility') { if (want.abilityName === 'SpecifiedAbility') {
// The returned key string is a custom string. // The returned key string is a custom string.
...@@ -145,15 +145,16 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili ...@@ -145,15 +145,16 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili
> **NOTE** > **NOTE**
> >
> 1. Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **specified**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, and the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) matches a created UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not. > - If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called to start an existing UIAbility instance in specified mode, and the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) matches that UIAbility instance, that instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not.
> 2. AbilityStage is not automatically generated in the default project of DevEco Studio. For details about how to create an AbilityStage file, see [AbilityStage Component Container](abilitystage.md). >
> - AbilityStage is not automatically generated by default in the project of DevEco Studio. For details about how to create an AbilityStage file, see [AbilityStage Component Container](abilitystage.md).
For example, in the document application, different keys are bound to different document instances. Each time a document is created, a new key (for example, file path) is passed, and a new UIAbility instance is created when UIAbility is started in AbilityStage. However, when you open an existing document, the same UIAbility instance is started again in AbilityStage.
The following steps are used as an example. For example, in the document application, different keys are bound to different document instances. Each time a document is created, a new key (for example, file path) is passed in, and a new UIAbility instance is created when UIAbility is started in AbilityStage. However, when an existing document is opened, the same UIAbility instance is started again in AbilityStage.
1. Open file A. A UIAbility instance, for example, UIAbility instance 1, is started. The following steps are used as an example.
2. Close the process of file A in **Recents**. UIAbility instance 1 is destroyed. Return to the home screen and open file A again. A new UIAbility instance is started, for example, UIAbility instance 2.
3. Return to the home screen and open file B. A new UIAbility instance is started, for example, UIAbility instance 3.
4. Return to the home screen and open file A again. UIAbility instance 2 is started. This is because the system automatically matches the key of the UIAbility instance and starts the UIAbility instance that has a matching key. In this example, UIAbility instance 2 has the same key as file A. Therefore, the system pulls back UIAbility instance 2 and focuses it without creating a new instance.
1. Open file A. A UIAbility instance, UIAbility instance 1, is started.
2. Close the process of file A in Recents. UIAbility instance 1 is destroyed. Return to the home screen and open file A again. A new UIAbility instance, UIAbility instance 2, is started.
3. Return to the home screen and open file B. A new UIAbility instance, UIAbility instance 3, is started.
4. Return to the home screen and open file A again. UIAbility instance 2 is started. This is because the system automatically matches the key with the UIAbility instance and starts the UIAbility instance that has a matching key. In this example, UIAbility instance 2 has the same key as file A. Therefore, the system pulls back UIAbility instance 2 and focuses it without creating a new instance.hao
# UIAbility Component Lifecycle # UIAbility Lifecycle
## Overview ## Overview
When a user opens, switches, and returns to an application, the UIAbility instances in the application transit in their different states. The UIAbility class provides a series of callbacks. Through these callbacks, you can know the state changes of the UIAbility instance, for example, being created or destroyed, or running in the foreground or background. When a user opens or switches to and from an application, the UIAbility instances in the application transit in their different states. The UIAbility class provides a series of callbacks. Through these callbacks, you can know the state changes of the UIAbility instance.
The lifecycle of UIAbility has four states: **Create**, **Foreground**, **Background**, and **Destroy**, as shown in the figure below. The lifecycle of UIAbility has four states: **Create**, **Foreground**, **Background**, and **Destroy**, as shown in the figure below.
...@@ -17,7 +17,7 @@ The lifecycle of UIAbility has four states: **Create**, **Foreground**, **Backgr ...@@ -17,7 +17,7 @@ The lifecycle of UIAbility has four states: **Create**, **Foreground**, **Backgr
### Create ### Create
The **Create** state is triggered when the UIAbility instance is created during application loading. The system invokes the **onCreate()** callback. In this callback, you can perform application initialization operations, for example, defining variables or loading resources. The **Create** state is triggered when the UIAbility instance is created during application loading. It corresponds to the **onCreate()** callback. In this callback, you can perform application initialization operations, for example, defining variables or loading resources.
```ts ```ts
...@@ -33,13 +33,14 @@ export default class EntryAbility extends UIAbility { ...@@ -33,13 +33,14 @@ export default class EntryAbility extends UIAbility {
> **NOTE** > **NOTE**
> >
> [Want](../reference/apis/js-apis-app-ability-want.md) is used as the carrier to transfer information between application components. For details, see [Want](want-overview.md). > The [want](../reference/apis/js-apis-app-ability-want.md) parameter in the **onCreate()** callback is used as the carrier to transfer information between application components. For details, see [Want](want-overview.md).
### WindowStageCreate and WindowStageDestory ### WindowStageCreate and WindowStageDestory
After the UIAbility instance is created but before it enters the **Foreground** state, the system creates a WindowStage instance and triggers the **onWindowStageCreate()** callback. You can set UI loading and WindowStage event subscription in the callback. After the UIAbility instance is created but before it enters the **Foreground** state, the system creates a WindowStage instance and triggers the **onWindowStageCreate()** callback. You can set UI loading and WindowStage event subscription in the callback.
**Figure 2** WindowStageCreate and WindowStageDestory **Figure 2** WindowStageCreate and WindowStageDestory
![Ability-Life-Cycle-WindowStage](figures/Ability-Life-Cycle-WindowStage.png) ![Ability-Life-Cycle-WindowStage](figures/Ability-Life-Cycle-WindowStage.png)
In the **onWindowStageCreate()** callback, use [loadContent()](../reference/apis/js-apis-window.md#loadcontent9-2) to set the page to be loaded, and call [on('windowStageEvent')](../reference/apis/js-apis-window.md#onwindowstageevent9) to subscribe to [WindowStage events](../reference/apis/js-apis-window.md#windowstageeventtype9), for example, having or losing focus, or becoming visible or invisible. In the **onWindowStageCreate()** callback, use [loadContent()](../reference/apis/js-apis-window.md#loadcontent9-2) to set the page to be loaded, and call [on('windowStageEvent')](../reference/apis/js-apis-window.md#onwindowstageevent9) to subscribe to [WindowStage events](../reference/apis/js-apis-window.md#windowstageeventtype9), for example, having or losing focus, or becoming visible or invisible.
...@@ -78,7 +79,7 @@ export default class EntryAbility extends UIAbility { ...@@ -78,7 +79,7 @@ export default class EntryAbility extends UIAbility {
JSON.stringify(exception)); JSON.stringify(exception));
} }
// Set UI loading. // Set the page to be loaded.
windowStage.loadContent('pages/Index', (err, data) => { windowStage.loadContent('pages/Index', (err, data) => {
... ...
}); });
...@@ -86,7 +87,7 @@ export default class EntryAbility extends UIAbility { ...@@ -86,7 +87,7 @@ export default class EntryAbility extends UIAbility {
} }
``` ```
> **NOTE**<br> > **NOTE**
> >
> For details about how to use WindowStage, see [Window Development](../windowmanager/application-window-stage.md). > For details about how to use WindowStage, see [Window Development](../windowmanager/application-window-stage.md).
...@@ -121,15 +122,15 @@ export default class EntryAbility extends UIAbility { ...@@ -121,15 +122,15 @@ export default class EntryAbility extends UIAbility {
### Foreground and Background ### Foreground and Background
The **Foreground** and **Background** states are triggered when the UIAbility instance is switched to the foreground and background respectively. They correspond to the **onForeground()** and **onBackground()** callbacks. The **Foreground** and **Background** states are triggered when the UIAbility instance is switched to the foreground and background, respectively. They correspond to the **onForeground()** and **onBackground()** callbacks.
The **onForeground()** callback is triggered before the UI of the UIAbility instance becomes visible, for example, when the UIAbility instance is switched to the foreground. In this callback, you can apply for resources required by the system or re-apply for resources that have been released in the **onBackground()** callback. The **onForeground()** callback is triggered when the UI of the UIAbility instance is about to become visible, for example, when the UIAbility instance is about to enter the foreground. In this callback, you can apply for resources required by the system or re-apply for resources that have been released in the **onBackground()** callback.
The **onBackground()** callback is triggered after the UI of the UIAbility component is completely invisible, for example, when the UIAbility instance is switched to the background. In this callback, you can release useless resources or perform time-consuming operations such as saving the status. The **onBackground()** callback is triggered when the UI of the UIAbility instance is about to become invisible, for example, when the UIAbility instance is about to enter the background. In this callback, you can release unused resources or perform time-consuming operations such as saving the status.
For example, an application needs to use positioning, and the application has requested the positioning permission from the user. Before the UI is displayed, you can enable positioning in the **onForeground()** callback to obtain the location information. For example, there is an application that requires location access and has obtained the location permission from the user. Before the UI is displayed, you can enable location in the **onForeground()** callback to obtain the location information.
When the application is switched to the background, you can disable positioning in the **onBackground()** callback to reduce system resource consumption. When the application is switched to the background, you can disable location in the **onBackground()** callback to reduce system resource consumption.
```ts ```ts
...@@ -143,7 +144,7 @@ export default class EntryAbility extends UIAbility { ...@@ -143,7 +144,7 @@ export default class EntryAbility extends UIAbility {
} }
onBackground() { onBackground() {
// Release useless resources when the UI is invisible, or perform time-consuming operations in this callback, // Release unused resources when the UI is invisible, or perform time-consuming operations in this callback,
// for example, saving the status. // for example, saving the status.
} }
} }
...@@ -154,7 +155,7 @@ export default class EntryAbility extends UIAbility { ...@@ -154,7 +155,7 @@ export default class EntryAbility extends UIAbility {
The **Destroy** state is triggered when the UIAbility instance is destroyed. You can perform operations such as releasing system resources and saving data in the **onDestroy()** callback. The **Destroy** state is triggered when the UIAbility instance is destroyed. You can perform operations such as releasing system resources and saving data in the **onDestroy()** callback.
The UIAbility instance is destroyed when **terminateSelf()** is called or the user closes the instance in **Recents**. The UIAbility instance is destroyed when **terminateSelf()** is called or the user closes the instance in the system application Recents.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
......
# UIAbility Component Overview # UIAbility Overview
## Overview ## Overview
UIAbility is a type of application component that provides the UI for user interaction. UIAbility is a type of application component that provides the UI for user interactions.
The following design philosophy is behind UIAbility: The following design philosophy is behind UIAbility:
1. Native support for [cross-device migration](hop-cross-device-migration.md) and [multi-device collaboration](hop-multi-device-collaboration.md) at the application component level 1. Native support for [cross-device migration](hop-cross-device-migration.md) and [multi-device collaboration](hop-multi-device-collaboration.md) at the application component level
2. Support for multiple device types and window forms 2. Support for multiple device types and window modes
> **NOTE** > **NOTE**
> >
> For details, see [Interpretation of the Application Model](application-model-description.md). > For details, see [Interpretation of the Application Model](application-model-description.md).
The UIAbility division principles and suggestions are as follows: UIAbility is the basic unit of scheduling in OpenHarmony and provides a window for applications to draw the UI. An application can contain one or more UIAbility components. For example, for a payment application, you can use separate UIAbility components to carry the entry and payment functionalities.
UIAbility is the basic unit scheduled by the system and provides a window for applications to draw UIs. An application can contain one or more UIAbility components. For example, for a payment application, you can use two UIAbility components to carry the entry and payment functionalities. Each UIAbility component instance is displayed as a mission in the system application Recents.
Each UIAbility component instance is displayed as a mission in Recents.
You can develop a single UIAbility or multiple UIAbilities for your application based on service requirements. You can develop a single UIAbility or multiple UIAbilities for your application based on service requirements.
- If you want only one mission to be displayed in Recents, use one UIAbility and multiple pages. - If you want your application to be displayed as one mission in Recents, use one UIAbility and multiple pages.
- If you want multiple missions to be displayed in Recents or multiple windows to be opened simultaneously, use multiple UIAbilities. - If you want your application to be displayed as multiple missions in Recents or multiple windows to be opened simultaneously, use multiple UIAbilities.
## Privacy Statement Configuration ## Declaration Configuration
To enable an application to properly use a UIAbility component, declare the UIAbility name, entry, and tags under [abilities](../quick-start/module-configuration-file.md#abilities) in the [module.json5 configuration file](../quick-start/module-configuration-file.md). To enable an application to properly use a UIAbility component, declare the UIAbility name, entry, and label under [abilities](../quick-start/module-configuration-file.md#abilities) in the [module.json5 file](../quick-start/module-configuration-file.md).
```json ```json
......
# UIAbility Component Usage # UIAbility Usage
When using the UIAbility component, you must specify a startup page and obtain the context, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md). When using the UIAbility component, you must specify a startup page and obtain the context, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md).
...@@ -6,7 +6,7 @@ When using the UIAbility component, you must specify a startup page and obtain t ...@@ -6,7 +6,7 @@ When using the UIAbility component, you must specify a startup page and obtain t
## Specifying the Startup Page of UIAbility ## Specifying the Startup Page of UIAbility
If no startup page is specified, a white screen occurs after the application is started. You can use **loadContent()** of [WindowStage](../reference/apis/js-apis-window.md#windowstage9) to set the startup page in the **onWindowStageCreate()** callback of the UIAbility instance. You can use **loadContent()** of [WindowStage](../reference/apis/js-apis-window.md#windowstage9) to set the startup page in the **onWindowStageCreate()** callback of the UIAbility instance. If no startup page is specified, a white screen occurs after the application is started.
```ts ```ts
...@@ -27,7 +27,7 @@ export default class EntryAbility extends UIAbility { ...@@ -27,7 +27,7 @@ export default class EntryAbility extends UIAbility {
> **NOTE** > **NOTE**
> >
> When you create UIAbility in DevEco Studio, the UIAbility instance loads the **Index** page by default. Therefore, you only need to replace the **Index** page path with the required startup page path. > When you create UIAbility in DevEco Studio, the UIAbility instance loads the **Index** page as its startup page. Therefore, you only need to replace the **Index** page path with the required startup page path.
## Obtaining the Context of UIAbility ## Obtaining the Context of UIAbility
......
...@@ -115,7 +115,7 @@ To create a widget in the FA model, implement the widget lifecycle callbacks. Ge ...@@ -115,7 +115,7 @@ To create a widget in the FA model, implement the widget lifecycle callbacks. Ge
import formBindingData from '@ohos.app.form.formBindingData'; import formBindingData from '@ohos.app.form.formBindingData';
import formInfo from '@ohos.app.form.formInfo'; import formInfo from '@ohos.app.form.formInfo';
import formProvider from '@ohos.app.form.formProvider'; import formProvider from '@ohos.app.form.formProvider';
import dataStorage from '@ohos.data.storage'; import dataPreferences from '@ohos.data.preferences';
``` ```
2. Implement the widget lifecycle callbacks in **form.ts**. 2. Implement the widget lifecycle callbacks in **form.ts**.
...@@ -265,7 +265,7 @@ async function storeFormInfo(formId: string, formName: string, tempFlag: boolean ...@@ -265,7 +265,7 @@ async function storeFormInfo(formId: string, formName: string, tempFlag: boolean
"updateCount": 0 "updateCount": 0
}; };
try { try {
const storage = await dataStorage.getStorage(DATA_STORAGE_PATH); const storage = await dataPreferences.getPreferences(this.context, DATA_STORAGE_PATH);
// Put the widget information. // Put the widget information.
await storage.put(formId, JSON.stringify(formInfo)); await storage.put(formId, JSON.stringify(formInfo));
console.info(`storeFormInfo, put form info successfully, formId: ${formId}`); console.info(`storeFormInfo, put form info successfully, formId: ${formId}`);
...@@ -303,7 +303,7 @@ You should override **onDestroy** to implement widget data deletion. ...@@ -303,7 +303,7 @@ You should override **onDestroy** to implement widget data deletion.
const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store"; const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store";
async function deleteFormInfo(formId: string) { async function deleteFormInfo(formId: string) {
try { try {
const storage = await dataStorage.getStorage(DATA_STORAGE_PATH); const storage = await dataPreferences.getPreferences(this.context, DATA_STORAGE_PATH);
// Delete the widget information. // Delete the widget information.
await storage.delete(formId); await storage.delete(formId);
console.info(`deleteFormInfo, del form info successfully, formId: ${formId}`); console.info(`deleteFormInfo, del form info successfully, formId: ${formId}`);
......
...@@ -13,7 +13,7 @@ Widget switching involves the following parts: ...@@ -13,7 +13,7 @@ Widget switching involves the following parts:
| Configuration item location | **formAbility** and **forms** are in the **config.json** file.| **extensionAbilities** (configuration for **formExtensionAbility**) is in the **module.json5** file in the level-1 directory, and **forms** (configuration for **forms** contained in **formExtensionAbility**) is in the **form_config.json** file in the level-2 directory.| | Configuration item location | **formAbility** and **forms** are in the **config.json** file.| **extensionAbilities** (configuration for **formExtensionAbility**) is in the **module.json5** file in the level-1 directory, and **forms** (configuration for **forms** contained in **formExtensionAbility**) is in the **form_config.json** file in the level-2 directory.|
| Widget code path | Specified by **srcPath**, without the file name. | Specified by **srcEntry**, with the file name. | | Widget code path | Specified by **srcPath**, without the file name. | Specified by **srcEntry**, with the file name. |
| Programming language | **srcLanguage** can be set to **js** or **ets**. | This configuration item is unavailable. Only ets is supported. | | Programming language | **srcLanguage** can be set to **js** or **ets**. | This configuration item is unavailable. Only ets is supported. |
| Whether to enable widgets | formsEnabled | This configuration item is unavailable. The setting of **type** set to **form** means that the widgets are enabled. | | Whether to enable widgets | formsEnabled | This configuration item is unavailable. When **type** is set to **form**, widgets are enabled. |
| Ability type | type: service | type: form | | Ability type | type: service | type: form |
| Level-2 directory configuration tag| This configuration item is unavailable. | **metadata**, which consists of **name**, **value**, and **resource**, where **resource** points to the location of the **form_config.json** file in the level-2 directory.| | Level-2 directory configuration tag| This configuration item is unavailable. | **metadata**, which consists of **name**, **value**, and **resource**, where **resource** points to the location of the **form_config.json** file in the level-2 directory.|
......
# window Switching # window Switching
| API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| | API in the FA Model| Corresponding .d.ts File in the Stage Model| Corresponding API in the Stage Model|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| [create(id: string, type: WindowType, callback: AsyncCallback&lt;Window&gt;): void;](../reference/apis/js-apis-window.md#windowcreatedeprecated)<br>[create(id: string, type: WindowType): Promise&lt;Window&gt;;](../reference/apis/js-apis-window.md#windowcreatedeprecated-1) | \@ohos.window.d.ts | [createSubWindow(name: string, callback: AsyncCallback&lt;Window&gt;): void;](../reference/apis/js-apis-window.md#createsubwindow9)<br>[createSubWindow(name: string): Promise;](../reference/apis/js-apis-window.md#createsubwindow9-1)<br>An application developed on the FA model uses **window.create(id, WindowType.TYPE_APP)** to create a subwindow, whereas an application developed on the stage model uses **WindowStage.CreateSubWindow()** to create a subwindow.| | [create(id: string, type: WindowType, callback: AsyncCallback&lt;Window&gt;): void;](../reference/apis/js-apis-window.md#windowcreatedeprecated)<br>[create(id: string, type: WindowType): Promise&lt;Window&gt;;](../reference/apis/js-apis-window.md#windowcreatedeprecated-1) | \@ohos.window.d.ts | [createSubWindow(name: string, callback: AsyncCallback&lt;Window&gt;): void;](../reference/apis/js-apis-window.md#createsubwindow9)<br>[createSubWindow(name: string): Promise;](../reference/apis/js-apis-window.md#createsubwindow9-1)<br>An application developed on the FA model uses **window.create(id, WindowType.TYPE_APP)** to create a subwindow, whereas an application developed on the stage model uses **WindowStage.CreateSubWindow()** to create a subwindow.|
| [getTopWindow(callback: AsyncCallback&lt;Window&gt;): void;](../reference/apis/js-apis-window.md#windowgettopwindowdeprecated)<br>[getTopWindow(): Promise&lt;Window&gt;;](../reference/apis/js-apis-window.md#windowgettopwindowdeprecated-1) | \@ohos.window.d.ts | [getLastWindow(ctx: BaseContext, callback: AsyncCallback&lt;Window&gt;): void;](../reference/apis/js-apis-window.md#windowgetlastwindow9)<br>[getLastWindow(ctx: BaseContext): Promise&lt;Window&gt;;](../reference/apis/js-apis-window.md#windowgetlastwindow9-1) | | [getTopWindow(callback: AsyncCallback&lt;Window&gt;): void;](../reference/apis/js-apis-window.md#windowgettopwindowdeprecated)<br>[getTopWindow(): Promise&lt;Window&gt;;](../reference/apis/js-apis-window.md#windowgettopwindowdeprecated-1) | \@ohos.window.d.ts | [getLastWindow(ctx: BaseContext, callback: AsyncCallback&lt;Window&gt;): void;](../reference/apis/js-apis-window.md#windowgetlastwindow9)<br>[getLastWindow(ctx: BaseContext): Promise&lt;Window&gt;;](../reference/apis/js-apis-window.md#windowgetlastwindow9-1) |
...@@ -11,7 +11,7 @@ the context is [WindowExtensionContext](../reference/apis/js-apis-inner-applicat ...@@ -11,7 +11,7 @@ the context is [WindowExtensionContext](../reference/apis/js-apis-inner-applicat
> **NOTE** > **NOTE**
> >
> **WindowExtensionAbility** is a system API. To embed a third-party application in another application and display it over the application, switch to the full SDK by following the instructions provided in [Guide to Switching to Full SDK](../faqs/full-sdk-switch-guide.md). > **WindowExtensionAbility** is a system API. To use it, switch to the full SDK by following the instructions provided in [Guide to Switching to Full SDK](../faqs/full-sdk-switch-guide.md).
> >
...@@ -19,11 +19,11 @@ the context is [WindowExtensionContext](../reference/apis/js-apis-inner-applicat ...@@ -19,11 +19,11 @@ the context is [WindowExtensionContext](../reference/apis/js-apis-inner-applicat
The **WindowExtensionAbility** class provides **onConnect()**, **onDisconnect()**, and **onWindowReady()** lifecycle callbacks, which can be overridden. The **WindowExtensionAbility** class provides **onConnect()**, **onDisconnect()**, and **onWindowReady()** lifecycle callbacks, which can be overridden.
- The **onWindowReady()** callback is invoked when a window is created for the ability. - The **onWindowReady()** callback is invoked when a window is created for the UIAbility.
- The **onConnect()** callback is invoked when the AbilityComponent corresponding to the window connects to the ability. - The **onConnect()** callback is invoked when the AbilityComponent corresponding to the window connects to the UIAbility.
- The **onDisconnect()** callback is invoked when the AbilityComponent disconnects from the ability. - The **onDisconnect()** callback is invoked when the AbilityComponent disconnects from the UIAbility.
**How to Develop** **How to Develop**
......
# IPC & RPC Development # IPC & RPC Development Guidelines
## When to Use ## When to Use
...@@ -11,8 +11,8 @@ Table 1 Native IPC APIs ...@@ -11,8 +11,8 @@ Table 1 Native IPC APIs
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| [IRemoteBroker](../reference/apis/js-apis-rpc.md#iremotebroker) | sptr&lt;IRemoteObject&gt; AsObject() | Holder of a remote proxy object. If you call this API on the stub, the **RemoteObject** is returned; if you call this API on the proxy, the proxy object is returned.| | [IRemoteBroker](../reference/apis/js-apis-rpc.md#iremotebroker) | sptr&lt;IRemoteObject&gt; AsObject() | Obtains the holder of a remote proxy object. If you call this API on the stub, the **RemoteObject** is returned; if you call this API on the proxy, the proxy object is returned.|
| IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &amp;data, MessageParcel &amp;reply, MessageOption &amp;option) | Callback used to process a request from the proxy and return the result. Derived classes need to override this API.| | IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &amp;data, MessageParcel &amp;reply, MessageOption &amp;option) | Called to process a request from the proxy and return the result. Derived classes need to override this API.|
| IRemoteProxy | | Service proxy class, which is derived from the **IRemoteProxy** class.| | IRemoteProxy | | Service proxy class, which is derived from the **IRemoteProxy** class.|
...@@ -29,7 +29,7 @@ Table 1 Native IPC APIs ...@@ -29,7 +29,7 @@ Table 1 Native IPC APIs
external_deps = [ external_deps = [
"ipc:ipc_single", "ipc:ipc_single",
] ]
#RPC scenario #RPC scenario
external_deps = [ external_deps = [
"ipc:ipc_core", "ipc:ipc_core",
...@@ -50,12 +50,12 @@ Table 1 Native IPC APIs ...@@ -50,12 +50,12 @@ Table 1 Native IPC APIs
```c++ ```c++
#include "iremote_broker.h" #include "iremote_broker.h"
// Define message codes. // Define message codes.
const int TRANS_ID_PING_ABILITY = 5 const int TRANS_ID_PING_ABILITY = 5;
const std::string DESCRIPTOR = "test.ITestAbility"; const std::string DESCRIPTOR = "test.ITestAbility";
class ITestAbility : public IRemoteBroker { class ITestAbility : public IRemoteBroker {
public: public:
// DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string. // DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string.
...@@ -71,13 +71,13 @@ Table 1 Native IPC APIs ...@@ -71,13 +71,13 @@ Table 1 Native IPC APIs
```c++ ```c++
#include "iability_test.h" #include "iability_test.h"
#include "iremote_stub.h" #include "iremote_stub.h"
class TestAbilityStub : public IRemoteStub<ITestAbility> { class TestAbilityStub : public IRemoteStub<ITestAbility> {
public: public:
virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
int TestPingAbility(const std::u16string &dummy) override; int TestPingAbility(const std::u16string &dummy) override;
}; };
int TestAbilityStub::OnRemoteRequest(uint32_t code, int TestAbilityStub::OnRemoteRequest(uint32_t code,
MessageParcel &data, MessageParcel &reply, MessageOption &option) MessageParcel &data, MessageParcel &reply, MessageOption &option)
{ {
...@@ -98,12 +98,12 @@ Table 1 Native IPC APIs ...@@ -98,12 +98,12 @@ Table 1 Native IPC APIs
```c++ ```c++
#include "iability_server_test.h" #include "iability_server_test.h"
class TestAbility : public TestAbilityStub { class TestAbility : public TestAbilityStub {
public: public:
int TestPingAbility(const std::u16string &dummy); int TestPingAbility(const std::u16string &dummy);
} }
int TestAbility::TestPingAbility(const std::u16string &dummy) { int TestAbility::TestPingAbility(const std::u16string &dummy) {
return 0; return 0;
} }
...@@ -117,7 +117,7 @@ Table 1 Native IPC APIs ...@@ -117,7 +117,7 @@ Table 1 Native IPC APIs
#include "iability_test.h" #include "iability_test.h"
#include "iremote_proxy.h" #include "iremote_proxy.h"
#include "iremote_object.h" #include "iremote_object.h"
class TestAbilityProxy : public IRemoteProxy<ITestAbility> { class TestAbilityProxy : public IRemoteProxy<ITestAbility> {
public: public:
explicit TestAbilityProxy(const sptr<IRemoteObject> &impl); explicit TestAbilityProxy(const sptr<IRemoteObject> &impl);
...@@ -125,12 +125,12 @@ Table 1 Native IPC APIs ...@@ -125,12 +125,12 @@ Table 1 Native IPC APIs
private: private:
static inline BrokerDelegator<TestAbilityProxy> delegator_; // Use the iface_cast macro. static inline BrokerDelegator<TestAbilityProxy> delegator_; // Use the iface_cast macro.
} }
TestAbilityProxy::TestAbilityProxy(const sptr<IRemoteObject> &impl) TestAbilityProxy::TestAbilityProxy(const sptr<IRemoteObject> &impl)
: IRemoteProxy<ITestAbility>(impl) : IRemoteProxy<ITestAbility>(impl)
{ {
} }
int TestAbilityProxy::TestPingAbility(const std::u16string &dummy){ int TestAbilityProxy::TestPingAbility(const std::u16string &dummy){
MessageOption option; MessageOption option;
MessageParcel dataParcel, replyParcel; MessageParcel dataParcel, replyParcel;
...@@ -149,7 +149,7 @@ Table 1 Native IPC APIs ...@@ -149,7 +149,7 @@ Table 1 Native IPC APIs
// Register the TestAbilityStub instance with the SystemAbilityManager on the same device as the SA. // Register the TestAbilityStub instance with the SystemAbilityManager on the same device as the SA.
auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
samgr->AddSystemAbility(saId, new TestAbility()); samgr->AddSystemAbility(saId, new TestAbility());
// Register the TestAbilityStub instance with the SystemAbilityManager on a different device. // Register the TestAbilityStub instance with the SystemAbilityManager on a different device.
auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
ISystemAbilityManager::SAExtraProp saExtra; ISystemAbilityManager::SAExtraProp saExtra;
...@@ -166,10 +166,10 @@ Table 1 Native IPC APIs ...@@ -166,10 +166,10 @@ Table 1 Native IPC APIs
sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(saId); sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(saId);
sptr<ITestAbility> testAbility = iface_cast<ITestAbility>(remoteObject); // Use the iface_cast macro to convert the proxy to a specific type. sptr<ITestAbility> testAbility = iface_cast<ITestAbility>(remoteObject); // Use the iface_cast macro to convert the proxy to a specific type.
// Obtain the proxy of the SA registered with any other devices. // Obtain the proxy of the SA registered with any other devices.
sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
// networkId is the device identifier and can be obtained through GetLocalNodeDeviceInfo. // networkId is the device identifier and can be obtained through GetLocalNodeDeviceInfo.
sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(saId, networkId); sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(saId, networkId);
sptr<TestAbilityProxy> proxy(new TestAbilityProxy(remoteObject)); // Construct a proxy. sptr<TestAbilityProxy> proxy(new TestAbilityProxy(remoteObject)); // Construct a proxy.
...@@ -180,59 +180,97 @@ Table 1 Native IPC APIs ...@@ -180,59 +180,97 @@ Table 1 Native IPC APIs
1. Add dependencies. 1. Add dependencies.
```ts ```ts
import rpc from "@ohos.rpc" import rpc from "@ohos.rpc";
import featureAbility from "@ohos.ability.featureAbility" // Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import featureAbility from "@ohos.ability.featureAbility";
``` ```
If you use the stage model, you need to obtain the context. The sample code is as follows:
```ts
import Ability from "@ohos.app.ability.UIAbility";
export default class MainAbility extends Ability {
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate");
globalThis.context = this.context;
}
onDestroy() {
console.log("[Demo] MainAbility onDestroy");
}
onWindowStageCreate(windowStage) {
// Main window is created, set main page for this ability
console.log("[Demo] MainAbility onWindowStageCreate");
}
onWindowStageDestroy() {
// Main window is destroyed, release UI related resources
console.log("[Demo] MainAbility onWindowStageDestroy");
}
onForeground() {
// Ability has brought to foreground
console.log("[Demo] MainAbility onForeground");
}
onBackground() {
// Ability has back to background
console.log("[Demo] MainAbility onBackground");
}
}
```
2. Bind the desired ability. 2. Bind the desired ability.
Construct the **want** variable, and specify the bundle name and component name of the application where the ability is located. If cross-device communication is involved, also specify the network ID of the target device, which can be obtained through **deviceManager**. Then, construct the **connect** variable, and specify the callback that is called when the binding is successful, the binding fails, or the ability is disconnected. After that, call the API provided by **featureAbility** to bind an ability. Construct the **want** variable, and specify the bundle name and component name of the application where the ability is located. If cross-device communication is involved, also specify the network ID of the target device, which can be obtained through **deviceManager**. Then, construct the **connect** variable, and specify the callback that is called when the binding is successful, the binding fails, or the ability is disconnected. If you use the FA model, call the API provided by **featureAbility** to bind an ability. If you use the stage model, obtain a service instance through **Context**, and then call the API provided by **featureAbility** to bind an ability.
```ts ```ts
import rpc from "@ohos.rpc" import rpc from "@ohos.rpc";
import featureAbility from "@ohos.ability.featureAbility" // Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import featureAbility from "@ohos.ability.featureAbility";
let proxy = null
let connectId = null let proxy = null;
let connectId = null;
// Bind the ability on a single device. // Bind the ability on a single device.
let want = { let want = {
// Enter the bundle name and ability name. // Enter the bundle name and ability name.
"bundleName": "ohos.rpc.test.server", "bundleName": "ohos.rpc.test.server",
"abilityName": "ohos.rpc.test.server.ServiceAbility", "abilityName": "ohos.rpc.test.server.ServiceAbility",
} };
let connect = { let connect = {
onConnect:function(elementName, remote) { onConnect:function(elementName, remote) {
proxy = remote proxy = remote;
}, },
onDisconnect:function(elementName) { onDisconnect:function(elementName) {
}, },
onFailed:function() { onFailed:function() {
proxy = null proxy = null;
} }
} };
connectId = featureAbility.connectAbility(want, connect) // Use this method to connect to the ability in the FA model.
// connectId = featureAbility.connectAbility(want, connect);
connectId = globalThis.context.connectServiceExtensionAbility(want,connect);
// If you're binding the ability across devices, use deviceManager to obtain the network ID of the target device. // If you're binding the ability across devices, use deviceManager to obtain the network ID of the target device.
import deviceManager from '@ohos.distributedHardware.deviceManager' import deviceManager from '@ohos.distributedHardware.deviceManager';
function deviceManagerCallback(deviceManager) { function deviceManagerCallback(deviceManager) {
let deviceList = deviceManager.getTrustedDeviceListSync() let deviceList = deviceManager.getTrustedDeviceListSync();
let networkId = deviceList[0].networkId let networkId = deviceList[0].networkId;
let want = { let want = {
"bundleName": "ohos.rpc.test.server", "bundleName": "ohos.rpc.test.server",
"abilityName": "ohos.rpc.test.service.ServiceAbility", "abilityName": "ohos.rpc.test.service.ServiceAbility",
"networkId": networkId, "networkId": networkId,
"flags": 256 "flags": 256
} };
connectId = featureAbility.connectAbility(want, connect) // The ID returned after the connection is set up must be saved. The ID will be passed for service disconnection.
// Use this method to connect to the ability in the FA model.
// connectId = featureAbility.connectAbility(want, connect);
connectId = globalThis.context.connectServiceExtensionAbility(want,connect);
} }
// The first parameter specifies the bundle name of the application, and the second parameter specifies the callback used to return the device ID obtained by using DeviceManager. // The first parameter specifies the bundle name of the application, and the second parameter specifies the callback used to return the device ID obtained by using DeviceManager.
deviceManager.createDeviceManager("ohos.rpc.test", deviceManagerCallback) deviceManager.createDeviceManager("ohos.rpc.test", deviceManagerCallback);
``` ```
3. Process requests sent from the client. 3. Process requests sent from the client.
...@@ -240,77 +278,79 @@ Table 1 Native IPC APIs ...@@ -240,77 +278,79 @@ Table 1 Native IPC APIs
```ts ```ts
onConnect(want: Want) { onConnect(want: Want) {
var robj:rpc.RemoteObject = new Stub("rpcTestAbility") var robj:rpc.RemoteObject = new Stub("rpcTestAbility");
return robj return robj;
} }
class Stub extends rpc.RemoteObject { class Stub extends rpc.RemoteObject {
constructor(descriptor) { constructor(descriptor) {
super(descriptor) super(descriptor);
} }
onRemoteMessageRequest(code, data, reply, option) { onRemoteMessageRequest(code, data, reply, option) {
// Process requests sent from the client based on the code. // Process requests sent from the client based on the code.
return true return true;
} }
} }
``` ```
4. Process responses sent from the server. 4. Process responses sent from the server.
Obtain the proxy object from the **onConnect** callback, call **sendRequestAsync** to send a request, and receive the response using a callback or a promise (an object representing the eventual completion or failure of an asynchronous operation and its result value). Obtain the proxy object from the **onConnect** callback, call **sendRequest** to send a request, and receive the response using a callback or a promise (an object representing the eventual completion or failure of an asynchronous operation and its result value).
```ts ```ts
// Use a promise. // Use a promise.
let option = new rpc.MessageOption() let option = new rpc.MessageOption();
let data = rpc.MessageParcel.create() let data = rpc.MessageParcel.create();
let reply = rpc.MessageParcel.create() let reply = rpc.MessageParcel.create();
// Write parameters to data. // Write parameters to data.
proxy.sendRequestAsync(1, data, reply, option) proxy.sendRequest(1, data, reply, option)
.then(function(result) { .then(function(result) {
if (result.errCode != 0) { if (result.errCode != 0) {
console.error("send request failed, errCode: " + result.errCode) console.error("send request failed, errCode: " + result.errCode);
return return;
} }
// Read the result from result.reply. // Read the result from result.reply.
}) })
.catch(function(e) { .catch(function(e) {
console.error("send request got exception: " + e) console.error("send request got exception: " + e);
} })
.finally(() => { .finally(() => {
data.reclaim() data.reclaim();
reply.reclaim() reply.reclaim();
}) })
// Use a callback. // Use a callback.
function sendRequestCallback(result) { function sendRequestCallback(result) {
try { try {
if (result.errCode != 0) { if (result.errCode != 0) {
console.error("send request failed, errCode: " + result.errCode) console.error("send request failed, errCode: " + result.errCode);
return return;
} }
// Read the result from result.reply. // Read the result from result.reply.
} finally { } finally {
result.data.reclaim() result.data.reclaim();
result.reply.reclaim() result.reply.reclaim();
} }
} }
let option = new rpc.MessageOption() let option = new rpc.MessageOption();
let data = rpc.MessageParcel.create() let data = rpc.MessageParcel.create();
let reply = rpc.MessageParcel.create() let reply = rpc.MessageParcel.create();
// Write parameters to data. // Write parameters to data.
proxy.sendRequest(1, data, reply, option, sendRequestCallback) proxy.sendRequest(1, data, reply, option, sendRequestCallback);
``` ```
5. Tear down the connection. 5. Tear down the connection.
Use the API provided by **featureAbility** to tear down the connection when the communication is over. If you use the FA model, call the API provided by **featureAbility** to tear down the connection when the communication is over. If you use the stage model, obtain a service instance through **Context**, and then call the API provided by **featureAbility** to tear down the connection.
```ts ```ts
import rpc from "@ohos.rpc" import rpc from "@ohos.rpc";
import featureAbility from "@ohos.ability.featureAbility" // Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import featureAbility from "@ohos.ability.featureAbility";
function disconnectCallback() { function disconnectCallback() {
console.info("disconnect ability done") console.info("disconnect ability done");
} }
featureAbility.disconnectAbility(connectId, disconnectCallback) // Use this method to disconnect from the ability in the FA model.
// featureAbility.disconnectAbility(connectId, disconnectCallback);
globalThis.context.disconnectServiceExtensionAbility(connectId);
``` ```
...@@ -3,42 +3,25 @@ ...@@ -3,42 +3,25 @@
## Basic Concepts ## Basic Concepts
The inter-process communication (IPC) and remote procedure call (RPC) mechanisms are used to implement cross-process communication. The difference between them lies in that IPC uses the Binder driver to implement cross-process communication within a device, whereas RPC uses the DSoftBus driver to implement cross-process communication across devices. The inter-process communication (IPC) and remote procedure call (RPC) mechanisms are used to implement cross-process communication. The difference between them lies in that IPC uses the Binder driver to implement cross-process communication within a device, whereas RPC uses the DSoftBus driver to implement cross-process communication across devices. The reason why cross-process communication is needed is that each process has its own independent resources and memory space and one process is not allowed to access the resources and memory space of other processes.
The reason why cross-process communication is needed is that each process has its own independent resources and memory space and one process is not allowed to access the resources and memory space of other processes. IPC and RPC usually use the client-server model, where the client (service requester, that is, the process that requests a service) obtains the proxy of the server (service provider, that is, the process that provides the service) and uses the proxy to read and write data to implement data communication across processes. More specifically, the client constructs a proxy object of the server. The proxy object has the same functions as the server. To access a certain API of the server, you only need to access the corresponding API in the proxy object. The proxy object sends the request to the server, and the server processes the received request and returns the processing result to the proxy object through the driver. Then, the proxy object forwards the processing result to the client. The server registers system abilities (SAs) with the system ability manager (SAMgr), which manages the SAs and provides APIs for clients. To communicate with a specific SA, the client must obtain the proxy of the SA from SAMgr. > **NOTE**
> The applications in the stage model cannot use IPC or RPC directly, and must use the following capabilities to implement related service scenarios:
>- [Background services](../application-models/background-services.md): use IPC to implement service invocation across processes.
>- [Multi-device collaboration](../application-models/hop-multi-device-collaboration.md): uses RPC to call remote interfaces and transfer data.
In the following sections, proxy represents the service requester, and stub represents the service provider.
![IPC&RPC communication mechanisms](figures/IPC_RPC_communication.PNG) ## Implementation Principles
IPC and RPC usually use the client-server model, where the client (service requester, that is, the process that requests a service) obtains the proxy of the server (service provider, that is, the process that provides the service) and uses the proxy to read and write data to implement data communication across processes. More specifically, the client constructs a proxy object of the server. The proxy object has the same functions as the server. To access a certain API of the server, you only need to access the corresponding API in the proxy object. The proxy object sends the request to the server, and the server processes the received request and returns the processing result to the proxy object through the driver. Then, the proxy object forwards the processing result to the client. The server registers system abilities (SAs) with the system ability manager (SAMgr), which manages the SAs and provides APIs for clients. To communicate with a specific SA, the client must obtain the proxy of the SA from SAMgr. In the following sections, proxy represents the service requester, and stub represents the service provider.
## Constraints ![IPC & RPC communication mechanisms] (figures/IPC_RPC_communication.PNG)
- During cross-process communication within a single device, the maximum amount of data to be transmitted is about 1 MB. If the amount of data to be transmitted exceeds this limit, use the [anonymous shared memory](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-rpc.md#ashmem8).
- Subscription to death notifications of anonymous stub objects (not registered with SAMgr) is prohibited in RPC.
- During cross-process communication across processes, a proxy object cannot be passed back to the device that hosts the stub object pointed by the proxy object. That is, the proxy object pointing to the stub object of the remote device cannot be passed across processes twice on the local device.
## **Recommendations**
First, compile an API class and define message codes in the API class for both communication parties to identify operations. Unimplemented APIs are allowed in the API class because it must be inherited by both communication parties and its inheritance classes cannot be abstract classes. When inheriting the API class, both communication parties must implement the unimplemented APIs, so as to make sure that the inheritance classes are not abstract classes.
Then, implement the API class specific to the stub, and override the **AsObject** and **OnRemoteRequest** APIs. In addition, compile the proxy to implement the APIs in the API class and override the **AsObject** API. You can also encapsulate an additional API for calling **SendRequest** to send data to the peer.
After the preceding operations are done, register a system ability (SA) with SAMgr. Note that the registration should be completed in the process that hosts the stub. Then, obtain the proxy from SAMgr as needed to implement cross-process communication with the stub.
Related steps are as follows:
- Implementing the API class: Inherit **IRemoteBroker**, define message codes, and declare APIs that are not implemented in the API class. ## Constraints
- Implementing the service provider (stub): Inherit **IRemoteStub** or **RemoteObject**, and override the **AsObject** and **OnRemoteRequest** APIs.
- Implementing the service requester (proxy): Inherit **IRemoteProxy** or **RemoteProxy**, override the **AsObject** API, and encapsulate the required API to call **SendRequest**.
- Registering the SA: Apply for a unique ID for the SA, and register the SA with SAMgr.
- Obtaining the SA: Obtain the proxy based on the SA ID and device ID, and use the proxy to communicate with the remote end.
- A maximum of 1 MB data can be transferred in cross-process communication on a single device. If the amount of data to be transmitted is larger than 1 MB, use [anonymous shared memory](../reference/apis/js-apis-rpc.md#ashmem8).
## Related Modules - Subscription to death notifications of anonymous stub objects (not registered with SAMgr) is prohibited in RPC.
[Distributed Ability Manager Service Framework](https://gitee.com/openharmony/ability_dmsfwk) - During cross-process communication across processes, a proxy object cannot be passed back to the device that hosts the stub object pointed by the proxy object. That is, the proxy object pointing to the stub object of the remote device cannot be passed across processes twice on the local device.
...@@ -2,12 +2,12 @@ ...@@ -2,12 +2,12 @@
Network management functions include: Network management functions include:
- [HTTP data request](http-request.md): initiates a data request through HTTP. - [HTTP data request](http-request.md): Initiates a data request through HTTP.
- [WebSocket connection](websocket-connection.md): establishes a bidirectional connection between the server and client through WebSocket. - [WebSocket connection](websocket-connection.md): Establishes a bidirectional connection between the server and client through WebSocket.
- [Socket connection](socket-connection.md): transmits data through Socket. - [Socket connection](socket-connection.md): Transmits data through Socket.
- [Network sharing](net-sharing.md): shares a device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing, and queries the network sharing state and shared mobile data volume. - [Network sharing](net-sharing.md): Shares a device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing, and queries the network sharing state and shared mobile data volume.
- [Ethernet connection](net-ethernet.md): provides wired network capabilities, which allow you to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network. - [Ethernet connection](net-ethernet.md): Provides wired network capabilities, which allow you to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network.
- [Network connection management](net-connection-manager.md): provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution. - [Network connection management](net-connection-manager.md): Provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution.
- [mDNS management](net-mdns.md): provides Multicast DNS (mDNS) management capabilities, such as adding, removing, discovering, and resolving local services on a LAN. - [mDNS management](net-mdns.md): provides Multicast DNS (mDNS) management capabilities, such as adding, removing, discovering, and resolving local services on a LAN.
## Constraints ## Constraints
......
...@@ -7,7 +7,7 @@ IPC/RPC allows you to subscribe to the state changes of a remote stub object. Wh ...@@ -7,7 +7,7 @@ IPC/RPC allows you to subscribe to the state changes of a remote stub object. Wh
This subscription mechanism is applicable when the local proxy object needs to detect death of the process hosting the remote stub object or network detach of the device hosting the remote stub object. When the proxy detects death of the remote stub object, the proxy can clear local resources. Currently, IPC supports death notification for anonymous objects, but RPC does not. That is, you can only subscribe to death notifications of services that have been registered with SAMgr. This subscription mechanism is applicable when the local proxy object needs to detect death of the process hosting the remote stub object or network detach of the device hosting the remote stub object. When the proxy detects death of the remote stub object, the proxy can clear local resources. Currently, IPC supports death notification for anonymous objects, but RPC does not. That is, you can only subscribe to death notifications of services that have been registered with SAMgr.
## **Using Native APIs** ## **Development Using Native APIs**
| API| Return Value Type| Feature Description| | API| Return Value Type| Feature Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -21,7 +21,6 @@ This subscription mechanism is applicable when the local proxy object needs to d ...@@ -21,7 +21,6 @@ This subscription mechanism is applicable when the local proxy object needs to d
#include "iremote_broker.h" #include "iremote_broker.h"
#include "iremote_stub.h" #include "iremote_stub.h"
// Define message codes. // Define message codes.
enum { enum {
TRANS_ID_PING_ABILITY = 5, TRANS_ID_PING_ABILITY = 5,
...@@ -61,9 +60,6 @@ int TestServiceProxy::TestPingAbility(const std::u16string &dummy){ ...@@ -61,9 +60,6 @@ int TestServiceProxy::TestPingAbility(const std::u16string &dummy){
} }
``` ```
```c++ ```c++
#include "iremote_object.h" #include "iremote_object.h"
...@@ -84,18 +80,54 @@ bool result = object->AddDeathRecipient(deathRecipient); // Add a recipient for ...@@ -84,18 +80,54 @@ bool result = object->AddDeathRecipient(deathRecipient); // Add a recipient for
result = object->RemoveDeathRecipient(deathRecipient); // Remove the recipient for death notifications. result = object->RemoveDeathRecipient(deathRecipient); // Remove the recipient for death notifications.
``` ```
## **Using JS APIs** ## **Development Using JS APIs**
| API | Return Value Type| Feature Description |
| ------------------------ | ---------- | ----------------------------------------------------------------- |
| registerDeathRecipient | void | Adds a recipient for death notifications of the remote object, including death notifications of the remote proxy.|
| unregisterDeathRecipient | void | Removes the recipient for death notifications of the remote object. |
| onRemoteDied | void | Called to perform subsequent operations when a death notification of the remote object is received. |
### Obtaining the Context
| API | Return Value Type| Feature Description | If you use the stage model, you need to obtain the context before connecting to an ability.
| -------------------- | ---------- | ------------------------------------------------------------ |
| addDeathRecippient | boolean | Adds a recipient for death notifications of the remote object, including death notifications of the remote proxy.| ```ts
| removeDeathRecipient | boolean | Removes the recipient for death notifications of the remote object. | import Ability from "@ohos.app.ability.UIAbility";
| onRemoteDied | void | Called to perform subsequent operations when a death notification of the remote object is received.|
export default class MainAbility extends Ability {
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate");
globalThis.context = this.context;
}
onDestroy() {
console.log("[Demo] MainAbility onDestroy");
}
onWindowStageCreate(windowStage) {
// Main window is created, set main page for this ability
console.log("[Demo] MainAbility onWindowStageCreate");
}
onWindowStageDestroy() {
// Main window is destroyed, release UI related resources
console.log("[Demo] MainAbility onWindowStageDestroy");
}
onForeground() {
// Ability has brought to foreground
console.log("[Demo] MainAbility onForeground");
}
onBackground() {
// Ability has back to background
console.log("[Demo] MainAbility onBackground");
}
}
```
### Sample Code ### Sample Code
```ts ```ts
import FA from "@ohos.ability.featureAbility"; // Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy; let proxy;
let connect = { let connect = {
onConnect: function(elementName, remoteProxy) { onConnect: function(elementName, remoteProxy) {
...@@ -113,31 +145,35 @@ let want = { ...@@ -113,31 +145,35 @@ let want = {
"bundleName": "com.ohos.server", "bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility", "abilityName": "com.ohos.server.EntryAbility",
}; };
FA.connectAbility(want, connect); // Use this method to connect to the ability in the FA model.
// FA.connectAbility(want, connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
} }
} }
let deathRecipient = new MyDeathRecipient(); let deathRecipient = new MyDeathRecipient();
proxy.addDeathRecippient(deathRecipient, 0); proxy.registerDeathRecippient(deathRecipient, 0);
proxy.removeDeathRecipient(deathRecipient, 0); proxy.unregisterDeathRecipient(deathRecipient, 0);
``` ```
## Reverse Death Notification (Anonymous Stub) ## Reverse Death Notification (Anonymous Stub)
Forward dead notification is a mechanism that allows the proxy to detect death notifications of the stub. To achieve reverse dead notification, we can leverage the forward dead notification mechanism to allow the stub to detect death notifications of the proxy. Forward dead notification is a mechanism that allows the proxy to detect death notifications of the stub. To achieve reverse dead notification, we can leverage the forward dead notification mechanism to allow the stub to detect death notifications of the proxy. Suppose there are two processes, A (the process hosting the original stub) and B (the process hosting the original proxy). After obtaining the proxy object of process A, process B creates an anonymous stub object (that is, a stub object not registered with SAMgr), which can be called a callback stub. Then, process B calls **SendRequest** to send the callback stub to the original stub of process A. As a result, process A obtains the callback proxy of process B. When process B dies or the device hosting process B detaches from the network, the callback stub dies. The callback proxy detects the death of the callback stub and sends a death notification to the original stub. In this way, reverse death notification is implemented.
Note:
Suppose there are two processes, A (the process hosting the original stub) and B (the process hosting the original proxy). After obtaining the proxy object of process A, process B creates an anonymous stub object (that is, a stub object not registered with SAMgr), which can be called a callback stub. Then, process B calls **SendRequest** to send the callback stub to the original stub of process A. As a result, process A obtains the callback proxy of process B. When process B dies or the device hosting process B detaches from the network, the callback stub dies. The callback proxy detects the death of the callback stub and sends a death notification to the original stub. In this way, reverse death notification is implemented. > Reverse death notification can only be used for cross-process communication within a device.
> NOTE > When an anonymous stub object is not pointed by any proxy, the kernel automatically reclaims the object.
> - Reverse death notification can only be used for cross-process communication within a device.
> - When an anonymous stub object is not pointed by any proxy, the kernel automatically reclaims the object.
### Sample Code ### Sample Code
```c++ ```c++
// Proxy //Proxy
int TestAbilityProxy::TestAnonymousStub() int TestAbilityProxy::TestAnonymousStub()
{ {
MessageOption option; MessageOption option;
...@@ -149,7 +185,7 @@ int TestAbilityProxy::TestAnonymousStub() ...@@ -149,7 +185,7 @@ int TestAbilityProxy::TestAnonymousStub()
return result; return result;
} }
// Stub //Stub
int TestAbilityStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) int TestAbilityStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{ {
......
...@@ -10,7 +10,7 @@ The **Preferences** module provides APIs for processing data in the form of key- ...@@ -10,7 +10,7 @@ The **Preferences** module provides APIs for processing data in the form of key-
User applications call **Preference** through the JS interface to read and write data files. You can load the data of a **Preferences** persistence file to a **Preferences** instance. Each file uniquely corresponds to an instance. The system stores the instance in memory through a static container until the instance is removed from the memory or the file is deleted. The following figure illustrates how **Preference** works. User applications call **Preference** through the JS interface to read and write data files. You can load the data of a **Preferences** persistence file to a **Preferences** instance. Each file uniquely corresponds to an instance. The system stores the instance in memory through a static container until the instance is removed from the memory or the file is deleted. The following figure illustrates how **Preference** works.
The preference persistent file of an application is stored in the application sandbox. You can use **context** to obtain the file path. For details, see [Obtaining the Application Development Path](../application-models/application-context-stage.md#obtaining-the-application-development-path). The preference persistent file of an application is stored in the application sandbox. You can use **context** to obtain the file path. For details, see [Obtaining Application File Paths](../application-models/application-context-stage.md#obtaining-application-file-paths).
**Figure 1** Preferences working mechanism **Figure 1** Preferences working mechanism
...@@ -21,7 +21,7 @@ The preference persistent file of an application is stored in the application sa ...@@ -21,7 +21,7 @@ The preference persistent file of an application is stored in the application sa
- The key in a KV pair must be a string and cannot be empty or exceed 80 bytes. - The key in a KV pair must be a string and cannot be empty or exceed 80 bytes.
- If the value is of the string type, it can be empty or a string not longer than 8192 bytes. - If the value is of the string type, use the UTF-8 encoding format. It can be empty or a string not longer than 8192 bytes.
- The memory usage increases with the amount of **Preferences** data. The maximum number of data records recommended is 10,000. Otherwise, high memory overheads will be caused. - The memory usage increases with the amount of **Preferences** data. The maximum number of data records recommended is 10,000. Otherwise, high memory overheads will be caused.
...@@ -30,23 +30,23 @@ The preference persistent file of an application is stored in the application sa ...@@ -30,23 +30,23 @@ The preference persistent file of an application is stored in the application sa
The following table lists the APIs used for preferences data persistence. Most of the APIs are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [User Preferences](../reference/apis/js-apis-data-preferences.md). The following table lists the APIs used for preferences data persistence. Most of the APIs are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [User Preferences](../reference/apis/js-apis-data-preferences.md).
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
| getPreferences(context: Context, name: string, callback: AsyncCallback&lt;Preferences&gt;): void | Obtain a **Preferences** instance.| | getPreferences(context: Context, name: string, callback: AsyncCallback&lt;Preferences&gt;): void | Obtain a **Preferences** instance.|
| put(key: string, value: ValueType, callback: AsyncCallback&lt;void&gt;): void | Writes data to the Preferences instance. You can use **flush()** to persist the **Preferences** instance data.| | put(key: string, value: ValueType, callback: AsyncCallback&lt;void&gt;): void | Writes data to the Preferences instance. You can use **flush()** to persist the **Preferences** instance data.|
| has(key: string, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether the **Preferences** instance contains a KV pair with the given key. The key cannot be empty.| | has(key: string, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether the **Preferences** instance contains a KV pair with the given key. The key cannot be empty.|
| get(key: string, defValue: ValueType, callback: AsyncCallback&lt;ValueType&gt;): void | Obtains the value of the specified key. If the value is null or not of the default value type, **defValue** is returned.| | get(key: string, defValue: ValueType, callback: AsyncCallback&lt;ValueType&gt;): void | Obtains the value of the specified key. If the value is null or not of the default value type, **defValue** is returned.|
| delete(key: string, callback: AsyncCallback&lt;void&gt;): void | Deletes the KV pair with the given key from the **Preferences** instance.| | delete(key: string, callback: AsyncCallback&lt;void&gt;): void | Deletes the KV pair with the given key from the **Preferences** instance.|
| flush(callback: AsyncCallback&lt;void&gt;): void | Flushes the data of this **Preferences** instance to a file for data persistence.| | flush(callback: AsyncCallback&lt;void&gt;): void | Flushes the data of this **Preferences** instance to a file for data persistence.|
| on(type: 'change', callback: Callback&lt;{ key : string }&gt;): void | Subscribes to data changes of the specified key. When the value of the specified key is changed and saved by **flush()**, a callback will be invoked to return the new data.| | on(type: 'change', callback: Callback&lt;{ key : string }&gt;): void | Subscribes to data changes of the specified key. When the value of the specified key is changed and saved by **flush()**, a callback will be invoked to return the new data.|
| off(type: 'change', callback?: Callback&lt;{ key : string }&gt;): void | Unsubscribes from data changes.| | off(type: 'change', callback?: Callback&lt;{ key : string }&gt;): void | Unsubscribes from data changes.|
| deletePreferences(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void | Deletes a **Preferences** instance from memory. If the **Preferences** instance has a persistent file, this API also deletes the persistent file.| | deletePreferences(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void | Deletes a **Preferences** instance from memory. If the **Preferences** instance has a persistent file, this API also deletes the persistent file.|
## How to Develop ## How to Develop
1. Import the **@ohos.data.preferences** module. 1. Import the **@ohos.data.preferences** module.
```js ```js
import dataPreferences from '@ohos.data.preferences'; import dataPreferences from '@ohos.data.preferences';
``` ```
...@@ -55,7 +55,7 @@ The following table lists the APIs used for preferences data persistence. Most o ...@@ -55,7 +55,7 @@ The following table lists the APIs used for preferences data persistence. Most o
Stage model: Stage model:
```js ```js
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
...@@ -79,7 +79,7 @@ The following table lists the APIs used for preferences data persistence. Most o ...@@ -79,7 +79,7 @@ The following table lists the APIs used for preferences data persistence. Most o
FA model: FA model:
```js ```js
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
...@@ -110,7 +110,7 @@ The following table lists the APIs used for preferences data persistence. Most o ...@@ -110,7 +110,7 @@ The following table lists the APIs used for preferences data persistence. Most o
Example: Example:
```js ```js
try { try {
preferences.has('startup', function (err, val) { preferences.has('startup', function (err, val) {
...@@ -163,7 +163,7 @@ The following table lists the APIs used for preferences data persistence. Most o ...@@ -163,7 +163,7 @@ The following table lists the APIs used for preferences data persistence. Most o
Use delete() to delete a KV pair.<br>Example: Use delete() to delete a KV pair.<br>Example:
```js ```js
try { try {
preferences.delete('startup', (err) => { preferences.delete('startup', (err) => {
...@@ -234,7 +234,7 @@ The following table lists the APIs used for preferences data persistence. Most o ...@@ -234,7 +234,7 @@ The following table lists the APIs used for preferences data persistence. Most o
Example: Example:
```js ```js
try { try {
dataPreferences.deletePreferences(this.context, 'mystore', (err, val) => { dataPreferences.deletePreferences(this.context, 'mystore', (err, val) => {
...@@ -247,4 +247,5 @@ The following table lists the APIs used for preferences data persistence. Most o ...@@ -247,4 +247,5 @@ The following table lists the APIs used for preferences data persistence. Most o
} catch (err) { } catch (err) {
console.error(`Failed to delete preferences. Code:${err.code}, message:${err.message}`); console.error(`Failed to delete preferences. Code:${err.code}, message:${err.message}`);
} }
``` ```
\ No newline at end of file
...@@ -3,8 +3,13 @@ ...@@ -3,8 +3,13 @@
- [Full SDK Compilation](full-sdk-compile-guide.md) - [Full SDK Compilation](full-sdk-compile-guide.md)
- [Switching to Full SDK](full-sdk-switch-guide.md) - [Switching to Full SDK](full-sdk-switch-guide.md)
- [Application Model Development](faqs-ability.md) - [Application Model Development](faqs-ability.md)
- ArkUI Framework Development (ArkTS) - ArkUI Development (ArkTS)
- [ArkUI Development (ArkTS Syntax)](faqs-arkui-arkts.md) - [ArkTS Syntax Usage](faqs-arkui-arkts.md)
- [ArkUI Component Development (ArkTS)](faqs-arkui-component.md)
- [ArkUI Layout Development (ArkTS)](faqs-arkui-layout.md)
- [ArkUI Routing/Navigation Development (ArkTS)](faqs-arkui-route-nav.md)
- [ArkUI Animation/Interaction Event Development (ArkTS)](faqs-arkui-animation-interactive-event.md)
- [ArkUI Development (JS)](faqs-arkui-js.md)
- [Web Development](faqs-arkui-web.md) - [Web Development](faqs-arkui-web.md)
- [Bundle Management Development](faqs-bundle-management.md) - [Bundle Management Development](faqs-bundle-management.md)
- [Resource Manager Development](faqs-globalization.md) - [Resource Manager Development](faqs-globalization.md)
...@@ -22,4 +27,5 @@ ...@@ -22,4 +27,5 @@
- [Startup Development](faqs-startup.md) - [Startup Development](faqs-startup.md)
- [Distributed Device Development](faqs-distributed-device-profile.md) - [Distributed Device Development](faqs-distributed-device-profile.md)
- [SDK Usage](faqs-sdk.md) - [SDK Usage](faqs-sdk.md)
- [Compiler and Runtime](faqs-compiler-runtime.md)
- [Usage of Third- and Fourth-Party Libraries](faqs-third-fourth-party-library.md) - [Usage of Third- and Fourth-Party Libraries](faqs-third-fourth-party-library.md)
\ No newline at end of file
# Ability Access Control Development # Application Access Control Development
## Can the app listen for the permission change after its permission is modified in Settings? ## Can the app listen for the permission change after its permission is modified in Settings?
Applicable to: OpenHarmony 3.1 Beta 5 (API version 9) Applicable to: OpenHarmony 3.1 Beta 5 (API version 9)
Third-party apps cannot listen for the permission change. Third-party apps cannot listen for the permission change.
## Why is there no pop-up window displayed when an app applies for the **ohos.permission.LOCATION** permission?
Applicable to: OpenHarmony 3.2 Release (API version 9)
Applications developed using SDKs earlier than API version 9 can directly apply for the **ohos.permission.LOCATION** permission.
For the applications developed using the SDK of API version 9 or later, you need to apply for **ohos.permission.APPROXIMATELY_LOCATION** and then **ohos.permission.LOCATION**.
**References**
[Application Permission List](../security/permission-list.md#ohospermissionlocation)
## What can I do to prevent the application from crashing when the application is started again after the user denies the permission requested?
Applicable to: OpenHarmony SDK 3.2 Beta5
**Possible Causes**
- If the permission required by a service is rejected by the user, the system directly returns the result and will no longer display a dialog box to request the permission.
- If related judgment is not performed after the permission is requested, the application will be rejected due to lack of the corresponding permission when accessing the target object under permission control, and terminated unexpectedly.
**Solution**
1. Before allowing an application to call an API protected by certain permission, verify whether the application has the permission. If the application has the permission, the application can call the API. Otherwise, a dialog box is dipslayed to ask user authorization.
2. If the user rejects to grant the permission, ensure that other functions irrelevant to this permission are not affected.
3. When this service is triggered again by the user or to implement a service function, on-screen message shall be provided to guide the user to grant the permission in **Settings**.
**References**
[Access Control (Permission) Overview](../security/accesstoken-overview.md)
## What are the differences between **extensionAbilities** and **requestPermissions** in the **module.json5** file?
Applicable to: OpenHarmony SDK 3.2 Beta5
- **requestPermissions**: specifies all the permissions required by an application for running. The permissions take effect only after being configured (declared) in the **module.json5** file.
- **extensionAbilitie.permissions**: specifies the permissions customized by the ExtensionAbility component. These permissions are required when an application needs to access the ExtensionAbility component. **extensionAbilitie.permissions** is used for permission verification only.
**References**
[module.json5 Configuration File](../quick-start/module-configuration-file.md)
# ArkUI Animation/Interaction Event Development (ArkTS)
## What should I do if the onBlur and onFocus callbacks cannot be triggered?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Symptom**
The **onBlur** and **onFocus** callbacks of the focus event cannot be triggered.
**Solution**
Check the trigger device. By default, the focus event (and the **onBlur** and **onFocus** callbacks) can be triggered only by the Tab button and arrow buttons on the connected keyboard. To enable the focus event to be triggered by a touch, add the **focusOnTouch** attribute for the target component.
**Reference**
[Focus Control](../reference/arkui-ts/ts-universal-attributes-focus.md)
## How do I disable the scroll event of a \<Grid> nested in the \<Scroll>?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
Implement nested scrolling of the containers, by using the **onScrollFrameBegin** event and the **scrollBy** method.
**Reference**
[Scroll](../reference/arkui-ts/ts-container-scroll.md#example-2)
## How do I enable a component to rotate continuously?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
You can use [attribute animation](../reference/arkui-ts/ts-animatorproperty.md) to that effect.
## How do I scroll a list with the keyboard?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
- Add **focusable\(true\)** to the list item to enable it to obtain focus.
- Nest a focusable component, for example, **\<Button>**, at the outer layer of each item.
## Why is the click event not triggered for the focused component upon the press of the Enter key after keyboard navigation?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
By default, the built-in click event of the component and the custom **onClick** click event are bound to the space bar instead of the Enter key.
## How do I block event bubbling when a button is nested in multi-layer components?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
You can bind the button to the **stopPropagation** parameter.
## How do I disable the transition effect between pages when the router or navigator is used to switch between pages?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
1. Define the **pageTransition** method for the current and target pages, by following instructions in [Example](../reference/arkui-ts/ts-page-transition-animation.md#example).
2. Set the **duration** parameter of both **PageTransitionEnter** and **PageTransitionExit** to **0**.
## How do I fix misidentification of the pan gesture where container nesting is involved?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
The pan gesture requires a minimum 5 vp movement distance of a finger on the screen. You can set the **distance** parameter in **PanGesture** to **1** so that the pan gesture can be more easily recognized.
**Reference**
[PanGesture](../reference/arkui-ts/ts-basic-gestures-pangesture.md)
## Can I use the fontFamily attribute to set different fonts for OpenHarmony applications?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
No. For applications developed based on OpenHarmony, only the default font, HarmonyOS Sans, is supported.
## How do I implement a text input box that shows a soft keyboard when touched and hides the soft keyboard when a button is touched?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
Use **focusControl** for the **\<TextInput>** component to control its focus. The **\<TextInput>** component shows a soft keyboard when it gains focus and hides the soft keyboard when it loses focus.
**Example**
```
build() {
Column() {
TextInput()
Button(`hide`)
.key('button')
.onClick(()=>{
focusControl.requestFocus('button')
})
}
}
```
## How do I implement a button that only responds to the bound onClick event, but not the onTouch event bound to the button's parent component?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
Bind **onTouch** to the **\<Button>** component and use **stopPropagation\(\)** in **onTouch** to prevent **onTouch** from bubbling up to the parent component.
**Example**
```
build() {
Row() {
Button ("Click Me")
.width(100)
.width(100)
.backgroundColor('#f00')
.onClick(()=>{
console.log("Button onClick")
})
.onTouch((e) => {
console.log("Button onTouch")
e.stopPropagation()
})
}
.onTouch(() => {
console.log("Row onTouch")
})
}
```
## Why is the menu bound to a component not displayed by a right-click on the component?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Solution**
Currently, the menu is displayed when the bound component is clicked or long pressed.
## How do I shield the default keyboard popup behavior of the \<TextInput> component?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
Set the **focusable** attribute of the **\<TextInput>** component to **false**. In this way, the component is not focusable and therefore will not bring up the keyboard.
## How do I implement the slide up and slide down effect for page transition?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Solution**
You can use the **pageTransition** API to implement the page transition effect. Specifically, set the **slide** attribute in **PageTransitionEnter** and **PageTransitionExit** to **SlideEffect.Bottom**. In this way, the page slides in and out from the bottom.
**Example**
```
// Index.ets
@Entry
@Component
struct PageTransition1 {
build() {
Stack({alignContent: Alignment.Bottom}) {
Navigator({ target: 'pages/Page1'}) {
Image($r('app.media.ic_banner01')).width('100%').height(200) // Save the image in the media folder.
}
}.height('100%').width('100%')
}
pageTransition() {
PageTransitionEnter({ duration: 500, curve: Curve.Linear }).slide(SlideEffect.Bottom)
PageTransitionExit({ duration: 500, curve: Curve.Ease }).slide(SlideEffect.Bottom)
}
}
```
```
// Page1.ets
@Entry
@Component
struct PageTransition2 {
build() {
Stack({alignContent: Alignment.Bottom}) {
Navigator({ target: 'pages/Index'}) {
Image($r('app.media.ic_banner02')).width('100%').height(200) // Save the image in the media folder.
}
}.height('100%').width('100%')
}
pageTransition() {
PageTransitionEnter({ duration: 500, curve: Curve.Linear }).slide(SlideEffect.Bottom)
PageTransitionExit({ duration: 500, curve: Curve.Ease }).slide(SlideEffect.Bottom)
}
}
```
**Reference**
[Page Transition Animation](../ui/arkts-page-transition-animation.md)
## How do I configure custom components to slide in and out from the bottom?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Symptom**
Custom components A and B need to deliver the following effects: When custom component A, displayed at the bottom of the screen by default, is touched, it is hidden, and custom component B slides in from the bottom. When custom component B is touched, it is hidden, and custom component A slides in from the bottom.
**Solution**
You can use the **transition** attribute to create component transition animations. Set the **type** parameter to specify the component transition type, which can be component addition, component deletion, or both. Set the **translate** parameter to specify the translation of the component during transition. **NOTE**<br>The **transition** attribute must work with **animateTo**. The animation duration, curve, and delay follow the settings in **animateTo**.
**Example**
```
@Entry
@Component
struct ComponentTransition {
@State flag: boolean = true;
build() {
Stack({alignContent: Alignment.Bottom}) {
if (this.flag) {
ComponentChild1({ flag: $flag })
.transition({ type: TransitionType.Insert,translate: { x: 0, y: 200 } })
}
if (!this.flag) {
ComponentChild2({ flag: $flag })
.transition({ type: TransitionType.Insert, translate: { x: 0, y: 200 } })
}
}.height('100%').width('100%')
}
}
@Component
struct ComponentChild1 {
@Link flag: boolean
build() {
Column() {
Image($r('app.media.ic_banner01'))
.width('100%')
.height(200)
.onClick(() => {
animateTo({ duration: 1000 }, () => {
this.flag = !this.flag;
})
})
}
}
}
@Component
struct ComponentChild2 {
@Link flag: boolean
build() {
Column() {
Image($r('app.media.ic_banner02'))
.width('100%')
.height(200)
.onClick(() => {
animateTo({ duration: 1000 }, () => {
this.flag = !this.flag;
})
})
}
}
}
```
**Reference**
[Transition Animation Within the Component](../ui/arkts-transition-animation-within-component.md)
# ArkUI Development (ArkTS Syntax) # ArkTS Syntax Usage
## How do I dynamically create components using code in ArkUI? ## How do I dynamically create components using code in ArkUI?
...@@ -522,7 +522,7 @@ Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) ...@@ -522,7 +522,7 @@ Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Reference** **Reference**
[Resource Categories and Access](../quick-start/resource-categories-and-access.md) and [@ohos.resourceManager (Resource Manager)](../reference/apis/js-apis-resource-manager.md#getstring) [Resource Categories and Access](../quick-start/resource-categories-and-access.md) and [@ohos.resourceManager (Resource Manager)](../reference/apis/js-apis-resource-manager.md)
## How do I convert the XML format to the JSON format? ## How do I convert the XML format to the JSON format?
......
# ArkUI Development (JS)
## Why can't array variables be used to control component attributes?
Applicable to: OpenHarmony (DevEco Studio 3.0.0.993, API version 8)
Currently, the web-like development paradigm does not listen for the modification of elements in an array. Therefore, the page refresh can be triggered only when the array object is modified, but not when an element in the array is modified. In the following example, the **test1\(\)** statement, which assigns values to the entire array, will disable the related **\<Button>** component; in contrast, the **test2\(\)** statement, which assigns a value to an element in the array, will not disable the **\<Button>** component. In addition to **test1\(\)**, you can also use the method of modifying the array, for example, **splice\(\)**, to trigger the page refresh.
```
test1() {this.isDisabled = [true, true, true, true, true]; // This statement disables the <Button> component.
test2() {this.isDisabled[0] = true; // This statement does not work for the <Button> component.
```
## Does the \<input> component support center alignment?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9, FA model)
**Symptom**
The **text-align** style does not work for the **\<input>** component.
**Solution**
The **text-align** style works for the **\<text>** component, but not for the **\<input>** component.
**Reference**
[input](../reference/arkui-js/js-components-basic-input.md), [text](../reference/arkui-js/js-components-basic-text.md)
## How do I determine whether a value exists in a JS object?
Applicable to: OpenHarmony 3.2 Release (API version 9)
**Solution**
Use **Object.values\(*object name*\).indexOf\(*value to be checked*\)**. If **-1** is returned, the corresponding value is not included. Otherwise, the corresponding value is included.
# ArkUI Layout Development (ArkTS)
## What should I do if the height settings in position do not take effect?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
When **position** is set for a container component, it is taken out of normal flow and works independently from the outer container. In this case, the height does not take effect. You can replace the outer container with a stack to solve this issue.
## How do I implement horizontal scrolling on a \<Grid> component?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
Set **rowsTemplate** (the number of rows) for the **\<Grid>** component and do not set **columnsTemplate** (the number of columns). In this way, the **\<Grid>** component scrolls horizontally when its content does not fit within its width.
## What should I do if the \<List> component cannot be dragged to the bottom when it is used with another component and does not have the size specified?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
Add the **layoutWeight** attribute for the **\<List>** component so that it takes up the remaining height (or width, depending on the scrolling direction) adapatively.
By default, the **\<List>** component, as a scrollable container, takes up the entire screen height. When it is used with any component whose height is fixed, you need to explicitly add the **layoutWeight** attribute for the **\<List>** component so that it takes up the remaining height instead of the entire screen height.
## Can tab switching be disabled for the \<Tabs> component?
Applicable to: OpenHarmony 3.2 Release (API version 9)
No. This feature is not supported.
## How do I intercept the onBackPress event so that it does not trigger page return?
Applicable to: OpenHarmony 3.2 Release (API version 9)
If **true** is returned in **onBackPress**, the page executes its own return logic instead of the default return logic.
**Reference**
[onBackPress](../reference/arkui-ts/ts-custom-component-lifecycle.md#onbackpress).
## How do I implement a sticky header for a list item group in the \<List> component?
Applicable to: OpenHarmony 3.2 Release (API version 9)
You can use the **sticky** attribute of the **\<List>** component together with the **\<ListItemGroup>** component. Specifically, set the **sticky** attribute of the **\<List>** component to **StickyStyle.Header** and set the **header** parameter of the corresponding **\<ListItemGroup>** component.
**Reference**
[Adding a Sticky Header](../ui/arkts-layout-development-create-list.md#adding-a-sticky-header)
\ No newline at end of file
# ArkUI Routing/Navigation Development (ArkTS)
## Why can't class objects be transferred through params in the router API?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9, stage model)
Only attributes in an object can be transferred, and methods in the object cannot.
## How do I use router to implement page redirection in the stage model?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9, stage model)
1. To implement page redirection through **router**, add all redirected-to pages to the **pages** list in the **main\_pages.json** file.
2. Page routing APIs in **router** can be invoked only after page rendering is complete. Do not call these APIs in **onInit** or **onReady** when the page is still in the rendering phase.
**Reference**
[@ohos.router (Page Routing)](../reference/apis/js-apis-router.md)
## Will a page pushed into the stack through router.push be reclaimed?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9, stage model)
After being pushed to the stack through **router.push**, a page can be reclaimed only when it is popped from the stack through **router.back**.
**Reference**
[router.getParams](../reference/apis/js-apis-router.md#routergetparams)
\ No newline at end of file
# Compiler and Runtime
## What if a crash occurs when I obtain a string in JSON format from rawfile, convert the string into an object, and call the instance method?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Symptom**
"jscrash happened in xxxxxxxxx" is displayed, and the crash log contains "Error message: Unexpected Object in JSON".
**Solution**
The prototype of the object obtained by parsing the string in JSON format is object. The prototype chain does not contain the instance method. Therefore, the object cannot be called.
To solve this problem, use either of the following methods:
1. Add the prototype to the parsed object.
2. Change the instance method to a static method and call it through the class name.
...@@ -25,8 +25,6 @@ An error is reported when the **TRUNCATE TABLE** statement is used to clear tabl ...@@ -25,8 +25,6 @@ An error is reported when the **TRUNCATE TABLE** statement is used to clear tabl
The RDB store uses SQLite and does not support the **TRUNCATE TABLE** statement. To clear a table in an RDB store, use the **DELETE** statement, for example, **DELETE FROM sqlite\_sequence WHERE name = 'table\_name'**. The RDB store uses SQLite and does not support the **TRUNCATE TABLE** statement. To clear a table in an RDB store, use the **DELETE** statement, for example, **DELETE FROM sqlite\_sequence WHERE name = 'table\_name'**.
## What data types does an RDB store support? ## What data types does an RDB store support?
Applicable to: OpenHarmony SDK 3.0 or later, API version 9 stage model Applicable to: OpenHarmony SDK 3.0 or later, API version 9 stage model
...@@ -35,13 +33,43 @@ Applicable to: OpenHarmony SDK 3.0 or later, API version 9 stage model ...@@ -35,13 +33,43 @@ Applicable to: OpenHarmony SDK 3.0 or later, API version 9 stage model
An RDB store supports data of the number, string, and Boolean types. The number type supports data of the Double, Long, Float, Int, or Int64 type, with a maximum precision of 17 decimal digits. An RDB store supports data of the number, string, and Boolean types. The number type supports data of the Double, Long, Float, Int, or Int64 type, with a maximum precision of 17 decimal digits.
## How do I save pixel map data to a database? ## How do I persist application data?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Symptom** **Solution**
You can use the **PersistentStorage** class to implement application data persistence. You can link the persistent data with specific tags to **AppStorage**, and invoke **AppStorage** APIs to access the persistent data. Persistent data is stored in a local XML file in **/data/app/el2/100/base/<bundleName\>/haps/<hapName\>/files/persistent\_storage**.
Example:
```
AppStorage.Link('varA')
PersistentStorage.PersistProp("varA", "111");
@Entry
@Component
struct Index {
@StorageLink('varA') varA: string = ''
build() {
Column() {
Text('varA: ' + this.varA).fontSize(20)
Button('Set').width(100).height(100).onClick(() => {
this.varA += '333'
})
}
.width('100%')
.height('100%')
}
}
```
**Reference**
[Persistent Data Management\(OpenHarmony\)](../quick-start/arkts-persiststorage.md)
## How do I save pixel map data to a database?
Pixel map data fails to be stored. Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution** **Solution**
...@@ -55,6 +83,10 @@ Convert the pixel map data into an **ArrayBuffer** and save the **ArrayBuffer** ...@@ -55,6 +83,10 @@ Convert the pixel map data into an **ArrayBuffer** and save the **ArrayBuffer**
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Symptom**
Problem of obtaining RDB store files.
**Solution** **Solution**
The RDB store files are stored in **/data/app/el2/100/database/*Bundle_name*/entry/rdb/**. You can use the hdc command to copy the file from the directory and use a SQLite tool to open the file. The RDB store files are stored in **/data/app/el2/100/database/*Bundle_name*/entry/rdb/**. You can use the hdc command to copy the file from the directory and use a SQLite tool to open the file.
...@@ -69,6 +101,10 @@ Example: ...@@ -69,6 +101,10 @@ Example:
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Symptom**
I do not know whether I need to design a lock mechanism for databases in development.
**Solution** **Solution**
The distributed data service (DDS), RDB store, and preferences provided OpenHarmony have a lock mechanism. You do not need to bother with the lock mechanism during the development. The distributed data service (DDS), RDB store, and preferences provided OpenHarmony have a lock mechanism. You do not need to bother with the lock mechanism during the development.
...@@ -97,5 +133,26 @@ In API version 8, large text files cannot be saved in RDB stores. ...@@ -97,5 +133,26 @@ In API version 8, large text files cannot be saved in RDB stores.
**Solution** **Solution**
In versions earlier than API version 9, the maximum length of a text file is 1024 bytes. If the text file exceeds 1024 bytes, it cannot be saved. In versions earlier than API version 9, the maximum length of a text file is 1024 bytes. If the text file exceeds 1024 bytes, it cannot be saved.
The limit on the text file size has been removed since API9 version. The limit on the text file size has been removed since API9 version.
## What if **undefined** is returned by **Preferences.get** after **Preferences.put()** is successfully called?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Symptom**
Data is successfully saved using **preferences**, but fails to be obtained.
**Solution**
1. After **put()** is performed, use **flush()** to persist the data.
2. Wait until the **flush()** asynchronous operation is complete, and call **get()**.
## Can I specify the in-memory database mode when using an RDB store?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
RDB stores use SQLite. The default in-memory database mode is file, which cannot be modified.
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
## How do I obtain the path of system screenshots? ## How do I obtain the path of system screenshots?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Solution** **Solution**
...@@ -10,7 +10,7 @@ The screenshots are stored in **/storage/media/100/local/files/Pictures/Screensh ...@@ -10,7 +10,7 @@ The screenshots are stored in **/storage/media/100/local/files/Pictures/Screensh
## How do I change the permissions on a directory to read/write on a device? ## How do I change the permissions on a directory to read/write on a device?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Symptom** **Symptom**
...@@ -19,3 +19,94 @@ When the hdc command is used to send a file to a device, "permission denied" is ...@@ -19,3 +19,94 @@ When the hdc command is used to send a file to a device, "permission denied" is
**Solution** **Solution**
Run the **hdc shell mount -o remount,rw /** command to grant the read/write permissions. Run the **hdc shell mount -o remount,rw /** command to grant the read/write permissions.
## What is the best way to create a file if the file to open does not exist?
Applicable to: OpenHarmony 3.2 (API version 9)
**Solution**
Use **fs.open(path: string, mode?: number)** with **mode** set to **fs.OpenMode.CREATE**. **fs.OpenMode.CREATE** creates a file if it does not exist.
## How do I solve the problem of garbled Chinese characters in a file?
Applicable to: OpenHarmony 3.2 (API version 9)
**Solution**
After the buffer data of the file content is read, use **TextDecoder** of @ohos.util to decode the file content.
```
let filePath = getContext(this).filesDir + "/test0.txt";
let stream = fs.createStreamSync(filePath, "r+");
let buffer = new ArrayBuffer(4096)
let readOut = stream.readSync(buffer);
let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM: true })
let readString = textDecoder.decodeWithStream(new Uint8Array(buffer), { stream: false });
console.log ("File content read: "+ readString);
```
## Why is an error reported when **fs.copyFile** is used to copy a **datashare://** file opened by **fs.open()**?
Applicable to: OpenHarmony 3.2 (API version 9)
**Solution**
**fs.copyFile** does not support URIs. You can use **fs.open()** to obtain the URI, obtain the file descriptor (FD) based on the URI, and then use **fs.copyFile** to copy the file based on the FD.
```
let file = fs.openSync("datashare://...")
fs.copyFile(file.fd, 'dstPath', 0).then(() => {
console.info('copyFile success')
}).catch((err) => {
console.info("copy file failed with error message: " + err.message + ", error code: " + err.code);
})
```
## How do I modify the specified content of a JSON file in the sandbox?
Applicable to: OpenHarmony 3.2 (API version 9)
**Solution**
Perform the following steps:
1. Use **fs.openSyn** to obtain the FD of the JSON file.
```
import fs from '@ohos.file.fs';
let sanFile = fs.open(basePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let fd = sanFile.fd;
```
2. Use **fs.readSync** to read the file content.
```
let content = fs.readSync(basePath);
```
3. Modify the file content.
```
obj.name = 'new name';
```
4. Write the JSON file again.
```
fs.writeSync(file.fd, JSON.stringify(obj));
```
For more information, see [@ohos.file.fs](../reference/apis/js-apis-file-fs.md).
## What is the actual path corresponding to the file path obtained through the FileAccess module?
Applicable to: OpenHarmony 3.2 (API version 9, stage model)
**Solution**
The files are stored in the **/storage/media/100/local/files** directory. The specific file path varies with the file type and source. To obtain the actual file path, run the following command in the **/storage/media/100/local/files** directory:
**-name \[filename\]**
For more information, see [Uploading and Downloading an Application File](../file-management/app-file-upload-download.md).
...@@ -10,6 +10,10 @@ ...@@ -10,6 +10,10 @@
- [Obtaining Application and File System Space Statistics](app-fs-space-statistics.md) - [Obtaining Application and File System Space Statistics](app-fs-space-statistics.md)
- [Sending Files to an Application Sandbox](send-file-to-app-sandbox.md) - [Sending Files to an Application Sandbox](send-file-to-app-sandbox.md)
- [Sharing an Application File](share-app-file.md) - [Sharing an Application File](share-app-file.md)
- Application Data Backup and Restoration
- [Application Data Backup and Restoration Overview](app-file-backup-overview.md)
- [Backing Up and Restoring Application Access Data](app-file-backup-extension.md)
- [Backing Up and Restoring Application-triggered Data (for System Applications Only)](app-file-backup.md)
- User File - User File
- [User File Overview](user-file-overview.md) - [User File Overview](user-file-overview.md)
- Selecting and Saving User Files (FilePicker) - Selecting and Saving User Files (FilePicker)
......
# Backing Up and Restoring Application Access Data
You can use BackupExtensionAbility to implement backup and restoration of application access data.
BackupExtensionAbility is a class derived from the [ExtensionAbility](../application-models/extensionability-overview.md) component in [Stage Model](../../application-dev/application-models/stage-model-development-overview.md). You can modify the configuration file to customize the behavior of the backup and restoration framework, including whether backup and restoration are allowed and which files are backed up.
## Constraints
- The paths of all files and directories to be backed up cannot exceed 4095 bytes. Otherwise, undefined behavior may occur.
- If a directory needs to be backed up, the application process must have the permission to read the directory and all its subdirectories (**r** in DAC). Otherwise, the backup fails.
- If a file needs to be backed up, the application process must have the permission to search for its grandparent directory of the file (**x** in DAC). Otherwise, the backup fails.
## How to Develop
1. Add the **extensionAbilities** configuration in the application's **module.json5** file.
Add **extensionAbilities**, set **type** to **backup**, and add **name: ohos.extension.backup** to **[metadata]**(../../application-dev/reference/apis/js-apis-bundleManager-metadata.md).
BackupExtensionAbility configuration example:
```json
{
"extensionAbilities": [
{
"description": "$string:ServiceExtAbility",
"icon": "$media:icon",
"name": "BackupExtensionAbility",
"type": "backup",
"visible": true,
"metadata": [
{
"name": "ohos.extension.backup",
"resource": "$profile:backup_config"
}
],
"srcEntrance": "",
}
]
}
```
2. Add a metadata resource configuration file.
The metadata resource configuration file defines the files to be transferred during backup and restoration. The file name must be the same as the value of **resource** under **metadata** in the **module.json5** file. This file is stored in the **Profile** folder.
Metadata resource configuration file example:
```json
{
"allowToBackupRestore": true,
"includes": [
"/data/storage/el2/base/files/users/*/*.json"
],
"excludes": [
"/data/storage/el2/base/files/users/*/hidden.json"
],
}
```
### Description of the Metadata Resource Configuration File
| Name | Type | Mandatory| Description |
| -------------------- | ---------- | ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| allowToBackupRestore | Boolean | Yes | Whether to allow backup and restoration. The default value is **false**. |
| includes | String array| No | Files and directories to be backed up in the application sandbox.<br>Each item in the array is a pattern string, which can contain shell-style wildcards such as *****, **?**, and **[**.<br>The pattern string that does not start with a slash (/) indicates a relative path relative to the root path.<br>If **includes** is configured, the backup and restoration framework uses the pattern strings configured. Otherwise, the backup and restoration framework uses the **includes** default value (see the following code segment).|
| excludes | String array| No | Exception items in **includes** that do not need to be backed up. The value is in the same format as **includes**.<br>If **excludes** is configured, the backup and restoration framework uses the pattern strings configured. Otherwise, the backup and restoration framework uses an empty array as the default value. |
**includes** default value:
```json
{
"includes": [
"data/storage/el2/database/",
"data/storage/el2/base/files/",
"data/storage/el2/base/preferences/",
"data/storage/el2/base/haps/*/database/",
"data/storage/el2/base/haps/*/base/files/",
"data/storage/el2/base/haps/*/base/preferences/",
]
}
```
# Application Data Backup and Restoration Overview
Application data, such as the configuration and service data, is generated when an application is used. To ensure that user data will not be lost due to operations, such as application updates and hopping, applications need to access data backup and restoration.
Before development, you need to understand the ExtensionAbility component. For details, see [ExtensionAbility Component Overview](../application-models/extensionability-overview.md).
BackupExtensionAbility is a class derived from ExtensionAbility in the stage model. It provides the capabilities of backing up and restoring application data. It is an extended component without the UI. It runs when a backup or restoration task starts and exits when the task is complete.
The implementation includes the following:
- [Backup and restoration of application access data](app-file-backup-extension.md): All applications can access data backup and restoration. After accessed, the application can modify the configuration file to customize the behavior of the backup and restoration framework, including whether to allow backup and restoration and specifying the data to be backed up.
Applications can perform backup and restoration configurations, but not trigger data backup and restoration.
- [Backup and restoration of application-triggered data](app-file-backup.md): Only system applications can trigger data backup and restoration. After data backup or restoration is triggered, the backup and restoration framework checks whether each application has accessed data backup and restoration. If yes, the backup and restore framework backs up or restores data based on the application's configuration file.
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册