提交 9a8396d1 编写于 作者: C caochuan

Merge remote-tracking branch 'docs/master' into getThumbnail

Signed-off-by: Ncaochuan <caochuan@huawei.com>
...@@ -368,18 +368,18 @@ zh-cn/application-dev/reference/apis/js-apis-http.md @zhang-hai-feng @zengyawen ...@@ -368,18 +368,18 @@ zh-cn/application-dev/reference/apis/js-apis-http.md @zhang-hai-feng @zengyawen
zh-cn/application-dev/reference/apis/js-apis-huks.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-huks.md @gaoyong @zengyawen @niejiteng @jumozhanjiang
zh-cn/application-dev/reference/apis/js-apis-i18n.md @Buda-Liu @ningningW @mengjingzhimo @yangqing3 zh-cn/application-dev/reference/apis/js-apis-i18n.md @Buda-Liu @ningningW @mengjingzhimo @yangqing3
zh-cn/application-dev/reference/apis/js-apis-image.md @zhangqiang183 @zengyawen @chenyuheng @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-image.md @zhangqiang183 @zengyawen @chenyuheng @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @yuanxinying @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-inputdevice.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-inputdevice.md @yuanxinying @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-inputevent.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-inputevent.md @yuanxinying @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @yuanxinying @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @feng-aiwen @ningningW @SuperShrimp @murphy1984 zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @feng-aiwen @ningningW @SuperShrimp @murphy1984
zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @feng-aiwen @ningningW @SuperShrimp @murphy1984 zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @feng-aiwen @ningningW @SuperShrimp @murphy1984
zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @feng-aiwen @ningningW @SuperShrimp @murphy1984 zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @feng-aiwen @ningningW @SuperShrimp @murphy1984
zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @feng-aiwen @ningningW @SuperShrimp @murphy1984 zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @feng-aiwen @ningningW @SuperShrimp @murphy1984
zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md @yuanxinying @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-intl.md @Buda-Liu @ningningW @mengjingzhimo @yangqing3 zh-cn/application-dev/reference/apis/js-apis-intl.md @Buda-Liu @ningningW @mengjingzhimo @yangqing3
zh-cn/application-dev/reference/apis/js-apis-keycode.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-keycode.md @yuanxinying @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-keyevent.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-keyevent.md @yuanxinying @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-lightweightset.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-lightweightset.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-linkedlist.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-linkedlist.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
...@@ -389,7 +389,7 @@ zh-cn/application-dev/reference/apis/js-apis-media.md @liuyuehua1 @zengyawen @xx ...@@ -389,7 +389,7 @@ zh-cn/application-dev/reference/apis/js-apis-media.md @liuyuehua1 @zengyawen @xx
zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-mediaquery.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-mediaquery.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-missionManager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-missionManager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-mouseevent.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-mouseevent.md @yuanxinying @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-net-connection.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-net-connection.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-nfcController.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-nfcController.md @cheng_guohong @RayShih @cheng_guohong @quanli125
zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @cheng_guohong @RayShih @cheng_guohong @quanli125
...@@ -400,7 +400,7 @@ zh-cn/application-dev/reference/apis/js-apis-particleAbility.md @littlejerry1 @R ...@@ -400,7 +400,7 @@ zh-cn/application-dev/reference/apis/js-apis-particleAbility.md @littlejerry1 @R
zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-plainarray.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-plainarray.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-pointer.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-pointer.md @yuanxinying @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-power.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-power.md @aqxyjay @zengyawen @aqxyjay @alien0208
zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @nianCode @zengyawen @shuqinglin2 @jinhaihw zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @nianCode @zengyawen @shuqinglin2 @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-process.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-process.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
...@@ -435,6 +435,7 @@ zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @cheng_guohong ...@@ -435,6 +435,7 @@ zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @cheng_guohong
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
zh-cn/application-dev/reference/apis/js-apis-system-cipher.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-system-cipher.md @gaoyong @zengyawen @niejiteng @jumozhanjiang
zh-cn/application-dev/reference/apis/js-apis-system-configuration.md @Buda-Liu @ningningW @budda-wang @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-system-configuration.md @Buda-Liu @ningningW @budda-wang @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-system-date-time.md @feng-aiwen @ningningW @illybyy @murphy1984
zh-cn/application-dev/reference/apis/js-apis-system-device.md @mupceet @zengyawen @handyohos @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-system-device.md @mupceet @zengyawen @handyohos @nan-xiansen
zh-cn/application-dev/reference/apis/js-apis-system-fetch.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-system-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
...@@ -520,16 +521,21 @@ zh-cn/application-dev/reference/apis/js-apis-bundleManager.md @shuaytao @RayShih ...@@ -520,16 +521,21 @@ zh-cn/application-dev/reference/apis/js-apis-bundleManager.md @shuaytao @RayShih
zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md @jayleehw @RayShih @li-weifeng2 @currydavids zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md @jayleehw @RayShih @li-weifeng2 @currydavids
zh-cn/application-dev/reference/apis/js-apis-configPolicy.md @Buda-Liu @ningningW @budda-wang @yangqing3 zh-cn/application-dev/reference/apis/js-apis-configPolicy.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-cooperate.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-cooperate.md @yuanxinying @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md @gaoyong @zengyawen @niejiteng @jumozhanjiang
zh-cn/application-dev/reference/apis/js-apis-cert.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-cert.md @gaoyong @zengyawen @niejiteng @jumozhanjiang
zh-cn/application-dev/reference/apis/js-apis-curve.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-curve.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy
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
zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md @Buda-Liu @ningningW @budda-wang @yangqing3 zh-cn/application-dev/reference/apis/js-apis-enterprise-accountManager.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md @Buda-Liu @ningningW @budda-wang @yangqing3 zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceControl.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceInfo.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-networkManager.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-wifiManager.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-fileAccess.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-fileAccess.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-freeInstall.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-freeInstall.md @shuaytao @RayShih @wangzhen107 @inter515
......
...@@ -18,7 +18,7 @@ This repository stores device and application development documents provided by ...@@ -18,7 +18,7 @@ This repository stores device and application development documents provided by
- master: the latest version. - master: the latest version.
- OpenHarmony 3.2 Beta3. [Learn more](en/release-notes/OpenHarmony-v3.2-beta3.md) - OpenHarmony 3.2 Beta5. [Learn more](en/release-notes/OpenHarmony-v3.2-beta5.md)
- OpenHarmony 3.1 Release. [Learn more](en/release-notes/OpenHarmony-v3.1-release.md) - OpenHarmony 3.1 Release. [Learn more](en/release-notes/OpenHarmony-v3.1-release.md)
...@@ -34,7 +34,7 @@ This repository stores device and application development documents provided by ...@@ -34,7 +34,7 @@ This repository stores device and application development documents provided by
### Historical Stable Versions ### Historical Stable Versions
OpenHarmony_v1.x_release: OpenHarmony v1.1.5 LTS. [Learn more](en/release-notes/OpenHarmony-v1.1.5-LTS.md) OpenHarmony_v1.x_release: OpenHarmony 1.1.5 LTS. [Learn more](en/release-notes/OpenHarmony-v1.1.5-LTS.md)
[More versions](en/release-notes/) [More versions](en/release-notes/)
...@@ -51,6 +51,6 @@ You can evaluate available documents, make simple modifications, provide feedbac ...@@ -51,6 +51,6 @@ You can evaluate available documents, make simple modifications, provide feedbac
Excellent contributors will be awarded and the contributions will be publicized in the developer community. Excellent contributors will be awarded and the contributions will be publicized in the developer community.
- Mail list: docs@openharmony.io - Mailing list: docs@openharmony.io
- Zulip group: documentation_sig - Zulip group: documentation_sig
\ No newline at end of file
...@@ -183,7 +183,7 @@ For details about how to obtain the source code of OpenHarmony, see [Source Code ...@@ -183,7 +183,7 @@ For details about how to obtain the source code of OpenHarmony, see [Source Code
## Hands-On Tutorials ## Hands-On Tutorials
[Samples](https://gitee.com/openharmony/app_samples) [Samples](https://gitee.com/openharmony/applications_app_samples)
[Codelabs](https://gitee.com/openharmony/codelabs) [Codelabs](https://gitee.com/openharmony/codelabs)
......
...@@ -24,7 +24,7 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O ...@@ -24,7 +24,7 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O
All applications should be developed on top of these frameworks. All applications should be developed on top of these frameworks.
Then, equip yourself for developing the key features, with the following guidelines: Then, equip yourself for developing the key features, with the following guidelines:
- [Common Event and Notification](notification/notification-brief.md) - [Common Event and Notification](notification/notification-overview.md)
- [Window Manager](windowmanager/window-overview.md) - [Window Manager](windowmanager/window-overview.md)
- [WebGL](webgl/webgl-overview.md) - [WebGL](webgl/webgl-overview.md)
- [Media](media/audio-overview.md) - [Media](media/audio-overview.md)
......
...@@ -17,8 +17,11 @@ ...@@ -17,8 +17,11 @@
- ExtensionAbility Component - ExtensionAbility Component
- [ExtensionAbility Component Overview](extensionability-overview.md) - [ExtensionAbility Component Overview](extensionability-overview.md)
- [ServiceExtensionAbility](serviceextensionability.md) - [ServiceExtensionAbility](serviceextensionability.md)
- [DataShareExtensionAbility](datashareextensionability.md) - [DataShareExtensionAbility (System Applications Only)](datashareextensionability.md)
- [FormExtensionAbility (Widget)](widget-development-stage.md) - [FormExtensionAbility (Widget)](widget-development-stage.md)
- [StaticSubscriberExtensionAbility](static-subscriber-extension-ability.md)
- [AccessibilityExtensionAbility](accessibilityextensionability.md)
- [WindowExtensionAbility](windowextensionability.md)
- [AbilityStage Component Container](abilitystage.md) - [AbilityStage Component Container](abilitystage.md)
- [Context](application-context-stage.md) - [Context](application-context-stage.md)
- Want - Want
...@@ -31,8 +34,8 @@ ...@@ -31,8 +34,8 @@
- [Component Startup Rules](component-startup-rules.md) - [Component Startup Rules](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](hop-cross-device-migration.md) - [Cross-Device Migration (System Applications Only)](hop-cross-device-migration.md)
- [Multi-device Collaboration](hop-multi-device-collaboration.md) - [Multi-device Collaboration (System Applications Only)](hop-multi-device-collaboration.md)
- IPC - IPC
- [Process Model](process-model-stage.md) - [Process Model](process-model-stage.md)
- Common Events - Common Events
...@@ -62,7 +65,7 @@ ...@@ -62,7 +65,7 @@
- [Creating a PageAbility](create-pageability.md) - [Creating a PageAbility](create-pageability.md)
- [Starting a Local PageAbility](start-local-pageability.md) - [Starting a Local PageAbility](start-local-pageability.md)
- [Stopping a PageAbility](stop-pageability.md) - [Stopping a PageAbility](stop-pageability.md)
- [Starting a Remote PageAbility](start-remote-pageability.md) - [Starting a Remote PageAbility (System Applications Only)](start-remote-pageability.md)
- [Starting a Specified Page](start-page.md) - [Starting a Specified Page](start-page.md)
- [Window Properties](window-properties.md) - [Window Properties](window-properties.md)
- [Requesting Permissions](request-permissions.md) - [Requesting Permissions](request-permissions.md)
......
# AccessibilityExtensionAbility Development
The **AccessibilityExtensionAbility** module provides accessibility extension capabilities based on the **ExtensionAbility** framework. You can develop your accessibility applications by applying the **AccessibilityExtensionAbility** template to enhance usability.
> **Environment Requirements**
>
> IDE: DevEco Studio 3.0 Beta3 (3.0.0.900) or later
>
> SDK: API version 9 or later
>
> Model: stage
This document is organized as follows:
- [Creating an AccessibilityExtAbility File](#creating-an-accessibility-extension-service)
- [Processing an Accessibility Event](#processing-an-accessibility-event)
- [Declaring Capabilities of Accessibility Extension Services](#declaring-capabilities-of-accessibility-extension-services)
- [Enabling a Custom Accessibility Extension Service](#enabling-a-custom-accessibility-extension-service)
## Creating an Accessibility Extension Service
You can create an accessibility extension service by creating a project from scratch or adding the service to an existing project.
### Creating a Project
Perform the following steps in DevEco Studio:
1. From the upper left corner of DevEco Studio, choose **File** > **New** > **Create Project**.
2. By following the project creation wizard, click the **OpenHarmony** tab, select the **Empty Ability** template, and then click **Next**.
3. Set **Project type** to **Application**, **Compile API** (or **Compile SDK**, depending on the version used) to **9**, and **Model** to **Stage**, and then click **Finish**.
### Creating an AccessibilityExtAbility File
To add an accessibility extension service to a project, create the **AccessibilityExtAbility** folder in the **ets** folder of the project, create the **AccessibilityExtAbility.ts** file in the new folder, and add the following code to the new file:
```typescript
import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility';
class AccessibilityExtAbility extends AccessibilityExtensionAbility {
onConnect() {
console.log('AccessibilityExtAbility onConnect');
}
onDisconnect() {
console.log('AccessibilityExtAbility onDisconnect');
}
onAccessibilityEvent(accessibilityEvent) {
console.log('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent));
}
}
export default AccessibilityExtAbility;
```
The APIs defined in the file are as follows.
| API| Description|
| ---- | ---- |
| onConnect(): void | Called when a connection with the extension service is set up.|
| onDisconnect(): void | Called when the connection with the extension service is severed.|
| onAccessibilityEvent(event: AccessibilityEvent): void | Called when an accessibility event occurs|
## Processing an Accessibility Event
You can process the service logic for accessibility events in the **onAccessibilityEvent()** API. For details about the events, see [AccessibilityEvent](../reference/apis/js-apis-application-accessibilityExtensionAbility.md#accessibilityevent). The following code snippet uses the **pageStateUpdate** event as an example.
```typescript
onAccessibilityEvent(accessibilityEvent) {
console.log('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent));
if (accessibilityEvent.eventType === 'pageStateUpdate') {
console.log('AccessibilityExtAbility onAccessibilityEvent: pageStateUpdate');
// TODO: Develop custom logic.
}
}
```
For an accessibility event, you can use the APIs of the [AccessibilityExtensionContext](../reference/apis/js-apis-inner-application-accessibilityExtensionContext.md) module to configure the concerned information, obtain root information, and inject gestures.
You can also process physical key events in the accessibility extension service. For details, see [onKeyEvent](../reference/apis/js-apis-application-accessibilityExtensionAbility.md#accessibilityextensionabilityonkeyevent).
## Declaring Capabilities of Accessibility Extension Services
After developing the custom logic for an accessibility extension service, you must add the configuration information of the service to the corresponding module-level **module.json5** file in the project directory. In the file, the **srcEntrance** tag indicates the path to the accessibility extension service. Make sure the value of the **type** tag is fixed at **accessibility**. Otherwise, the connection to the service will fail.
```json
"extensionAbilities": [
{
"name": "AccessibilityExtAbility",
"srcEntrance": "./ets/AccessibilityExtAbility/AccessibilityExtAbility.ts",
"label": "$string:MainAbility_label",
"description": "$string:MainAbility_desc",
"type": "accessibility",
"metadata": [
{
"name": "ohos.accessibleability",
"resource": "$profile:accessibility_config"
}
]
}
]
```
**accessibility_config** is the specific configuration of the accessibility extension service. You need to create the **accessibility_config.json** file in **resources/base/profile/** and declare the [capabilities](../reference/apis/js-apis-accessibility.md#capability) of the service in the file.
```json
{
"accessibilityCapabilities": [
"retrieve",
"gesture"
]
}
```
## Enabling a Custom Accessibility Extension Service
To enable or disable an accessibility extension service, run the following command:
- To enable the service: **accessibility enable -a AccessibilityExtAbility -b com.example.demo -c rg**
- To disable the service: **accessibility disable -a AccessibilityExtAbility -b com.example.demo**
In the preceding commands, **AccessibilityExtAbility** indicates the name of the accessibility extension service, **com.example.demo** indicates the bundle name, and **rg** indicates the capabilities (**r** is short for retrieve).
If the service is enabled or disabled successfully, the message "enable ability successfully" or "disable ability successfully" is displayed.
# Common action and entities Values # Common action and entities Values
The [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) field specifies the common operation (such as viewing, sharing, and application details) to be performed by the caller. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data, for example, viewing URI data. For example, if the URI is a website and the action is **ohos.want.action.viewData**, the ability that supports website viewing is matched. Declaring the **action** field in Want indicates that the invoked application should support the declared operation. The **actions** field under **skills** in the configuration file indicates the operations supported by the application. **action**: Action to take, such as viewing, sharing, and application details, by the caller. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data, for example, viewing URI data. For example, if the URI is a website and the action is **ohos.want.action.viewData**, the ability that supports website viewing is matched. Declaring the **action** field in Want indicates that the invoked application should support the declared operation. The **actions** field under **skills** in the configuration file indicates the operations supported by the application.
**Common action Values** **Common action Values**
...@@ -14,7 +14,7 @@ The [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantactio ...@@ -14,7 +14,7 @@ The [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantactio
- **ACTION_VIEW_MULTIPLE_DATA**: action of launching the UI for sending multiple data records. - **ACTION_VIEW_MULTIPLE_DATA**: action of launching the UI for sending multiple data records.
The [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) field specifies the additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want. You can define this field to filter application categories, for example, browser. Declaring the **entities** field in Want indicates that the invoked application should belong to the declared category. The **entities** field under **skills** in the configuration file indicates the categories supported by the application. **entities**: Category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want. You can define this field to filter application categories, for example, browser. Declaring the **entities** field in Want indicates that the invoked application should belong to the declared category. The **entities** field under **skills** in the configuration file indicates the categories supported by the application.
**Common entities Values** **Common entities Values**
......
...@@ -3,7 +3,8 @@ ...@@ -3,7 +3,8 @@
When developing an application, you may need to configure certain tags to identify the application, such as the bundle name and application icon. This topic describes key tags that need to be configured during application development. Icons and labels are usually configured together. There is the application icon, application label, entry icon, and entry label, which correspond to the **icon** and **label** fields in the [app.json5 file](../quick-start/app-configuration-file.md) and [module.json5 file](../quick-start/module-configuration-file.md). The application icon and label are used in **Settings**. For example, they are displayed in the application list in **Settings**. The entry icon is displayed on the device's home screen after the application is installed. The entry icon maps to a [UIAbility](uiability-overview.md) component. Therefore, an application can have multiple entry icons and labels. When you touch one of them, the corresponding UIAbility page is displayed. When developing an application, you may need to configure certain tags to identify the application, such as the bundle name and application icon. This topic describes key tags that need to be configured during application development. Icons and labels are usually configured together. There is the application icon, application label, entry icon, and entry label, which correspond to the **icon** and **label** fields in the [app.json5 file](../quick-start/app-configuration-file.md) and [module.json5 file](../quick-start/module-configuration-file.md). The application icon and label are used in **Settings**. For example, they are displayed in the application list in **Settings**. The entry icon is displayed on the device's home screen after the application is installed. The entry icon maps to a [UIAbility](uiability-overview.md) component. Therefore, an application can have multiple entry icons and labels. When you touch one of them, the corresponding UIAbility page is displayed.
**Figure 1** Icons and labels
**Figure 1** Icons and labels
![application-component-configuration-stage](figures/application-component-configuration-stage.png) ![application-component-configuration-stage](figures/application-component-configuration-stage.png)
...@@ -14,11 +15,11 @@ When developing an application, you may need to configure certain tags to identi ...@@ -14,11 +15,11 @@ When developing an application, you may need to configure certain tags to identi
- **Configuring the application icon and label** - **Configuring the application icon and label**
The application icon is specified by the **icon** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory of the project. The **icon** field must be set to the index of an image so that the image is displayed as the application icon. The application icon is usually displayed in an application list, for example, the application list in **Settings**. You must configure an icon and label for an application on the stage model.
The application label is specified by the **label** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** module of the project. The **label** field specifies the application name displayed to users. It must be set to the index of a string resource. The application icon is specified by the **icon** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory of the project. The **icon** field must be set to the index of an image so that the image is displayed as the application icon.
The **icon** and **label** fields in the **app.json5** file are under **app**, as follows: The application label is specified by the **label** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** module of the project. The **label** field specifies the application name displayed to users. It must be set to the index of a string resource.
```json ```json
{ {
...@@ -32,7 +33,9 @@ When developing an application, you may need to configure certain tags to identi ...@@ -32,7 +33,9 @@ When developing an application, you may need to configure certain tags to identi
- **Configuring the entry icon and label** - **Configuring the entry icon and label**
The entry icon and label are configured by specifying **icon** and **label** under **abilities** in the [module.json5 file](../quick-start/module-configuration-file.md). For example, if you want to display the icon and label of the UIAbility component on the home screen, add **entity.system.home** to **entities** and **action.system.home** to **actions** under **skills**. If the preceding fields are configured for multiple UIAbility components of an application, multiple icons and labels are displayed on the home screen, corresponding to their respective UIAbility component. On the stage model, you can configure an entry icon and label for each application component. The entry icon and label are displayed on the home screen.
The entry icon is configured by specifying **icon** under **abilities** in the [module.json5 file](../quick-start/module-configuration-file.md). For example, if you want to display the icon of the UIAbility component on the home screen, add **entity.system.home** to **entities** and **ohos.want.action.home** to **actions** under **skills**. If this field is configured for multiple UIAbility components of an application, multiple icons are displayed on the home screen, corresponding to their respective UIAbility component.
```json ```json
{ {
...@@ -49,7 +52,7 @@ When developing an application, you may need to configure certain tags to identi ...@@ -49,7 +52,7 @@ When developing an application, you may need to configure certain tags to identi
"entity.system.home" "entity.system.home"
], ],
"actions": [ "actions": [
"action.system.home" "ohos.want.action.home"
] ]
} }
], ],
...@@ -69,4 +72,3 @@ When developing an application, you may need to configure certain tags to identi ...@@ -69,4 +72,3 @@ When developing an application, you may need to configure certain tags to identi
- **Configuring the module permission** - **Configuring the module permission**
The **requestPermission** field in the [module.json5 file](../quick-start/module-configuration-file.md) is used to configure the permission information required by the module to access the protected part of the system or other applications. This field declares the name of the permission to request, the reason for requesting the permission, and the scenario where the permission is used. The **requestPermission** field in the [module.json5 file](../quick-start/module-configuration-file.md) is used to configure the permission information required by the module to access the protected part of the system or other applications. This field declares the name of the permission to request, the reason for requesting the permission, and the scenario where the permission is used.
...@@ -10,11 +10,11 @@ ...@@ -10,11 +10,11 @@
![context-inheritance](figures/context-inheritance.png) ![context-inheritance](figures/context-inheritance.png)
- The figure below illustrates the holding relationship of contexts. - The figure below illustrates the holding relationship of contexts.
![context-holding](figures/context-holding.png) ![context-holding](figures/context-holding.png)
- The following describes the information provided by different contexts. - The following describes the information provided by different contexts.
- [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md): Each UIAbility has the **Context** attribute, which provides APIs to operate the ability, obtain the ability configuration, and more. - [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md): Each UIAbility has the **Context** attribute, which provides APIs to operate an application component, obtain the application component configuration, and more.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
...@@ -25,6 +25,10 @@ ...@@ -25,6 +25,10 @@
} }
} }
``` ```
> **NOTE**
>
> For details about how to obtain the context of a **UIAbility** instance on the page, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
- Scenario-specific [ExtensionContext](../reference/apis/js-apis-inner-application-extensionContext.md): For example, ServiceExtensionContext, inherited from ExtensionContext, provides APIs related to background services. - Scenario-specific [ExtensionContext](../reference/apis/js-apis-inner-application-extensionContext.md): For example, ServiceExtensionContext, inherited from ExtensionContext, provides APIs related to background services.
```ts ```ts
...@@ -47,7 +51,7 @@ ...@@ -47,7 +51,7 @@
} }
} }
``` ```
- [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md): application-level context. It provides APIs for subscribing to ability lifecycle changes, system memory changes, and system environment changes. The application-level context can be obtained from UIAbility, ExtensionAbility, and AbilityStage. - [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md): application-level context. It provides APIs for subscribing to application component lifecycle changes, system memory changes, and system environment changes. The application-level context can be obtained from UIAbility, ExtensionAbility, and AbilityStage.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
...@@ -179,13 +183,10 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] ...@@ -179,13 +183,10 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
> To obtain the context of another application: > To obtain the context of another application:
> >
> - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
>
> - This is a system API and cannot be called by third-party applications.
>
> - This is a system API and cannot be called by third-party applications. > - This is a system API and cannot be called by third-party applications.
For example, application information displayed on the home screen includes the application name and icon. The home screen application calls the foregoing method to obtain the context information, so as to obtain the resource information including the application name and icon. For example, application information displayed on the home screen includes the application name and icon. The home screen application calls the foregoing method to obtain the context information, so as to obtain the resource information including the application name and icon.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
...@@ -198,7 +199,6 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] ...@@ -198,7 +199,6 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
} }
} }
``` ```
- Call **createModuleContext(bundleName:string, moduleName:string)** to obtain the context of a specified module of another application. After obtaining the context, you can obtain the resource information of that module. - Call **createModuleContext(bundleName:string, moduleName:string)** to obtain the context of a specified module of another application. After obtaining the context, you can obtain the resource information of that module.
> **NOTE** > **NOTE**
...@@ -206,9 +206,6 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] ...@@ -206,9 +206,6 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
> To obtain the context of a specified module of another application: > To obtain the context of a specified module of another application:
> >
> - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
>
> - This is a system API and cannot be called by third-party applications.
>
> - This is a system API and cannot be called by third-party applications. > - This is a system API and cannot be called by third-party applications.
```ts ```ts
...@@ -223,7 +220,7 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] ...@@ -223,7 +220,7 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
} }
} }
``` ```
- Call **createModuleContext(moduleName:string)** to obtain the context of another module in the current application. After obtaining the context, you can obtain the resource information of that module. - Call **createModuleContext(moduleName:string)** to obtain the context of another module in the current application. After obtaining the context, you can obtain the resource information of that module.
```ts ```ts
......
...@@ -14,7 +14,7 @@ The stage model is designed based on the following considerations, which make it ...@@ -14,7 +14,7 @@ The stage model is designed based on the following considerations, which make it
1. **Designed for complex applications** 1. **Designed for complex applications**
- In the stage model, multiple application components share an ArkTS engine (VM running the programming language ArkTS) instance, making it easy for application components to share objects and status while requiring less memory. - In the stage model, multiple application components share an ArkTS engine (VM running the programming language ArkTS) instance, making it easy for application components to share objects and status while requiring less memory.
- The object-oriented development mode makes the code of complex applications easy to read, maintain, and scale. - The object-oriented development mode makes the code of complex applications easy to read, maintain, and scale.
2. **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. **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**
...@@ -48,13 +48,12 @@ In the stage model, multiple application components share the same ArkTS engine ...@@ -48,13 +48,12 @@ In the stage model, multiple application components share the same ArkTS engine
The table below describes their differences in detail. The table below describes their differences in detail.
**Table 1** Differences between the FA model and stage model **Table 1** Differences between the FA model and stage model
| Item| FA model| Stage model| | Item| FA model| Stage model|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| **Application component**| 1. Component classification<br>- PageAbility: has the UI and supports user interaction. For details, see [PageAbility Component Overview](pageability-overview.md).<br>- ServiceAbility: provides background services and has no UI. For details, see [ServiceAbility Component Overview](serviceability-overview.md).<br>- DataAbility: provides the data sharing capability and has no UI. For details, see [DataAbility Component Overview](dataability-overview.md).<br>2. Development mode<br>Application components are specified by exporting anonymous objects and fixed entry files. You cannot perform derivation. It is inconvenient for capability expansion.| 1. Component classification<br>- UIAbility: has the UI and supports user interaction. For details, see [UIAbility Component Overview](uiability-overview.md).<br>- ExtensionAbility: provides extension capabilities (such as widget and input methods) for specific scenarios. For details, see [ExtensionAbility Component Overview](extensionability-overview.md).<br>2. Development mode<br>The object-oriented mode is used to provide open application components as classes. You can derive application components for capability expansion.| | **Application component**| 1. Component classification<br>![fa-model-component](figures/fa-model-component.png)<br/>- PageAbility: has the UI and supports user interaction For details, see [PageAbility Component Overview](pageability-overview.md).<br>- ServiceAbility: provides background services and has no UI. For details, see [ServiceAbility Component Overview](serviceability-overview.md).<br>- DataAbility: provides the data sharing capability and has no UI. For details, see [DataAbility Component Overview](dataability-overview.md).<br>2. Development mode<br>Application components are specified by exporting anonymous objects and fixed entry files. You cannot perform derivation. It is inconvenient for capability expansion. | 1. Component classification<br>![stage-model-component](figures/stage-model-component.png)<br/> - UIAbility: has the UI and supports user interaction. For details, see [UIAbility Component Overview](uiability-overview.md).<br>- ExtensionAbility: provides extension capabilities (such as widget and input methods) for specific scenarios. For details, see [ExtensionAbility Component Overview](extensionability-overview.md).<br>2. Development mode<br>The object-oriented mode is used to provide open application components as classes. You can derive application components for capability expansion. |
| **Process model**| There are two types of processes:<br>1. Main process<br>2. Rendering process<br>For details, see [Process Model (FA Model)](process-model-fa.md). | There are three types of processes:<br>1. Main process<br>2. ExtensionAbility process<br>3. Rendering process<br>For details, see [Process Model (Stage Model)](process-model-stage.md). | | **Process model**| There are two types of processes:<br>1. Main process<br>2. Rendering process<br>For details, see [Process Model (FA Model)](process-model-fa.md).| There are three types of processes:<br>1. Main process<br>2. ExtensionAbility process<br>3. Rendering process<br>For details, see [Process Model (Stage Model)](process-model-stage.md).|
| **Thread model**| 1. ArkTS engine instance creation<br>A process can run multiple application component instances, and each application component instance runs in an independent ArkTS engine instance.<br>2. Thread model<br>Each ArkTS engine instance is created on an independent thread (non-main thread). The main thread does not have an ArkTS engine instance.<br>3. Intra-process object sharing: not supported.<br>For details, see [Thread Model (FA Model)](thread-model-fa.md). | 1. ArkTS engine instance creation<br>A process can run multiple application component instances, and all application component instances share one ArkTS engine instance.<br>2. Thread model<br>The ArkTS engine instance is created on the main thread.<br>3. Intra-process object sharing: supported.<br>For details, see [Thread Model (Stage Model)](thread-model-stage.md). | | **Thread model**| 1. ArkTS engine instance creation<br>A process can run multiple application component instances, and each application component instance runs in an independent ArkTS engine instance.<br>2. Thread model<br>Each ArkTS engine instance is created on an independent thread (non-main thread). The main thread does not have an ArkTS engine instance.<br>3. Intra-process object sharing: not supported.<br>For details, see [Thread Model (FA Model)](thread-model-fa.md).| 1. ArkTS engine instance creation<br>A process can run multiple application component instances, and all application component instances share one ArkTS engine instance.<br>2. Thread model<br>The ArkTS engine instance is created on the main thread.<br>3. Intra-process object sharing: supported.<br>For details, see [Thread Model (Stage Model)](thread-model-stage.md).|
| **Mission management model**| - A mission is created for each PageAbility component instance.<br>- Missions are stored persistently until the number of missions exceeds the maximum (customized based on the product configuration) or users delete missions.<br>- PageAbility components do not form a stack structure.<br>For details, see [Mission Management Scenarios](mission-management-overview.md).| - A mission is created for each UIAbility component instance.<br>- Missions are stored persistently until the number of missions exceeds the maximum (customized based on the product configuration) or users delete missions.<br>- UIAbility components do not form a stack structure.<br>For details, see [Mission Management Scenarios](mission-management-overview.md).| | **Mission management model**| - A mission is created for each PageAbility component instance.<br>- Missions are stored persistently until the number of missions exceeds the maximum (customized based on the product configuration) or users delete missions.<br>- PageAbility components do not form a stack structure.<br>For details, see [Mission Management Scenarios](mission-management-overview.md).| - A mission is created for each UIAbility component instance.<br>- Missions are stored persistently until the number of missions exceeds the maximum (customized based on the product configuration) or users delete missions.<br>- UIAbility components do not form a stack structure.<br>For details, see [Mission Management Scenarios](mission-management-overview.md).|
| **Application configuration file**| The **config.json** file is used to describe the application, HAP, and application component information.<br>For details, see [Application Configuration File Overview (FA Model)](../quick-start/application-configuration-file-overview-fa.md).| The **app.json5** file is used to describe the application information, and the **module.json5** file is used to describe the HAP and application component information.<br>For details, see [Application Configuration File Overview (Stage Model)](../quick-start/application-configuration-file-overview-stage.md).| | **Application configuration file**| The **config.json** file is used to describe the application, HAP, and application component information.<br>For details, see [Application Configuration File Overview (FA Model)](../quick-start/application-configuration-file-overview-fa.md).| The **app.json5** file is used to describe the application information, and the **module.json5** file is used to describe the HAP and application component information.<br>For details, see [Application Configuration File Overview (Stage Model)](../quick-start/application-configuration-file-overview-stage.md).|
# DataShareExtensionAbility # DataShareExtensionAbility (System Applications Only)
DataShareExtensionAbility is available only for system application. It provides the data sharing capability. System applications can implement a DataShareExtensionAbility or access an existing DataShareExtensionAbility in the system. Third-party applications can only access an existing DataShareExtensionAbility. For details, see [DataShare Development](../database/database-datashare-guidelines.md). DataShareExtensionAbility provides the data sharing capability. System applications can implement a DataShareExtensionAbility or access an existing DataShareExtensionAbility in the system. Third-party applications can only access an existing DataShareExtensionAbility. For details, see [DataShare Development](../database/database-datashare-guidelines.md).
# EnterpriseAdminExtensionAbility Development
## Introduction
**EnterpriseAdminExtensionAbility** is essential to a mobile device management (MDM) application. When developing an MDM application for an enterprise, you must inherit the **EnterpriseAdminExtensionAbility** class and have the MDM service logic implemented in an **EnterpriseAdminExtensionAbility** instance. The **EnterpriseAdminExtensionAbility** class provides callbacks for the enable, disable, install, and uninstall events of a device administrator application, implementing notification of system administrator status changes.
## Constraints
- ***Function constraints***
The APIs provided can be used only by device administrator applications.
## Scenarios: Listening for the Enable, Disable, Install, and Uninstall Events of a Device Administrator Application
### Overview
**onAdminEnabled**: called when the 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**: called when the system or employee disables the DeviceAdmin permission to notify the enterprise administrator that the device is no longer managed.
**onBundleAdded**: called to notify the enterprise administrator that the specified MDM application is installed on the device. In enterprise application administration settings, after the enterprise administrator subscribes to application installation and uninstallation events, the MDM application reports the events through the callbacks.
**onBundleRemoved**: called to notify the enterprise administrator that the specified MDM application is uninstalled on the device.
### Available APIs
| Class | API | Description |
| :------------------------------ | ----------------------------------------- | ---------------------------- |
| EnterpriseAdminExtensionAbility | onAdminDisabled(): void | Called when the device administrator application is enabled.|
| EnterpriseAdminExtensionAbility | onBundleAdded(bundleName: string): void | Called when the MDM application is installed. |
| EnterpriseAdminExtensionAbility | onAdminEnabled(): void | Called when the device administrator application is disabled. |
| EnterpriseAdminExtensionAbility | onBundleRemoved(bundleName: string): void | Called when the MDM application is uninstalled. |
### How to Develop
To implement **EnterpriseAdminExtensionAbility**, enable the device administrator application and create an **ExtensionAbility** instance from 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**.
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. Customize a class that inherits from **EnterpriseAdminExtensionAbility** and add the required callbacks, such as **onAdminEnabled()** and **onAdminDisabled()**, through which the enterprise administrator can receive notification when the device administrator application is enabled or disabled.
```ts
import EnterpriseAdminExtensionAbility from '@ohos.enterprise.EnterpriseAdminExtensionAbility';
export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility {
onAdminEnabled() {
console.info("onAdminEnabled");
}
onAdminDisabled() {
console.info("onAdminDisabled");
}
onBundleAdded(bundleName: string) {
console.info("EnterpriseAdminAbility onBundleAdded bundleName:" + bundleName)
}
onBundleRemoved(bundleName: string) {
console.info("EnterpriseAdminAbility onBundleRemoved bundleName" + bundleName)
}
};
```
4. Register **ServiceExtensionAbility** in the [module.json5](../quick-start/module-configuration-file.md) file of the target module. Among the parameters, set **type** to **enterpriseAdmin** and **srcEntrance** to the code path of the current ExtensionAbility.
```ts
"extensionAbilities": [
{
"name": "ohos.samples.enterprise_admin_ext_ability",
"type": "enterpriseAdmin",
"visible": true,
"srcEntrance": "./ets/enterpriseextability/EnterpriseAdminAbility.ts"
}
]
```
## Example
Use the **subscribeManagedEvent** and **unsubscribeManagedEvent** APIs in the **@ohos.enterprise.adminManager** module to subscribe to and unsubscribe from the application installation and uninstallation event, respectively. After the subscription is successful, the MDM application notifies the enterprise administrator when it is installed or uninstalled on the device.
```ts
@State managedEvents: Array<adminManager.ManagedEvent> = [0,1]
@State subscribeManagedEventMsg: string = ""
@State unsubscribeManagedEventMsg: string = ""
async subscribeManagedEventCallback() {
await adminManager.subscribeManagedEvent(this.admin,
[adminManager.ManagedEvent.MANAGED_EVENT_BUNDLE_ADDED,
adminManager.ManagedEvent.MANAGED_EVENT_BUNDLE_REMOVED], (error) => {
if (error) {
this.subscribeManagedEventMsg = 'subscribeManagedEvent Callback::errorCode: ' + error.code + ' errorMessage: ' + error.message
} else {
this.subscribeManagedEventMsg = 'subscribeManagedEvent Callback::success'
}
})
}
async unsubscribeManagedEventPromise() {
await adminManager.unsubscribeManagedEvent(this.admin,
[adminManager.ManagedEvent.MANAGED_EVENT_BUNDLE_ADDED,
adminManager.ManagedEvent.MANAGED_EVENT_BUNDLE_REMOVED]).then(() => {
this.unsubscribeManagedEventMsg = 'unsubscribeManagedEvent Promise::success'
}).catch((error) => {
this.unsubscribeManagedEventMsg = 'unsubscribeManagedEvent Promise::errorCode: ' + error.code + ' errorMessage: ' + error.message
})
}
```
...@@ -50,7 +50,7 @@ The system matches the **want** parameter (including the **action**, **entities* ...@@ -50,7 +50,7 @@ The system matches the **want** parameter (including the **action**, **entities*
### Matching Rules of action in the want Parameter ### Matching Rules of action in the want Parameter
The system matches the [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) attribute in the **want** parameter passed by the caller against **actions** under **skills** of the abilities. The system matches the **action** attribute in the **want** parameter passed by the caller against **actions** under **skills** of the abilities.
- If **action** in the passed **want** parameter is specified but **actions** under **skills** of an ability is unspecified, the matching fails. - If **action** in the passed **want** parameter is specified but **actions** under **skills** of an ability is unspecified, the matching fails.
...@@ -62,12 +62,12 @@ The system matches the [action](../reference/apis/js-apis-ability-wantConstant.m ...@@ -62,12 +62,12 @@ The system matches the [action](../reference/apis/js-apis-ability-wantConstant.m
**Figure 1** Matching rules of action in the want parameter **Figure 1** Matching rules of action in the want parameter
![want-action](figures/want-action.png) ![want-action](figures/want-action.png)
### Matching Rules of entities in the want Parameter ### Matching Rules of entities in the want Parameter
The system matches the [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) attribute in the **want** parameter passed by the caller against **entities** under **skills** of the abilities. The system matches the **entities** attribute in the **want** parameter passed by the caller against **entities** under **skills** of the abilities.
- If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an ability is specified, the matching is successful. - If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an ability is specified, the matching is successful.
...@@ -117,7 +117,7 @@ To simplify the description, **uri** and **type** passed in the **want** paramet ...@@ -117,7 +117,7 @@ To simplify the description, **uri** and **type** passed in the **want** paramet
Figure 4 Matching rules of uri and type in the want parameter Figure 4 Matching rules of uri and type in the want parameter
![want-uri-type2](figures/want-uri-type2.png) ![want-uri-type2](figures/want-uri-type2.png)
### Matching Rules of uri ### Matching Rules of uri
......
...@@ -9,7 +9,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab ...@@ -9,7 +9,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab
- [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.
- [WorkSchedulerExtensionAbility](../reference/apis/js-apis-resourceschedule-workScheduler.md): ExtensionAbility component of the work_scheduler type, which provides callbacks for Work Scheduler tasks. - [WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md): ExtensionAbility component of the work_scheduler type, which provides callbacks for Work Scheduler tasks.
- [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md): ExtensionAbility component of the input_method type, which provides an input method framework that can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more. - [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md): ExtensionAbility component of the input_method type, which provides an input method framework that can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more.
...@@ -21,7 +21,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab ...@@ -21,7 +21,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab
- [StaticSubscriberExtensionAbility](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md): ExtensionAbility component of the static_subscriber type, which provides APIs for static broadcast. - [StaticSubscriberExtensionAbility](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md): ExtensionAbility component of the static_subscriber type, which provides APIs for static broadcast.
- [WindowExtensionAbility](../reference/apis/js-apis-application-windowExtensionAbility.md): ExtensionAbility component of the window type, which allows system applications to display UIs of other applications. - [WindowExtensionAbility](../reference/apis/js-apis-application-windowExtensionAbility.md): ExtensionAbility component of the window type, which allows a system application to be embedded in and displayed over another application.
- [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.
......
# Cross-Device Migration # Cross-Device Migration (System Applications Only)]
## When to Use ## When to Use
Cross-device migration is available only for system applications. The main task 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 functionalities:
- Storage and restoration of custom data - Storage and restoration of custom data
......
# Multi-device Collaboration # Multi-device Collaboration (System Applications Only)
## When to Use ## When to Use
Multi-device coordination is available only for system applications. It involves the following scenarios: Multi-device coordination involves the following scenarios:
- [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned) - [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned)
...@@ -93,7 +93,7 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -93,7 +93,7 @@ On device A, touch the **Start** button provided by the initiator application to
} }
``` ```
4. Set the target component parameters, and call **startAbility()** to start UIAbility or ServiceExtensionAbility. 4. Set the target component parameters, and call [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start UIAbility or ServiceExtensionAbility.
```ts ```ts
let want = { let want = {
...@@ -305,7 +305,7 @@ A system application can connect to a service on another device by calling [conn ...@@ -305,7 +305,7 @@ A system application can connect to a service on another device by calling [conn
## Using Cross-Device Ability Call ## Using Cross-Device Ability Call
The basic principle of cross-device ability call is the same as that of intra-device ability call. For details, see [Using Ability Call to Implement UIAbility Interaction](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction). The basic principle of cross-device ability call is the same as that of intra-device ability call. For details, see [Using Ability Call to Implement UIAbility Interaction (System Applications Only)](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction-system-applications-only).
The following describes how to implement multi-device collaboration through cross-device ability call. The following describes how to implement multi-device collaboration through cross-device ability call.
...@@ -382,68 +382,68 @@ The following describes how to implement multi-device collaboration through cros ...@@ -382,68 +382,68 @@ The following describes how to implement multi-device collaboration through cros
```ts ```ts
export default class MySequenceable { export default class MySequenceable {
num: number = 0 num: number = 0;
str: string = "" str: string = "";
constructor(num, string) { constructor(num, string) {
this.num = num this.num = num;
this.str = string this.str = string;
} }
marshalling(messageParcel) { marshalling(messageParcel) {
messageParcel.writeInt(this.num) messageParcel.writeInt(this.num);
messageParcel.writeString(this.str) messageParcel.writeString(this.str);
return true return true;
} }
unmarshalling(messageParcel) { unmarshalling(messageParcel) {
this.num = messageParcel.readInt() this.num = messageParcel.readInt();
this.str = messageParcel.readString() this.str = messageParcel.readString();
return true return true;
} }
} }
``` ```
4. Implement **Callee.on** and **Callee.off**. 4. Implement **Callee.on** and **Callee.off**.
In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements.
```ts ```ts
const TAG: string = '[CalleeAbility]' const TAG: string = '[CalleeAbility]';
const MSG_SEND_METHOD: string = 'CallSendMsg' const MSG_SEND_METHOD: string = 'CallSendMsg';
function sendMsgCallback(data) { function sendMsgCallback(data) {
console.info('CalleeSortFunc called') console.info('CalleeSortFunc called');
// Obtain the sequenceable data sent by the caller ability. // Obtain the sequenceable data sent by the caller ability.
let receivedData = new MySequenceable(0, '') let receivedData = new MySequenceable(0, '');
data.readSequenceable(receivedData) data.readSequenceable(receivedData);
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`) console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`);
// Process the data. // Process the data.
// Return the sequenceable data result to the caller ability. // Return the sequenceable data result to the caller ability.
return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`) return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`);
} }
export default class CalleeAbility extends Ability { export default class CalleeAbility extends Ability {
onCreate(want, launchParam) { onCreate(want, launchParam) {
try { try {
this.callee.on(MSG_SEND_METHOD, sendMsgCallback) this.callee.on(MSG_SEND_METHOD, sendMsgCallback);
} catch (error) { } catch (error) {
console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`);
} }
} }
onDestroy() { onDestroy() {
try { try {
this.callee.off(MSG_SEND_METHOD) this.callee.off(MSG_SEND_METHOD);
} catch (error) { } catch (error) {
console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`) console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`);
} }
} }
} }
``` ```
4. Obtain the caller object and access the callee ability. 4. Obtain the caller object and access the callee ability.
1. Import the **UIAbility** module. 1. Import the **UIAbility** module.
...@@ -458,8 +458,8 @@ The following describes how to implement multi-device collaboration through cros ...@@ -458,8 +458,8 @@ The following describes how to implement multi-device collaboration through cros
```ts ```ts
async onButtonGetRemoteCaller() { async onButtonGetRemoteCaller() {
var caller = undefined var caller = undefined;
var context = this.context var context = this.context;
context.startAbilityByCall({ context.startAbilityByCall({
deviceId: getRemoteDeviceId(), deviceId: getRemoteDeviceId(),
...@@ -467,16 +467,16 @@ The following describes how to implement multi-device collaboration through cros ...@@ -467,16 +467,16 @@ The following describes how to implement multi-device collaboration through cros
abilityName: 'CalleeAbility' abilityName: 'CalleeAbility'
}).then((data) => { }).then((data) => {
if (data != null) { if (data != null) {
caller = data caller = data;
console.info('get remote caller success') console.info('get remote caller success');
// Register the onRelease() listener of the caller ability. // Register the onRelease() listener of the caller ability.
caller.onRelease((msg) => { caller.onRelease((msg) => {
console.info(`remote caller onRelease is called ${msg}`) console.info(`remote caller onRelease is called ${msg}`);
}) })
console.info('remote caller register OnRelease succeed') console.info('remote caller register OnRelease succeed');
} }
}).catch((error) => { }).catch((error) => {
console.error(`get remote caller failed with ${error}`) console.error(`get remote caller failed with ${error}`);
}) })
} }
``` ```
......
...@@ -10,7 +10,7 @@ The following describes how the mission list manager manages the UIAbility insta ...@@ -10,7 +10,7 @@ The following describes how the mission list manager manages the UIAbility insta
**Figure 1** Missions and singleton mode **Figure 1** Missions and singleton mode
![mission-and-singleton](figures/mission-and-singleton.png) ![mission-and-singleton](figures/mission-and-singleton.png)
- **standard**: Each time **startAbility()** is called, a UIAbility instance is created in the application process. - **standard**: Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, a **UIAbility** instance is created in the application process.
**Figure 2** Missions and standard mode **Figure 2** Missions and standard mode
![mission-and-standard](figures/mission-and-standard.png) ![mission-and-standard](figures/mission-and-standard.png)
...@@ -30,4 +30,3 @@ Every mission retains a snapshot of the UIAbility instance. After the UIAbility ...@@ -30,4 +30,3 @@ Every mission retains a snapshot of the UIAbility instance. After the UIAbility
> **NOTE** > **NOTE**
> >
> The **specified** mode is supported in the stage model only. > The **specified** mode is supported in the stage model only.
...@@ -28,7 +28,7 @@ Missions are managed by system applications (such as home screen), rather than t ...@@ -28,7 +28,7 @@ Missions are managed by system applications (such as home screen), rather than t
- Switch a mission to the foreground. - Switch a mission to the foreground.
A UIAbility instance corresponds to an independent mission. Therefore, when an application calls the **startAbility()** method to start a UIAbility, a mission is created. A UIAbility instance corresponds to an independent mission. Therefore, when an application calls [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start a UIAbility, a mission is created.
To call [missionManager](../reference/apis/js-apis-application-missionManager.md) to manage missions, the home screen application must request the **ohos.permission.MANAGE_MISSIONS** permission. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). To call [missionManager](../reference/apis/js-apis-application-missionManager.md) to manage missions, the home screen application must request the **ohos.permission.MANAGE_MISSIONS** permission. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
...@@ -36,6 +36,8 @@ To call [missionManager](../reference/apis/js-apis-application-missionManager.md ...@@ -36,6 +36,8 @@ To call [missionManager](../reference/apis/js-apis-application-missionManager.md
You can use **missionManager** to manage missions, for example, listening for mission changes, obtaining mission information or snapshots, and clearing, locking, or unlocking missions. The sample code is as follows: You can use **missionManager** to manage missions, for example, listening for mission changes, obtaining mission information or snapshots, and clearing, locking, or unlocking missions. The sample code is as follows:
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager' import missionManager from '@ohos.app.ability.missionManager'
......
# ServiceExtensionAbility # ServiceExtensionAbility
[ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) is an ExtensionAbility component of the service type that provides extension capabilities related to background services. [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) is an ExtensionAbility component of the service type that provides extension capabilities related to background services.
...@@ -17,9 +18,9 @@ Each type of ExtensionAbility has its own context. ServiceExtensionAbility has [ ...@@ -17,9 +18,9 @@ Each type of ExtensionAbility has its own context. ServiceExtensionAbility has [
This topic describes how to use ServiceExtensionAbility in the following scenarios: This topic describes how to use ServiceExtensionAbility in the following scenarios:
- [Implementing a Background Service](#implementing-a-background-service) - [Implementing a Background Service (System Applications Only)](#implementing-a-background-service-system-applications-only)
- [Starting a Background Service](#starting-a-background-service) - [Starting a Background Service (System Applications Only)](#starting-a-background-service-system-applications-only)
- [Connecting to a Background Service](#connecting-to-a-background-service) - [Connecting to a Background Service](#connecting-to-a-background-service)
...@@ -32,36 +33,32 @@ This topic describes how to use ServiceExtensionAbility in the following scenari ...@@ -32,36 +33,32 @@ This topic describes how to use ServiceExtensionAbility in the following scenari
> - Third-party applications can connect to ServiceExtensionAbility provided by the system only when they gain focus in the foreground. > - Third-party applications can connect to ServiceExtensionAbility provided by the system only when they gain focus in the foreground.
## Implementing a Background Service ## Implementing a Background Service (System Applications Only)
This feature applies only to system applications. [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) provides the callbacks **onCreate()**, **onRequest()**, **onConnect()**, **onDisconnect()**, and **onDestory()**. Override them as required. The following figure shows the lifecycle of ServiceExtensionAbility. [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) provides the callbacks **onCreate()**, **onRequest()**, **onConnect()**, **onDisconnect()**, and **onDestory()**. Override them as required. The following figure shows the lifecycle of ServiceExtensionAbility.
**Figure 1** ServiceExtensionAbility lifecycle **Figure 1** ServiceExtensionAbility lifecycle
![ServiceExtensionAbility-lifecycle](figures/ServiceExtensionAbility-lifecycle.png) ![ServiceExtensionAbility-lifecycle](figures/ServiceExtensionAbility-lifecycle.png)
- **onCreate** - **onCreate**
This callback is triggered when a service is created for the first time. You can perform initialization operations, for example, registering a common event listener. This callback is triggered when a service is created for the first time. You can perform initialization operations, for example, registering a common event listener.
> **NOTE** > **NOTE**
> >
> If a service has been created, starting it again does not trigger the **onCreate()** callback. > If a service has been created, starting it again does not trigger the **onCreate()** callback.
- **onRequest** - **onRequest**
This callback is triggered when another component calls the **startServiceExtensionAbility()** method to start the service. After being started, the service runs in the background. This callback is triggered when another component calls the **startServiceExtensionAbility()** method to start the service. After being started, the service runs in the background.
- **onConnect** - **onConnect**
This callback is triggered when another component calls the **connectServiceExtensionAbility()** method to connect to the service. In this method, a remote proxy object (IRemoteObject) is returned, through which the client communicates with the server by means of RPC. This callback is triggered when another component calls the **connectServiceExtensionAbility()** method to connect to the service. In this method, a remote proxy object (IRemoteObject) is returned, through which the client communicates with the server by means of RPC.
- **onDisconnect** - **onDisconnect**
This callback is triggered when a component calls the **disconnectServiceExtensionAbility()** method to disconnect from the service. This callback is triggered when a component calls the **disconnectServiceExtensionAbility()** method to disconnect from the service.
- **onDestroy** - **onDestroy**
...@@ -167,9 +164,9 @@ To implement a background service, manually create a ServiceExtensionAbility com ...@@ -167,9 +164,9 @@ To implement a background service, manually create a ServiceExtensionAbility com
``` ```
## Starting a Background Service ## Starting a Background Service (System Applications Only)
This feature applies only to system applications. A system application uses the [startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartserviceextensionability) method to start a background service. The [onRequest()](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonrequest) callback is invoked, and the **Want** object passed by the caller is received through the callback. After the background service is started, its lifecycle is independent of that of the client. In other words, even if the client is destroyed, the background service can still run. Therefore, the background service must be stopped by calling [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) when its work is complete. Alternatively, another component can call [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability) to stop the background service. A system application uses the [startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartserviceextensionability) method to start a background service. The [onRequest()](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonrequest) callback is invoked, and the **Want** object passed by the caller is received through the callback. After the background service is started, its lifecycle is independent of that of the client. In other words, even if the client is destroyed, the background service can still run. Therefore, the background service must be stopped by calling [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) when its work is complete. Alternatively, another component can call [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability) to stop the background service.
> **NOTE** > **NOTE**
> >
......
# Starting a Remote PageAbility # Starting a Remote PageAbility (System Applications Only)
This feature applies only to system applications. The **startAbility()** method in the **featureAbility** class is used to start a remote PageAbility. The **startAbility()** method in the **featureAbility** class is used to start a remote PageAbility.
In addition to **'\@ohos.ability.featureAbility'**, you must import **'\@ohos.distributedHardware.deviceManager'**, which provides account-independent distributed device networking capabilities. Then you can use **getTrustedDeviceListSync** of the **DeviceManager** module to obtain the remote device ID and pass the remote device ID in the **want** parameter for starting the remote PageAbility. In addition to **'\@ohos.ability.featureAbility'**, you must import **'\@ohos.distributedHardware.deviceManager'**, which provides account-independent distributed device networking capabilities. Then you can use **getTrustedDeviceListSync** of the **DeviceManager** module to obtain the remote device ID and pass the remote device ID in the **want** parameter for starting the remote PageAbility.
......
...@@ -27,7 +27,7 @@ async function startServiceAbility() { ...@@ -27,7 +27,7 @@ async function startServiceAbility() {
``` ```
In the preceding code, **startAbility()** is used to start the ServiceAbility. In the preceding code, [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is used to start the ServiceAbility.
- If the ServiceAbility is not running, the system calls **onStart()** to initialize the ServiceAbility, and then calls **onCommand()** on the ServiceAbility. - If the ServiceAbility is not running, the system calls **onStart()** to initialize the ServiceAbility, and then calls **onCommand()** on the ServiceAbility.
......
# StaticSubscriberExtensionAbility Development
## Scenario Description
​The common event service provides two subscription modes: dynamic and static. In dynamic subscription mode, a subscriber calls an API during the running period to subscribe to common events. For details, see [Subscribing to Common Events](common-event-subscription.md). In static subscription mode, no common event subscription API is called. A common event is subscribed by configuring a declaration file and implementing a class that inherits from **StaticSubscriberExtensionAbility**. A static subscriber is started once it receives a target event (for example, a power-on event) published by the system or application. At the same time, the **onReceiveEvent** callback is triggered, in which you can implement the service logic. **The static subscriber APIs are system APIs and can be used only by system applications that have passed the system-level power consumption review.**
## How to Develop
1. Prerequisites
The application must meet the following requirements:
The application is a system application.
The application is developed using the full SDK.
The application's power consumption has passed the system-level power consumption review. If you want to use static subscription in the debugging phase, add the bundle name of your application to the system configuration file **/etc/static_subscriber_config.json**.
2. Declaring a Static Subscriber
To declare a static subscriber, create an ExtensionAbility, which is derived from the **StaticSubscriberExtensionAbility** class, in the project. The sample code is as follows:
```ts
import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility'
export default class StaticSubscriber extends StaticSubscriberExtensionAbility {
onReceiveEvent(event) {
console.log('onReceiveEvent, event:' + event.event);
}
}
```
You can implement service logic in the **onReceiveEvent** callback.
3. Project Configuration for a Static Subscriber
After writing the static subscriber code, configure the subscriber in the **module.json5** file. The configuration format is as follows:
```ts
{
"module": {
......
"extensionAbilities": [
{
"name": "StaticSubscriber",
"srcEntrance": "./ets/StaticSubscriber/StaticSubscriber.ts",
"description": "$string:StaticSubscriber_desc",
"icon": "$media:icon",
"label": "$string:StaticSubscriber_label",
"type": "staticSubscriber",
"visible": true,
"metadata": [
{
"name": "ohos.extension.staticSubscriber",
"resource": "$profile:subscribe"
}
]
}
]
......
}
}
```
Pay attention to the following fields in the JSON file:
**srcEntrance**: entry file path of the ExtensionAbility, that is, the file path of the static subscriber declared in Step 2.
**type**: ExtensionAbility type. For a static subscriber, set this field to **staticSubscriber**.
**metadata**: level-2 configuration file information of the ExtensionAbility. The configuration information varies according to the ExtensionAbility type. Therefore, you must use different config files to indicate the specific configuration. The **metadata** field contains two keywords: **name** and **resource**. The **name** field indicates the ExtensionAbility type name. For a static subscriber, declare the name as **ohos.extension.staticSubscriber** for successful identification. The **resource** field indicates the path that stores the ExtensionAbility configuration, which is customizable. In this example, the path is **resources/base/profile/subscribe.json**.
A level-2 configuration file pointed to by **metadata** must be in the following format:
```ts
{
"commonEvents": [
{
"name": "xxx",
"permission": "xxx",
"events":[
"xxx"
]
}
]
}
```
If the level-2 configuration file is not declared in this format, the file cannot be identified. The fields are described as follows:
**name**: name of the ExtensionAbility, which must be the same as the name of **extensionAbility** declared in **module.json5**.
**permission**: permission required by the publisher. If a publisher without the required permission attempts to publish an event, the event is regarded as invalid and will not be published.
**events**: list of subscribed target events
## Samples
For details about how to develop StaticSubscriberExtensionAbility, see [StaticSubscriber (ArkTS, API version 9, Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/StaticSubscriber).
...@@ -3,17 +3,16 @@ ...@@ -3,17 +3,16 @@
Based on the OpenHarmony application model, you can use any of the following ways to implement data synchronization between the UIAbility component and UI: Based on the OpenHarmony application model, you can use any of the following ways to implement data synchronization between the UIAbility component and UI:
- EventHub: The [base class Context](application-context-stage.md) provides the EventHub capability. It is implemented based on the publish/subscribe (pub/sub) pattern. Your application subscribes to an event and when the event occurs, receives a notification. - [Using EventHub for Data Synchronization](#using-eventhub-for-data-synchronization): The **EventHub** object is provided by the base class **Context**. Events are transferred using the publish/subscribe (pub/sub) pattern. Specifically, after subscribing to an event, your application will receive the event and process it accordingly when the event is published.
- [Using globalThis for Data Synchronization](#using-globalthis-for-data-synchronization): **globalThis** is a global object inside the ArkTS engine instance and can be accessed by components such as UIAbility, ExtensionAbility, and Page.
- globalThis: It is a global object accessible in the ArkTS engine instance. - [Using AppStorage or LocalStorage for Data Synchronization](#using-appstorage-or-localstorage-for-data-synchronization): ArkUI provides two application-level state management solutions: AppStorage and LocalStorage, which implement application- and UIAbility-level data synchronization, respectively.
- LocalStorage/AppStorage: See [State Management of Application-Level Variables](../quick-start/arkts-state-mgmt-application-level.md).
## Using EventHub for Data Synchronization ## Using EventHub for Data Synchronization
[EventHub](../reference/apis/js-apis-inner-application-eventHub.md) provides an event mechanism at the UIAbility or ExtensionAbility component level. Centered on the UIAbility or ExtensionAbility component, EventHub provides data communication capabilities for subscribing to, unsubscribing from, and triggering events. [EventHub](../reference/apis/js-apis-inner-application-eventHub.md) provides an event mechanism for the UIAbility or ExtensionAbility component so that they can subscribe to, unsubscribe from, and trigger events.
Before using EventHub, you must obtain an EventHub object, which is provided by the [base class Context](application-context-stage.md). This section uses EventHub as an example to describe how to implement data synchronization between the UIAbility component and the UI. Before using the APIs provided by **EventHub**, you must obtain an **EventHub** object, which is provided by the [base class Context](application-context-stage.md). This section uses EventHub as an example to describe how to implement data synchronization between the UIAbility component and the UI.
1. Call [eventHub.on()](../reference/apis/js-apis-inner-application-eventHub.md#eventhubon) in the UIAbility in either of the following ways to register a custom event **event1**. 1. Call [eventHub.on()](../reference/apis/js-apis-inner-application-eventHub.md#eventhubon) in the UIAbility in either of the following ways to register a custom event **event1**.
...@@ -81,17 +80,16 @@ Before using EventHub, you must obtain an EventHub object, which is provided by ...@@ -81,17 +80,16 @@ Before using EventHub, you must obtain an EventHub object, which is provided by
4. After **event1** is used, you can call [eventHub.off()](../reference/apis/js-apis-inner-application-eventHub.md#eventhuboff) to unsubscribe from the event. 4. After **event1** is used, you can call [eventHub.off()](../reference/apis/js-apis-inner-application-eventHub.md#eventhuboff) to unsubscribe from the event.
```ts ```ts
// context is the ability context of the UIAbility instance. // context is the ability-level context of the UIAbility instance.
this.context.eventHub.off('event1'); this.context.eventHub.off('event1');
``` ```
## Using globalThis for Data Synchronization ## Using globalThis for Data Synchronization
**globalThis** is a global object inside the [ArkTS engine instance](thread-model-stage.md) and can be used by UIAbility, ExtensionAbility, and Page inside the engine. Therefore, you can use **globalThis** for data synchronization. **globalThis** is a global object inside the [ArkTS engine instance](thread-model-stage.md) and can be used by UIAbility, ExtensionAbility, and Page inside the engine. Therefore, you can use **globalThis** for data synchronization.
**Figure 1** Using globalThis for data synchronization **Figure 1** Using globalThis for data synchronization
![globalThis1](figures/globalThis1.png) ![globalThis1](figures/globalThis1.png)
...@@ -99,18 +97,18 @@ Before using EventHub, you must obtain an EventHub object, which is provided by ...@@ -99,18 +97,18 @@ Before using EventHub, you must obtain an EventHub object, which is provided by
The following describes how to use **globalThis** in three scenarios. Precautions are provided as well. The following describes how to use **globalThis** in three scenarios. Precautions are provided as well.
- [Using globalThis Between UIAbility and Page](#using-globalthis-between-uiability-and-page) - [Using globalThis Between UIAbility and Page](#using-globalthis-between-uiability-and-page)
- [Using globalThis Between UIAbility and UIAbility](##using-globalthis-between-uiability-and-uiability) - [Using globalThis Between UIAbility and UIAbility](#using-globalthis-between-uiability-and-uiability)
- [Use globalThis Between UIAbility and ExtensionAbility](#using-globalthis-between-uiability-and-extensionability) - [Use globalThis Between UIAbility and ExtensionAbility](#using-globalthis-between-uiability-and-extensionability)
- [Precautions for Using globalThis](#precautions-for-using-globalthis) - [Precautions for Using globalThis](#precautions-for-using-globalthis)
### Using globalThis Between UIAbility and Page ### Using globalThis Between UIAbility and Page
You can use **globalThis** to bind attributes or methods to implement data synchronization between the UIAbility component and UI. For example, if you bind the **want** parameter in the UIAbility component, you can use the **want** parameter information on the UI corresponding to the UIAbility component. By binding attributes or methods to **globalThis**, you can implement data synchronization between the UIAbility component and UI. For example, if you bind the **want** parameter in the UIAbility component, you can use the **want** parameter information on the UI corresponding to the UIAbility component.
1. When **startAbility()** is called to start a UIAbility instance, the **onCreate()** callback is invoked, and the **want** parameter can be passed in the callback. Therefore, you can bind the **want** parameter to **globalThis**. 1. When [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called to start a UIAbility instance, the **onCreate()** callback is invoked, and the **want** parameter can be passed in the callback. Therefore, you can bind the **want** parameter to **globalThis**.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate(want, launch) { onCreate(want, launch) {
...@@ -144,29 +142,29 @@ You can use **globalThis** to bind attributes or methods to implement data synch ...@@ -144,29 +142,29 @@ You can use **globalThis** to bind attributes or methods to implement data synch
### Using globalThis Between UIAbility and UIAbility ### Using globalThis Between UIAbility and UIAbility
To implement data synchronization between two UIAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in AbilityA and obtain the data from AbilityB. To implement data synchronization between two UIAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in UIAbilityA and obtain the data from UIAbilityB.
1. AbilityA stores a string and binds it to globalThis. 1. UIAbilityA stores a string and binds it to globalThis.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
export default class AbilityA extends UIAbility { export default class UIAbilityA extends UIAbility {
onCreate(want, launch) { onCreate(want, launch) {
globalThis.entryAbilityStr = 'AbilityA'; // AbilityA stores the string "AbilityA" to globalThis. globalThis.entryAbilityStr = 'UIAbilityA'; // UIAbilityA stores the string "UIAbilityA" to globalThis.
// ... // ...
} }
} }
``` ```
2. Obtain the data from AbilityB. 2. Obtain the data from UIAbilityB.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
export default class AbilityB extends UIAbility { export default class UIAbilityB extends UIAbility {
onCreate(want, launch) { onCreate(want, launch) {
// AbilityB reads the name from globalThis and outputs it. // UIAbilityB reads name from globalThis and outputs it.
console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr); console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr);
// ... // ...
} }
...@@ -176,17 +174,17 @@ To implement data synchronization between two UIAbility components in the same a ...@@ -176,17 +174,17 @@ To implement data synchronization between two UIAbility components in the same a
### Using globalThis Between UIAbility and ExtensionAbility ### Using globalThis Between UIAbility and ExtensionAbility
To implement data synchronization between the UIAbility and ExtensionAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in AbilityA and obtain the data from ServiceExtensionAbility. To implement data synchronization between the UIAbility and ExtensionAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in UIAbilityA and obtain the data from ServiceExtensionAbility.
1. AbilityA stores a string and binds it to globalThis. 1. UIAbilityA stores a string and binds it to globalThis.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
export default class AbilityA extends UIAbility { export default class UIAbilityA extends UIAbility {
onCreate(want, launch) { onCreate(want, launch) {
// AbilityA stores the string "AbilityA" to globalThis. // UIAbilityA stores the string "UIAbilityA" to globalThis.
globalThis.entryAbilityStr = 'AbilityA'; globalThis.entryAbilityStr = 'UIAbilityA';
// ... // ...
} }
} }
...@@ -209,11 +207,11 @@ To implement data synchronization between the UIAbility and ExtensionAbility com ...@@ -209,11 +207,11 @@ To implement data synchronization between the UIAbility and ExtensionAbility com
### Precautions for Using globalThis ### Precautions for Using globalThis
**Figure 2** Precautions for globalThis **Figure 2** Precautions for globalThis
![globalThis2](figures/globalThis2.png) ![globalThis2](figures/globalThis2.png)
- In the stage model, all the UIAbility components in a process share one ArkTS engine instance. When using **globalThis**, do not store objects with the same name. For example, if AbilityA and AbilityB use **globalThis** to store two objects with the same name, the object stored earlier will be overwritten. - In the stage model, all the UIAbility components in a process share one ArkTS engine instance. When using **globalThis**, do not store objects with the same name. For example, if UIAbilityA and UIAbilityB use **globalThis** to store two objects with the same name, the object stored earlier will be overwritten.
- This problem does not occur in the FA model because each UIAbility component uses an independent engine. - This problem does not occur in the FA model because each UIAbility component uses an independent engine.
...@@ -221,20 +219,20 @@ To implement data synchronization between the UIAbility and ExtensionAbility com ...@@ -221,20 +219,20 @@ To implement data synchronization between the UIAbility and ExtensionAbility com
The following provides an example to describe the object overwritten problem in the stage model. The following provides an example to describe the object overwritten problem in the stage model.
1. In the AbilityA file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis**. 1. In the UIAbilityA file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis**.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
export default class AbilityA extends UIAbility { export default class UIAbilityA extends UIAbility {
onCreate(want, launch) { onCreate(want, launch) {
globalThis.context = this.context; // AbilityA stores the context in globalThis. globalThis.context = this.context; // UIAbilityA stores the context in globalThis.
// ... // ...
} }
} }
``` ```
2. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of Ability A. After the AbilityA instance is used, switch it to the background. 2. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of UIAbilityA. After the UIAbilityA instance is used, switch it to the background.
```ts ```ts
@Entry @Entry
...@@ -254,21 +252,21 @@ The following provides an example to describe the object overwritten problem in ...@@ -254,21 +252,21 @@ The following provides an example to describe the object overwritten problem in
} }
``` ```
3. In the AbilityB file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis** and has the same name as that in the AbilityA file. 3. In the UIAbilityB file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis** and has the same name as that in the UIAbilityA file.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
export default class AbilityB extends UIAbility { export default class UIAbilityB extends UIAbility {
onCreate(want, launch) { onCreate(want, launch) {
// AbilityB overwrites the context stored by AbilityA in globalThis. // UIAbilityB overwrites the context stored by UIAbilityA in globalThis.
globalThis.context = this.context; globalThis.context = this.context;
// ... // ...
} }
} }
``` ```
4. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of Ability B. The obtained **globalThis.context** is the value of [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) in AbilityB. 4. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of UIAbilityB. The obtained **globalThis.context** is the value of [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) in UIAbilityB.
```ts ```ts
@Entry @Entry
...@@ -288,27 +286,27 @@ The following provides an example to describe the object overwritten problem in ...@@ -288,27 +286,27 @@ The following provides an example to describe the object overwritten problem in
} }
``` ```
5. Switch the AbilityB instance to the background and switch the AbilityA instance to the foreground. In this case, AbilityA will not enter the **onCreate()** lifecycle again. 5. Switch the UIAbilityB instance to the background and switch the UIAbilityA instance to the foreground. In this case, UIAbilityA will not enter the **onCreate()** lifecycle again.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
export default class AbilityA extends UIAbility { export default class UIAbilityA extends UIAbility {
onCreate(want, launch) { // AbilityA will not enter this lifecycle. onCreate(want, launch) { // UIAbilityA will not enter this lifecycle.
globalThis.context = this.context; globalThis.context = this.context;
// ... // ...
} }
} }
``` ```
6. When the page of AbilityA is displayed, the obtained **globalThis.context** is [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) of AbilityB instead of AbilityA. An error occurs. 6. When the page of UIAbilityA is displayed, the obtained **globalThis.context** is [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) of UIAbilityB instead of UIAbilityA. An error occurs.
```ts ```ts
@Entry @Entry
@Component @Component
struct Index { struct Index {
onPageShow() { onPageShow() {
let ctx = globalThis.context; // The context in globalThis is the context of AbilityB. let ctx = globalThis.context; // The context in globalThis is the context of UIAbilityB.
let permissions=['com.example.permission']; let permissions=['com.example.permission'];
ctx.requestPermissionsFromUser(permissions,(result) => { // Using this object causes a process breakdown. ctx.requestPermissionsFromUser(permissions,(result) => { // Using this object causes a process breakdown.
console.info('requestPermissionsFromUser result:' + JSON.stringify(result)); console.info('requestPermissionsFromUser result:' + JSON.stringify(result));
...@@ -320,3 +318,7 @@ The following provides an example to describe the object overwritten problem in ...@@ -320,3 +318,7 @@ The following provides an example to describe the object overwritten problem in
} }
} }
``` ```
## Using AppStorage or LocalStorage for Data Synchronization
ArkUI provides AppStorage and LocalStorage to implement application- and UIAbility-level data synchronization, respectively. Both solutions can be used to manage the application state, enhance application performance, and improve user experience. The AppStorage is a global state manager and is applicable when multiple UIAbilities share the same state data. The LocalStorage is a local state manager that manages state data used inside a single UIAbility. They help you control the application state more flexibly and improve the maintainability and scalability of applications. For details, see [State Management of Application-Level Variables](../quick-start/arkts-state-mgmt-application-level.md).
...@@ -17,7 +17,7 @@ This topic describes the UIAbility interaction modes in the following scenarios. ...@@ -17,7 +17,7 @@ This topic describes the UIAbility interaction modes in the following scenarios.
- [Starting a Specified Page of UIAbility](#starting-a-specified-page-of-uiability) - [Starting a Specified Page of UIAbility](#starting-a-specified-page-of-uiability)
- [Using Ability Call to Implement UIAbility Interaction](#using-ability-call-to-implement-uiability-interaction) - [Using Ability Call to Implement UIAbility Interaction (System Applications Only)](#using-ability-call-to-implement-uiability-interaction-system-applications-only)
## Starting UIAbility in the Same Application ## Starting UIAbility in the Same Application
...@@ -26,7 +26,7 @@ This scenario is possible when an application contains multiple UIAbility compon ...@@ -26,7 +26,7 @@ This scenario is possible when an application contains multiple UIAbility compon
Assume that your application has two UIAbility components: EntryAbility and FuncAbility, either in the same module or different modules. You are required to start FuncAbility from EntryAbility. Assume that your application has two UIAbility components: EntryAbility and FuncAbility, either in the same module or different modules. You are required to start FuncAbility from EntryAbility.
1. In EntryAbility, call **startAbility()** to start UIAbility. The [want](../reference/apis/js-apis-app-ability-want.md) parameter is the entry parameter for starting the UIAbility instance. In the **want** parameter, **bundleName** indicates the bundle name of the application to start; **abilityName** indicates the name of the UIAbility to start; **moduleName** is required only when the target UIAbility belongs to a different module; **parameters** is used to carry custom information. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). 1. In EntryAbility, call [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start UIAbility. The [want](../reference/apis/js-apis-app-ability-want.md) parameter is the entry parameter for starting the UIAbility instance. In the **want** parameter, **bundleName** indicates the bundle name of the application to start; **abilityName** indicates the name of the UIAbility to start; **moduleName** is required only when the target UIAbility belongs to a different module; **parameters** is used to carry custom information. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
```ts ```ts
let wantInfo = { let wantInfo = {
...@@ -62,21 +62,27 @@ Assume that your application has two UIAbility components: EntryAbility and Func ...@@ -62,21 +62,27 @@ Assume that your application has two UIAbility components: EntryAbility and Func
} }
``` ```
3. To stop the **UIAbility** instance after the FuncAbility service is complete, call **terminateSelf()** in FuncAbility. 3. To stop the **UIAbility** instance after the FuncAbility service is complete, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) in FuncAbility.
```ts ```ts
// context is the ability context of the UIAbility instance to stop. // context is the ability-level context of the UIAbility instance to stop.
this.context.terminateSelf((err) => { this.context.terminateSelf((err) => {
// ... // ...
}); });
``` ```
> **NOTE**
>
> When [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) is called to stop the **UIAbility** instance, the snapshot of the instance is retained by default. That is, the mission corresponding to the instance is still displayed in Recents. If you do not want to retain the snapshot, set **removeMissionAfterTerminate** under the [abilities](../quick-start/module-configuration-file.md#abilities) tag to **true** in the [module.json5 file](../quick-start/module-configuration-file.md) of the corresponding UIAbility.
4. To stop all UIAbility instances of the application, call [killProcessBySelf()](../reference/apis/js-apis-inner-application-applicationContext.md#applicationcontextkillallprocesses9) of [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md) to stop all processes of the application.
## Starting UIAbility in the Same Application and Obtaining the Return Result ## Starting UIAbility in the Same Application and Obtaining the Return Result
When starting FuncAbility from EntryAbility, you want the result to be returned after the FuncAbility service is finished. For example, your application uses two independent UIAbility components to carry the entry and sign-in functionalities. After the sign-in operation is finished in the sign-in UIAbility, the sign-in result needs to be returned to the entry UIAbility. When starting FuncAbility from EntryAbility, you want the result to be returned after the FuncAbility service is finished. For example, your application uses two independent UIAbility components to carry the entry and sign-in functionalities. After the sign-in operation is finished in the sign-in UIAbility, the sign-in result needs to be returned to the entry UIAbility.
1. In EntryAbility, call **startAbilityForResult()** to start FuncAbility. Use **data** in the asynchronous callback to receive information returned after FuncAbility stops itself. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). 1. In EntryAbility, call [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to start FuncAbility. Use **data** in the asynchronous callback to receive information returned after FuncAbility stops itself. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
```ts ```ts
let wantInfo = { let wantInfo = {
...@@ -96,7 +102,7 @@ When starting FuncAbility from EntryAbility, you want the result to be returned ...@@ -96,7 +102,7 @@ When starting FuncAbility from EntryAbility, you want the result to be returned
}) })
``` ```
2. Call **terminateSelfWithResult()** to stop FuncAbility. Use the input parameter **abilityResult** to carry the information that FuncAbility needs to return to EntryAbility. 2. Call [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to stop FuncAbility. Use the input parameter **abilityResult** to carry the information that FuncAbility needs to return to EntryAbility.
```ts ```ts
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
...@@ -111,13 +117,13 @@ When starting FuncAbility from EntryAbility, you want the result to be returned ...@@ -111,13 +117,13 @@ When starting FuncAbility from EntryAbility, you want the result to be returned
}, },
}, },
} }
// context is the ability context of the callee UIAbility. // context is the ability-level context of the callee UIAbility.
this.context.terminateSelfWithResult(abilityResult, (err) => { this.context.terminateSelfWithResult(abilityResult, (err) => {
// ... // ...
}); });
``` ```
3. After FuncAbility stops itself, EntryAbility uses the **startAbilityForResult()** method to receive the information returned by FuncAbility. The value of **RESULT_CODE** must be the same as the preceding value. 3. After FuncAbility stops itself, EntryAbility uses [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to receive the information returned by FuncAbility. The value of **RESULT_CODE** must be the same as the preceding value.
```ts ```ts
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
...@@ -145,11 +151,11 @@ There are two ways to start **UIAbility**: [explicit and implicit](want-overview ...@@ -145,11 +151,11 @@ There are two ways to start **UIAbility**: [explicit and implicit](want-overview
- Explicit Want launch: This mode is used to start a determined UIAbility component of an application. You need to set **bundleName** and **abilityName** of the target application in the **want** parameter. - Explicit Want launch: This mode is used to start a determined UIAbility component of an application. You need to set **bundleName** and **abilityName** of the target application in the **want** parameter.
- Implicit Want launch: The user selects a UIAbility to start based on the matching conditions. That is, the UIAbility to start is not determined (the **abilityName** parameter is not specified). When the **startAbility()** method is called, the **want** parameter specifies a series of parameters such as [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) and [actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction). **entities** provides additional type information of the target UIAbility, such as the browser or video player. **actions** specifies the common operations to perform, such as viewing, sharing, and application details. Then the system analyzes the **want** parameter to find the right UIAbility to start. You usually do not know whether the target application is installed and what **bundleName** and **abilityName** of the target application are. Therefore, implicit Want launch is usually used to start the UIAbility of another application. - Implicit Want launch: The user selects a UIAbility to start based on the matching conditions. That is, the UIAbility to start is not determined (the **abilityName** parameter is not specified). When [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, the want parameter specifies a series of parameters such as **entities** and **actions**. **entities** provides category information of the target UIAbility, such as the browser or video player. **actions** specifies the common operations to perform, such as viewing, sharing, and application details. Then the system analyzes the **want** parameter to find the right UIAbility to start. You usually do not know whether the target application is installed and what **bundleName** and **abilityName** of the target application are. Therefore, implicit Want launch is usually used to start the UIAbility of another application.
This section describes how to start the UIAbility of another application through implicit Want. This section describes how to start the UIAbility of another application through implicit Want.
1. Install multiple document applications on your device. In the **module.json5** file of each UIAbility component, configure [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) and [actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) under **skills**. 1. Install multiple document applications on your device. In the [module.json5 file](../quick-start/module-configuration-file.md) of each UIAbility component, configure **entities** and **actions** under **skills**.
```json ```json
{ {
...@@ -196,13 +202,13 @@ This section describes how to start the UIAbility of another application through ...@@ -196,13 +202,13 @@ This section describes how to start the UIAbility of another application through
``` ```
The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select. The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select.
![uiability-intra-device-interaction](figures/uiability-intra-device-interaction.png) ![uiability-intra-device-interaction](figures/uiability-intra-device-interaction.png)
3. To stop the **UIAbility** instance after the document application is used, call **terminateSelf()**. 3. To stop the **UIAbility** instance after the document application is used, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself).
```ts ```ts
// context is the ability context of the UIAbility instance to stop. // context is the ability-level context of the UIAbility instance to stop.
this.context.terminateSelf((err) => { this.context.terminateSelf((err) => {
// ... // ...
}); });
...@@ -211,9 +217,9 @@ This section describes how to start the UIAbility of another application through ...@@ -211,9 +217,9 @@ This section describes how to start the UIAbility of another application through
## Starting UIAbility of Another Application and Obtaining the Return Result ## Starting UIAbility of Another Application and Obtaining the Return Result
If you want to obtain the return result when using implicit Want to start the UIAbility of another application, use the **startAbilityForResult()** method. An example scenario is that the main application needs to start a third-party payment application and obtain the payment result. If you want to obtain the return result when using implicit Want to start the UIAbility of another application, use [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult). An example scenario is that the main application needs to start a third-party payment application and obtain the payment result.
1. In the **module.json5** file of the UIAbility corresponding to the payment application, set [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) and [actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) under **skills**. 1. In the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility corresponding to the payment application, set **entities** and **actions** under **skills**.
```json ```json
{ {
...@@ -239,7 +245,7 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -239,7 +245,7 @@ If you want to obtain the return result when using implicit Want to start the UI
} }
``` ```
2. Call the **startAbilityForResult()** method to start the UIAbility of the payment application. Include **entities** and **actions** of the caller's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. Use **data** in the asynchronous callback to receive the information returned to the caller after the payment UIAbility stops itself. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select. 2. Call [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to start the UIAbility of the payment application. Include **entities** and **actions** of the caller's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. Use **data** in the asynchronous callback to receive the information returned to the caller after the payment UIAbility stops itself. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select.
```ts ```ts
let wantInfo = { let wantInfo = {
...@@ -259,7 +265,7 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -259,7 +265,7 @@ If you want to obtain the return result when using implicit Want to start the UI
}) })
``` ```
3. After the payment is finished, call the **terminateSelfWithResult()** method to stop the payment UIAbility and return the **abilityResult** parameter. 3. After the payment is finished, call [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to stop the payment UIAbility and return the **abilityResult** parameter.
```ts ```ts
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
...@@ -274,13 +280,13 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -274,13 +280,13 @@ If you want to obtain the return result when using implicit Want to start the UI
}, },
}, },
} }
// context is the ability context of the callee UIAbility. // context is the ability-level context of the callee UIAbility.
this.context.terminateSelfWithResult(abilityResult, (err) => { this.context.terminateSelfWithResult(abilityResult, (err) => {
// ... // ...
}); });
``` ```
4. Receive the information returned by the payment application in the callback of the **startAbilityForResult()** method. The value of **RESULT_CODE** must be the same as that returned by **terminateSelfWithResult()**. 4. Receive the information returned by the payment application in the callback of the [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) method. The value of **RESULT_CODE** must be the same as that returned by [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult).
```ts ```ts
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
...@@ -416,9 +422,9 @@ In summary, when a UIAbility instance of application A has been created and the ...@@ -416,9 +422,9 @@ In summary, when a UIAbility instance of application A has been created and the
> When the [launch type of the callee UIAbility](uiability-launch-type.md) is set to **standard**, a new instance is created each time the callee UIAbility is started. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback will not be invoked. > When the [launch type of the callee UIAbility](uiability-launch-type.md) is set to **standard**, a new instance is created each time the callee UIAbility is started. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback will not be invoked.
## Using Ability Call to Implement UIAbility Interaction ## Using Ability Call to Implement UIAbility Interaction (System Applications Only)
This feature applies only to system applications. Ability call is an extension of the UIAbility capability. It enables the UIAbility to be invoked by and communicate with external systems. The UIAbility invoked can be either started in the foreground or created and run in the background. You can use the ability call to implement data sharing between two UIAbility instances (caller ability and callee ability) through IPC. Ability call is an extension of the UIAbility capability. It enables the UIAbility to be invoked by and communicate with external systems. The UIAbility invoked can be either started in the foreground or created and run in the background. You can use the ability call to implement data sharing between two UIAbility instances (caller ability and callee ability) through IPC.
The core API used for the ability call is **startAbilityByCall**, which differs from **startAbility** in the following ways: The core API used for the ability call is **startAbilityByCall**, which differs from **startAbility** in the following ways:
...@@ -443,7 +449,7 @@ Ability call is usually used in the following scenarios: ...@@ -443,7 +449,7 @@ Ability call is usually used in the following scenarios:
The following figure shows the ability call process. The following figure shows the ability call process.
**Figure 1** Ability call process Figure 1 Ability call process
![call](figures/call.png) ![call](figures/call.png)
...@@ -490,24 +496,23 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -490,24 +496,23 @@ For the callee ability, implement the callback to receive data and the methods t
Set **launchType** of the callee ability to **singleton** in the **module.json5** file. Set **launchType** of the callee ability to **singleton** in the **module.json5** file.
| JSON Field| Description| | JSON Field| Description|
| -------- | -------- | | -------- | -------- |
| "launchType" | Ability launch type. Set this parameter to **singleton**.| | "launchType" | Ability launch type. Set this parameter to **singleton**.|
An example of the ability configuration is as follows: An example of the ability configuration is as follows:
```json
```json "abilities":[{
"abilities":[{ "name": ".CalleeAbility",
"name": ".CalleeAbility", "srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts",
"srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts", "launchType": "singleton",
"launchType": "singleton", "description": "$string:CalleeAbility_desc",
"description": "$string:CalleeAbility_desc", "icon": "$media:icon",
"icon": "$media:icon", "label": "$string:CalleeAbility_label",
"label": "$string:CalleeAbility_label", "visible": true
"visible": true }]
}] ```
```
2. Import the **UIAbility** module. 2. Import the **UIAbility** module.
...@@ -519,7 +524,6 @@ An example of the ability configuration is as follows: ...@@ -519,7 +524,6 @@ An example of the ability configuration is as follows:
The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string. The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string.
```ts ```ts
export default class MySequenceable { export default class MySequenceable {
num: number = 0 num: number = 0
...@@ -548,7 +552,6 @@ An example of the ability configuration is as follows: ...@@ -548,7 +552,6 @@ An example of the ability configuration is as follows:
The time to register a listener for the callee ability depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code is as follows: The time to register a listener for the callee ability depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code is as follows:
```ts ```ts
const TAG: string = '[CalleeAbility]'; const TAG: string = '[CalleeAbility]';
const MSG_SEND_METHOD: string = 'CallSendMsg'; const MSG_SEND_METHOD: string = 'CallSendMsg';
...@@ -598,7 +601,6 @@ An example of the ability configuration is as follows: ...@@ -598,7 +601,6 @@ An example of the ability configuration is as follows:
The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements. The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements.
```ts ```ts
// Register the onRelease() listener of the caller ability. // Register the onRelease() listener of the caller ability.
private regOnRelease(caller) { private regOnRelease(caller) {
......
...@@ -3,9 +3,11 @@ ...@@ -3,9 +3,11 @@
## Overview ## Overview
UIAbility has the UI and is mainly used for user interaction. UIAbility is a type of application component that provides the UI for user interaction.
UIAbility is the basic unit scheduled by the system and provides a window for applications to draw UIs. A UIAbility component can implement a functional module through multiple pages. Each UIAbility component instance corresponds to a mission in **Recents**. 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. You are advised to use one UIAbility component to carry the same functional module, with multiple pages (if necessary).
Each UIAbility component instance is displayed as a mission in Recents.
## Privacy Statement Configuration ## Privacy Statement Configuration
...@@ -32,8 +34,3 @@ To enable an application to properly use a UIAbility component, declare the UIAb ...@@ -32,8 +34,3 @@ To enable an application to properly use a UIAbility component, declare the UIAb
} }
} }
``` ```
> **NOTE**
>
> For the ability composition, see [Adding an Ability to a Module](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-ability-0000001218280664-V3).
...@@ -3,17 +3,16 @@ ...@@ -3,17 +3,16 @@
## Definition and Usage of Want ## Definition and Usage of Want
[Want](../reference/apis/js-apis-app-ability-want.md) is used as the carrier to transfer information between application components. It is used as a parameter of **startAbility()** to specify the startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. For example, when UIAbilityA starts UIAbilityB and needs to transfer some data to UIAbilityB, it can use Want to transfer the data. [Want](../reference/apis/js-apis-app-ability-want.md) is an object that transfers information between application components. It is often used as a parameter of [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability). For example, when UIAbilityA needs to start UIAbilityB and transfer some data to UIAbilityB, it can use the **want** parameter in **startAbility()** to transfer the data.
**Figure 1** Want usage **Figure 1** Want usage
![usage-of-want](figures/usage-of-want.png)
![usage-of-want](figures/usage-of-want.png)
## Types of Want ## Types of Want
- **Explicit Want**: A type of Want with **abilityName** and **bundleName** specified when starting an ability. - **Explicit Want**: If **abilityName** and **bundleName** are specified when starting an ability, explicit Want is used.
When there is an explicit object to process the request, the target ability can be started by specifying the bundle name and ability name in Want. Explicit Want is usually used to start a known ability. Explicit Want is usually used to start a known target ability in the same application. The target ability is started by specifying **bundleName** of the application where the target ability is located and **abilityName** in the **Want** object. When there is an explicit object to process the request, explicit Want is a simple and effective way to start the target ability.
```ts ```ts
let wantInfo = { let wantInfo = {
...@@ -23,8 +22,8 @@ ...@@ -23,8 +22,8 @@
} }
``` ```
- **Implicit Want**: A type of Want with **abilityName** unspecified when starting the ability. - **Implicit Want**: If **abilityName** is not specified when starting the ability, implicit Want is used.
Implicit Want can be used when the object used to process the request is unclear and the current application wants to use a capability (defined by the [skills tag](../quick-start/module-configuration-file.md#skills)) provided by another application. For example, you can use implicit Want to describe a request for opening a link, since you do not care which application is used to open the link. The system matches all applications that support the request. Implicit Want can be used when the object used to process the request is unclear and the current application wants to use a capability (defined by the [skills tag](../quick-start/module-configuration-file.md#skills)) provided by another application. The system matches all applications that declare to support the capability. For example, for a link open request, the system matches all applications that support the request and provides the available ones for users to select.
```ts ```ts
......
...@@ -100,7 +100,7 @@ The widget provider development based on the [stage model](stage-model-developme ...@@ -100,7 +100,7 @@ The widget provider development based on the [stage model](stage-model-developme
- [Configuring the Widget Configuration File](#configuring-the-widget-configuration-file): Configure the application configuration file **module.json5** and profile configuration file. - [Configuring the Widget Configuration File](#configuring-the-widget-configuration-file): Configure the application configuration file **module.json5** and profile configuration file.
- [Persistently Storing Widget Data](#persistently-storing-widget-data): Perform persistent management on widget information. - [Persistently Storing Widget Data](#persistently-storing-widget-data): This operation is a form of widget data exchange.
- [Updating Widget Data](#updating-widget-data): Call **updateForm()** to update the information displayed on a widget. - [Updating Widget Data](#updating-widget-data): Call **updateForm()** to update the information displayed on a widget.
...@@ -597,3 +597,13 @@ The following is an example: ...@@ -597,3 +597,13 @@ The following is an example:
}; };
``` ```
## Restrictions
To minimize the abuse of **FormExtensionAbility** by third-party applications, the following APIs cannot be invoked in **FormExtensionAbility**:
- @ohos.ability.particleAbility.d.ts
- @ohos.backgroundTaskManager.d.ts
- @ohos.resourceschedule.backgroundTaskManager.d.ts
- @ohos.multimedia.camera.d.ts
- @ohos.multimedia.audio.d.ts
- @ohos.multimedia.media.d.ts
# WindowExtensionAbility
[WindowExtensionAbility](../reference/apis/js-apis-application-windowExtensionAbility.md) is a type of ExtensionAbility component that allows a system application to be embedded in and displayed over another application.
The WindowExtensionAbility component must be used together with the [AbilityComponent](../reference/arkui-ts/ts-container-ability-component.md) to process services of the started application. WindowExtensionAbility is run in connection mode. A system application must use the AbilityComponent to start the WindowExtensionAbility component.
Each ExtensionAbility has its own context. For WindowExtensionAbility,
the context is [WindowExtensionContext](../reference/apis/js-apis-inner-application-windowExtensionContext.md).
> **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](../../application-dev/quick-start/full-sdk-switch-guide.md).
>
## Setting an Embedded Ability (System Applications Only)
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 **onConnect()** callback is invoked when the AbilityComponent corresponding to the window connects to the ability.
- The **onDisconnect()** callback is invoked when the AbilityComponent disconnects from the ability.
**How to Develop**
To implement an embedded application, manually create a WindowExtensionAbility in DevEco Studio as follows:
1. In the **ets** directory of the **Module** project, right-click and choose **New > Directory** to create a directory named **WindowExtAbility**.
2. Right-click the **WindowExtAbility** directory, and choose **New > TypeScript File** to create a file named **WindowExtAbility.ts**.
3. Open the **WindowExtAbility.ts** file and import the dependency package of **WindowExtensionAbility**. Customize a class that inherits from **WindowExtensionAbility** and implement the **onWindowReady()**, **onConnect()**, and **onDisconnect()** lifecycle callbacks.
```ts
import Extension from '@ohos.application.WindowExtensionAbility'
export default class WindowExtAbility extends Extension {
onWindowReady(window) {
window.loadContent('WindowExtAbility/pages/index1').then(() => {
window.getProperties().then((pro) => {
console.log("WindowExtension " + JSON.stringify(pro));
})
window.show();
})
}
onConnect(want) {
console.info('JSWindowExtension onConnect ' + want.abilityName);
}
onDisconnect(want) {
console.info('JSWindowExtension onDisconnect ' + want.abilityName);
}
}
```
4. Register the WindowExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the **Module** project. Set **type** to **"window"** and **srcEntrance** to the code path of the ExtensionAbility component.
```json
{
"module": {
"extensionAbilities": [
{
"name": "WindowExtAbility",
"srcEntrance": "./ets/WindowExtAbility/WindowExtAbility.ts",
"icon": "$media:icon",
"description": "WindowExtension",
"type": "window",
"visible": true,
}
],
}
}
```
## Starting an Embedded Ability (System Applications Only)
System applications can load the created WindowExtensionAbility through the AbilityComponent.
**How to Develop**
1. To connect to an embedded application, add the AbilityComponent to the corresponding pages in the DevEco Studio project.
2. Set **bundleName** and **abilityName** in the AbilityComponent.
3. Set the width and height. The sample code is as follows:
```ts
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
AbilityComponent({ abilityName: "WindowExtAbility", bundleName: "com.example.WindowExtAbility"})
.width(500)
.height(500)
}
.width('100%')
}
.height('100%')
.backgroundColor(0x64BB5c)
}
}
```
...@@ -108,7 +108,7 @@ You write a UI test script based on the unit test framework, adding the invoking ...@@ -108,7 +108,7 @@ You write a UI test script based on the unit test framework, adding the invoking
In this example, the UI test script is written based on the preceding unit test script. First, add the dependency package, as shown below: In this example, the UI test script is written based on the preceding unit test script. First, add the dependency package, as shown below:
```js ```js
import {UiDriver,BY,UiComponent,MatchPattern} from '@ohos.uitest' import {Driver,ON,Component,MatchPattern} from '@ohos.uitest'
``` ```
Then, write specific test code. Specifically, implement the click action on the started application page and add checkpoint check cases. Then, write specific test code. Specifically, implement the click action on the started application page and add checkpoint check cases.
...@@ -131,16 +131,16 @@ export default function abilityTest() { ...@@ -131,16 +131,16 @@ export default function abilityTest() {
expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility'); expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility');
}) })
//ui test code //ui test code
//init uidriver //init driver
var driver = await UiDriver.create(); var driver = await Driver.create();
await driver.delayMs(1000); await driver.delayMs(1000);
//find button by text 'Next' //find button on text 'Next'
var button = await driver.findComponent(BY.text('Next')); var button = await driver.findComponent(ON.text('Next'));
//click button //click button
await button.click(); await button.click();
await driver.delayMs(1000); await driver.delayMs(1000);
//check text //check text
await driver.assertComponentExist(BY.text('after click')); await driver.assertComponentExist(ON.text('after click'));
await driver.pressBack(); await driver.pressBack();
done(); done();
}) })
...@@ -195,14 +195,15 @@ The framework supports multiple test case execution modes, which are triggered b ...@@ -195,14 +195,15 @@ The framework supports multiple test case execution modes, which are triggered b
| itName | Test case to be executed. | {itName} | -s itName testAttributeIt | | itName | Test case to be executed. | {itName} | -s itName testAttributeIt |
| timeout | Timeout interval for executing a test case. | Positive integer (unit: ms). If no value is set, the default value 5000 is used. | -s timeout 15000 | | timeout | Timeout interval for executing a test case. | Positive integer (unit: ms). If no value is set, the default value 5000 is used. | -s timeout 15000 |
| breakOnError | Whether to enable break-on-error mode. When this mode is enabled, the test execution process exits if a test assertion error or any other error occurs.| **true**/**false** (default value) | -s breakOnError true | | breakOnError | Whether to enable break-on-error mode. When this mode is enabled, the test execution process exits if a test assertion error or any other error occurs.| **true**/**false** (default value) | -s breakOnError true |
| random | Whether to execute test cases in random sequence.| **true**/**false** (default value) | -s random true |
| testType | Type of the test case to be executed. | function, performance, power, reliability, security, global, compatibility, user, standard, safety, resilience| -s testType function | | testType | Type of the test case to be executed. | function, performance, power, reliability, security, global, compatibility, user, standard, safety, resilience| -s testType function |
| level | Level of the test case to be executed. | 0, 1, 2, 3, 4 | -s level 0 | | level | Level of the test case to be executed. | 0, 1, 2, 3, 4 | -s level 0 |
| size | Size of the test case to be executed. | small, medium, large | -s size small | | size | Size of the test case to be executed. | small, medium, large | -s size small |
| stress | Number of times that the test case is executed. | Positive integer | -s stress 1000 | | stress | Number of times that the test case is executed. | Positive integer | -s stress 1000 |
**Running Commands** **Running Commands**
> Configure hdc-related environment variables, and then perform the following: > Before running commands in the CLI, make sure hdc-related environment variables have been configured.
- Open the CLI. - Open the CLI.
- Run the **aa test** commands. - Run the **aa test** commands.
......
...@@ -40,7 +40,7 @@ There are two roles in **DataShare**: ...@@ -40,7 +40,7 @@ There are two roles in **DataShare**:
- **onCreate** - **onCreate**
Called by the server to initialize service logic when the **DataShare** client connects to the **DataShareExtensionAbility** server. Called by the server to initialize service logic when the **DataShare** client connects to the **DataShareExtensionAbility** server.
- **insert** - **insert**
...@@ -64,11 +64,11 @@ There are two roles in **DataShare**: ...@@ -64,11 +64,11 @@ There are two roles in **DataShare**:
- **normalizeUri** - **normalizeUri**
Converts the URI provided by the client to the URI used by the server. This API can be overridden as required. Converts the URI provided by the client to the URI used by the server.
- **denormalizeUri** - **denormalizeUri**
Converts the URI used by the server to the initial URI passed by the client. This API can be overridden as required. Converts the URI used by the server to the initial URI passed by the client.
Before implementing a **DataShare** service, create a **DataShareExtensionAbility** object in the DevEco Studio project as follows: Before implementing a **DataShare** service, create a **DataShareExtensionAbility** object in the DevEco Studio project as follows:
...@@ -76,7 +76,7 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -76,7 +76,7 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
2. Right-click the **DataShareAbility** directory, and choose **New > TypeScript File** to create a file named **DataShareAbility.ts**. 2. Right-click the **DataShareAbility** directory, and choose **New > TypeScript File** to create a file named **DataShareAbility.ts**.
3. In the **DataShareAbility.ts** file, import the **DataShareExtensionAbility** and other dependencies. 3. In the **DataShareAbility.ts** file, import **DataShareExtensionAbility** and other dependencies.
```ts ```ts
import Extension from '@ohos.application.DataShareExtensionAbility'; import Extension from '@ohos.application.DataShareExtensionAbility';
...@@ -85,9 +85,9 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -85,9 +85,9 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
``` ```
5. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**. 4. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**.
6. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network. 5. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network.
```ts ```ts
const DB_NAME = "DB00.db"; const DB_NAME = "DB00.db";
...@@ -95,13 +95,13 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -95,13 +95,13 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
+ TBL_NAME + TBL_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)"; + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)";
let rdbStore; let rdbStore;
let result; let result;
export default class DataShareExtAbility extends Extension { export default class DataShareExtAbility extends Extension {
private rdbStore_; private rdbStore_;
// Override onCreate(). // Override onCreate().
onCreate(want, callback) { onCreate(want, callback) {
result = this.context.cacheDir + '/datashare.txt'; result = this.context.cacheDir + '/datashare.txt';
...@@ -114,12 +114,12 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -114,12 +114,12 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err)); console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err));
}); });
if (callbakc) { if (callback) {
callback(); callback();
} }
}); });
} }
// Override query(). // Override query().
query(uri, predicates, columns, callback) { query(uri, predicates, columns, callback) {
if (predicates == null || predicates == undefined) { if (predicates == null || predicates == undefined) {
...@@ -143,17 +143,18 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -143,17 +143,18 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
}; };
``` ```
7. Define **DataShareExtensionAbility** in **module.json5**. 6. Define **DataShareExtensionAbility** in **module.json5**.
| Field| Description | | Field | Description | Mandatory |
| ------------ | ------------------------------------------------------------ | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | | "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | Yes |
| "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template.| | "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template. | Yes |
| "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. | | "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. | Yes |
| "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**.| | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**. | Yes |
| "metadata" | Configuration for silent access, including the **name** and **resource** fields. <br/>The **name** field identifies the configuration, which has a fixed value of **ohos.extension.dataShare**. <br/>The **resource** field has a fixed value of **$profile:data_share_config**, which indicates that the profile name is **data_share_config.json**. | **metadata** is mandatory when the ability launch type is **singleton**. For details about the ability launch type, see **launchType** in the [Internal Structure of the abilities Attribute](../quick-start/module-structure.md#internal-structure-of-the-abilities-attribute). |
**module.json5 example** **module.json5 example**
```json ```json
"extensionAbilities": [ "extensionAbilities": [
{ {
...@@ -163,10 +164,44 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -163,10 +164,44 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
"description": "$string:description_datashareextability", "description": "$string:description_datashareextability",
"type": "dataShare", "type": "dataShare",
"uri": "datashare://com.samples.datasharetest.DataShare", "uri": "datashare://com.samples.datasharetest.DataShare",
"visible": true "visible": true,
"metadata": [{"name": "ohos.extension.dataShare", "resource": "$profile:data_share_config"}]
} }
] ]
``` ```
**data_share_config.json Description**
| Field | Description | Mandatory |
| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| "tableConfig" | Label configuration. | Yes |
| "uri" | Range for which the configuration takes effect. The URI supports the following formats in descending order by priority:<br>- **\***: indicates all databases and tables.<br>- **datashare:///{bundleName\}/{moduleName\}/{storeName\}**: specifies a database.<br>- **datashare:///{bundleName\}/{moduleName\}/{storeName\}/{tableName\}**: specifies a table.<br>If URIs of different formats are configured, only the URI with higher priority takes effect. | Yes |
| "crossUserMode" | Whether data is shared by multiple users. The value **1** means to share data between multiple users, and the value **2** means the opposite. | **crossUserMode** is mandatory when the ability launch type is **singleton**. For details about the ability launch type, see **launchType** in the [Internal Structure of the abilities Attribute](../quick-start/module-structure.md#internal-structure-of-the-abilities-attribute). |
| "writePermission" | Write permission required for silent access. | No |
| "readPermission" | Read permission required for silent access. | No |
**data_share_config.json Example**
```json
"tableConfig": [
{
"uri": "*",
"writePermission": "ohos.permission.xxx"
},
{
"uri": "datashare:///com.acts.datasharetest/entry/DB00",
"crossUserMode": 1,
"writePermission": "ohos.permission.xxx",
"readPermission": "ohos.permission.xxx"
},
{
"uri": "datashare:///com.acts.datasharetest/entry/DB00/TBL00",
"crossUserMode": 2
}
]
```
### Data Consumer Application Development ### Data Consumer Application Development
...@@ -182,7 +217,7 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -182,7 +217,7 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
```ts ```ts
// Different from the URI defined in the module.json5 file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). // Different from the URI defined in the module.json5 file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/).
let dseUri = ("datashare:///com.samples.datasharetest.DataShare"); let dseUri = ('datashare:///com.samples.datasharetest.DataShare');
``` ```
3. Create a **DataShareHelper** instance. 3. Create a **DataShareHelper** instance.
...@@ -211,18 +246,18 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -211,18 +246,18 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
let valArray = ['*']; let valArray = ['*'];
// Insert a piece of data. // Insert a piece of data.
dsHelper.insert(dseUri, valuesBucket, (err, data) => { dsHelper.insert(dseUri, valuesBucket, (err, data) => {
console.log("dsHelper insert result: " + data); console.log('dsHelper insert result: ' + data);
}); });
// Update data. // Update data.
dsHelper.update(dseUri, predicates, updateBucket, (err, data) => { dsHelper.update(dseUri, predicates, updateBucket, (err, data) => {
console.log("dsHelper update result: " + data); console.log('dsHelper update result: ' + data);
}); });
// Query data. // Query data.
dsHelper.query(dseUri, predicates, valArray, (err, data) => { dsHelper.query(dseUri, predicates, valArray, (err, data) => {
console.log("dsHelper query result: " + data); console.log('dsHelper query result: ' + data);
}); });
// Delete data. // Delete data.
dsHelper.delete(dseUri, predicates, (err, data) => { dsHelper.delete(dseUri, predicates, (err, data) => {
console.log("dsHelper delete result: " + data); console.log('dsHelper delete result: ' + data);
}); });
``` ```
...@@ -19,7 +19,7 @@ Call **createDistributedObject()** to create a distributed data object instance. ...@@ -19,7 +19,7 @@ Call **createDistributedObject()** to create a distributed data object instance.
| Bundle Name| API| Description| | Bundle Name| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>- **source**: attributes of the distributed data object to set.<br>- **DistributedObject**: returns the distributed data object created. | | ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>- **source**: attributes of the distributed data object to create.<br>- **DistributedObject**: returns the distributed data object created.|
### Generating a Session ID ### Generating a Session ID
...@@ -91,10 +91,9 @@ The following example shows how to implement distributed data object synchroniza ...@@ -91,10 +91,9 @@ The following example shows how to implement distributed data object synchroniza
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
``` ```
2. Apply for the permission. 2. Apply for the permission.
Add the permissions required (FA model) to the **config.json** file. Add the required permission (FA model) to the **config.json** file.
```json ```json
{ {
...@@ -112,18 +111,43 @@ The following example shows how to implement distributed data object synchroniza ...@@ -112,18 +111,43 @@ The following example shows how to implement distributed data object synchroniza
This permission must also be granted by the user when the application is started for the first time. This permission must also be granted by the user when the application is started for the first time.
```js ```js
// FA model
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
function grantPermission() { function grantPermission() {
console.info('grantPermission'); console.info('grantPermission');
let context = featureAbility.getContext(); let context = featureAbility.getContext();
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
console.info(`result.requestCode=${result.requestCode}`) console.info(`requestPermissionsFromUser CallBack`);
}) })
console.info('end grantPermission'); console.info('end grantPermission');
} }
grantPermission();
```
```ts
// Stage model
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
context = this.context;
}
}
function grantPermission() {
let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC'];
context.requestPermissionsFromUser(permissions).then((data) => {
console.info('success: ${data}');
}).catch((error) => {
console.error('failed: ${error}');
});
}
grantPermission(); grantPermission();
``` ```
...@@ -139,10 +163,10 @@ The following example shows how to implement distributed data object synchroniza ...@@ -139,10 +163,10 @@ The following example shows how to implement distributed data object synchroniza
}); });
let sessionId = distributedObject.genSessionId(); let sessionId = distributedObject.genSessionId();
``` ```
4. Add the distributed data object instance to a network for data synchronization. The data objects in the synchronization network include the local and remote objects. 4. Add the distributed data object instance to a network for data synchronization. The data objects in the synchronization network include the local and remote objects.
```js ```js
// Local object // Local object
let localObject = distributedObject.createDistributedObject({ let localObject = distributedObject.createDistributedObject({
name: "jack", name: "jack",
...@@ -164,7 +188,7 @@ The following example shows how to implement distributed data object synchroniza ...@@ -164,7 +188,7 @@ The following example shows how to implement distributed data object synchroniza
// After learning that the local device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18. // After learning that the local device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18.
remoteObject.setSessionId(sessionId); remoteObject.setSessionId(sessionId);
``` ```
5. Observe the data changes of the distributed data object. You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be invoked to return the data changes. 5. Observe the data changes of the distributed data object. You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be invoked to return the data changes.
```js ```js
...@@ -202,33 +226,29 @@ The following example shows how to implement distributed data object synchroniza ...@@ -202,33 +226,29 @@ The following example shows how to implement distributed data object synchroniza
localObject.parent.mother = "mom"; localObject.parent.mother = "mom";
``` ```
7. Access the distributed data object. 7. Access the distributed data object.<br>Obtain the distributed data object attributes, which are the latest data on the network.
Obtain the distributed data object attributes, which are the latest data on the network.
```js ```js
console.info("name " + localObject["name"]); console.info("name " + localObject["name"]);
``` ```
8. Unsubscribe from data changes. You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered. 8. Unsubscribe from data changes. You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered.
```js ```js
// Unregister the specified data change callback. // Unregister the specified data change callback.
localObject.off("change", changeCallback); localObject.off("change", changeCallback);
// Unregister all data change callbacks. // Unregister all data change callbacks.
localObject.off("change"); localObject.off("change");
``` ```
9. Subscribe to status changes of this distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline. 9. Subscribe to status changes of this distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline.
```js ```js
function statusCallback(sessionId, networkId, status) { function statusCallback(sessionId, networkId, status) {
this.response += "status changed " + sessionId + " " + status + " " + networkId; this.response += "status changed " + sessionId + " " + status + " " + networkId;
} }
localObject.on("status", this.statusCallback); localObject.on("status", this.statusCallback);
``` ```
10. Save a distributed data object and delete it. 10. Save a distributed data object and delete it.
```js ```js
...@@ -247,20 +267,16 @@ console.info("name " + localObject["name"]); ...@@ -247,20 +267,16 @@ console.info("name " + localObject["name"]);
console.info("revokeSave failed."); console.info("revokeSave failed.");
}); });
``` ```
11. Unsubscribe from the status changes of this distributed data object. You can specify the callback to unregister. If you do not specify the callback, this API unregisters all status change callbacks of this distributed data object.
11. Unsubscribe from the status changes of the distributed data object.
You can specify the callback to unregister. If you do not specify the callback, all status change callbacks of this distributed data object will be unregistered.
```js ```js
// Unregister the specified status change callback. // Unregister the specified status change callback.
localObject.off("status", this.statusCallback); localObject.off("status", this.statusCallback);
// Unregister all status change callbacks. // Unregister all status change callbacks.
localObject.off("status"); localObject.off("status");
``` ```
12. Remove the distributed data object from the synchronization network. The data changes on the local object will not be synchronized to the removed distributed data object. 12. Remove the distributed data object from the synchronization network. The data changes on the local object will not be synchronized to the removed distributed data object.
```js ```js
localObject.setSessionId(""); localObject.setSessionId("");
``` ```
...@@ -13,7 +13,7 @@ For details about the APIs, see [Distributed KV Store](../reference/apis/js-apis ...@@ -13,7 +13,7 @@ For details about the APIs, see [Distributed KV Store](../reference/apis/js-apis
| API | Description | | API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KvManager** object for database management. | | createKVManager(config: KVManagerConfig): KVManager | Creates a **KvManager** object for database management. |
| getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Creates and obtains a KV store.| | getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Creates and obtains a KV store.|
| put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array\|string\|number\|boolean): Promise&lt;void> | Inserts and updates data. | | put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array\|string\|number\|boolean): Promise&lt;void> | Inserts and updates data. |
| delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. | | delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. |
...@@ -117,16 +117,10 @@ The following uses a single KV store as an example to describe the development p ...@@ -117,16 +117,10 @@ The following uses a single KV store as an example to describe the development p
bundleName: 'com.example.datamanagertest', bundleName: 'com.example.datamanagertest',
context:context, context:context,
} }
distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) { kvManager = distributedKVStore.createKVManager(kvManagerConfig);
if (err) { console.log("Created KVManager successfully");
console.error(`Failed to create KVManager. code is ${err.code},message is ${err.message}`);
return;
}
console.log('Created KVManager successfully');
kvManager = manager;
});
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`Failed to create KVManager. Code is ${e.code}, message is ${e.message}`);
} }
``` ```
...@@ -150,14 +144,14 @@ The following uses a single KV store as an example to describe the development p ...@@ -150,14 +144,14 @@ The following uses a single KV store as an example to describe the development p
}; };
kvManager.getKVStore('storeId', options, function (err, store) { kvManager.getKVStore('storeId', options, function (err, store) {
if (err) { if (err) {
console.error(`Failed to get KVStore: code is ${err.code},message is ${err.message}`); console.error(`Failed to get KVStore: code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.log('Obtained KVStore successfully'); console.log('Obtained KVStore successfully');
kvStore = store; kvStore = store;
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred. Code is ${e.code}, message is ${e.message}`);
} }
``` ```
...@@ -175,7 +169,7 @@ The following uses a single KV store as an example to describe the development p ...@@ -175,7 +169,7 @@ The following uses a single KV store as an example to describe the development p
console.log(`dataChange callback call data: ${data}`); console.log(`dataChange callback call data: ${data}`);
}); });
}catch(e){ }catch(e){
console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occured. Code is ${e.code}, message is ${e.message}`);
} }
``` ```
...@@ -192,13 +186,13 @@ The following uses a single KV store as an example to describe the development p ...@@ -192,13 +186,13 @@ The following uses a single KV store as an example to describe the development p
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
if (err != undefined) { if (err != undefined) {
console.error(`Failed to put.code is ${err.code},message is ${err.message}`); console.error(`Failed to put data. Code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.log('Put data successfully'); console.log("Put data successfully");
}); });
}catch (e) { }catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred. Code is ${e.code}, message is ${e.message}`);
} }
``` ```
...@@ -215,20 +209,20 @@ The following uses a single KV store as an example to describe the development p ...@@ -215,20 +209,20 @@ The following uses a single KV store as an example to describe the development p
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
if (err != undefined) { if (err != undefined) {
console.error(`Failed to put.code is ${err.code},message is ${err.message}`); console.error(`Failed to put data. Code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.log('Put data successfully'); console.log("Put data successfully");
kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) { kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) {
if (err != undefined) { if (err != undefined) {
console.error(`Failed to get data.code is ${err.code},message is ${err.message}`); console.error(`Failed to obtain data. Code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.log(`Obtained data successfully:${data}`); console.log(`Obtained data successfully:${data}`);
}); });
}); });
}catch (e) { }catch (e) {
console.error(`Failed to get.code is ${e.code},message is ${e.message}`); console.error(`Failed to obtain data. Code is ${e.code}, message is ${e.message}`);
} }
``` ```
...@@ -262,7 +256,7 @@ The following uses a single KV store as an example to describe the development p ...@@ -262,7 +256,7 @@ The following uses a single KV store as an example to describe the development p
// 1000 indicates that the maximum delay is 1000 ms. // 1000 indicates that the maximum delay is 1000 ms.
kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000); kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000);
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred. code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred. Code is ${e.code}, message is ${e.message}`);
} }
} }
}); });
......
...@@ -114,21 +114,19 @@ You can use the following APIs to delete a **Preferences** instance or data file ...@@ -114,21 +114,19 @@ You can use the following APIs to delete a **Preferences** instance or data file
```ts ```ts
// Obtain the context. // Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
let preferences = null; let preferences = null;
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage) {
context = this.context; let promise = data_preferences.getPreferences(this.context, 'mystore');
promise.then((pref) => {
preferences = pref;
}).catch((err) => {
console.info("Failed to get the preferences.");
})
} }
} }
let promise = data_preferences.getPreferences(context, 'mystore');
promise.then((pref) => {
preferences = pref;
}).catch((err) => {
console.info("Failed to get the preferences.");
})
``` ```
3. Write data. 3. Write data.
......
...@@ -37,14 +37,14 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -37,14 +37,14 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
- **Updating Data** - **Updating Data**
Call **update()** to update data based on the passed data and the conditions specified by **RdbPredicates**. If the data is updated, the number of rows of the updated data will be returned; otherwise, **0** will be returned. Call **update()** to pass the new data and specify the update conditions by using **RdbPredicates**. If the data is updated, the number of rows of the updated data will be returned; otherwise, **0** will be returned.
**Table 3** API for updating data **Table 3** API for updating data
| Class | API | Description | | Class | API | Description |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStore | update(values: ValuesBucket, predicates: RdbPredicates): Promise&lt;number&gt; | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the number of rows updated.<br>- **values**: data to update, which is stored in **ValuesBucket**.<br>- **predicates**: conditions for updating data. | | RdbStore | update(values: ValuesBucket, predicates: RdbPredicates): Promise&lt;number&gt; | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the number of rows updated.<br>- **values**: data to update, which is stored in **ValuesBucket**.<br>- **predicates**: conditions for updating data.|
- **Deleting Data** - **Deleting Data**
...@@ -55,7 +55,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -55,7 +55,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
| Class | API | Description | | Class | API | Description |
| ---------- | ---------------------------------------------------------- | ------------------------------------------------------------ | | ---------- | ---------------------------------------------------------- | ------------------------------------------------------------ |
| RdbStore | delete(predicates: RdbPredicates): Promise&lt;number&gt; | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the number of rows deleted.<br>- **predicates**: conditions for deleting data. | | RdbStore | delete(predicates: RdbPredicates): Promise&lt;number&gt; | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the number of rows deleted.<br>- **predicates**: conditions for deleting data.|
- **Querying Data** - **Querying Data**
...@@ -201,76 +201,81 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -201,76 +201,81 @@ You can obtain the distributed table name for a remote device based on the local
FA model: FA model:
```js ```js
import data_rdb from '@ohos.data.relationalStore' import relationalStore from '@ohos.data.relationalStore'
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
var store;
// Obtain the context. // Obtain the context.
let context = featureAbility.getContext() let context = featureAbility.getContext();
const STORE_CONFIG = { const STORE_CONFIG = {
name: "RdbTest.db", name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1 securityLevel: relationalStore.SecurityLevel.S1
} };
// Assume that the current RDB store version is 3. // Assume that the current RDB store version is 3.
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { relationalStore.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
// When an RDB store is created, the default version is 0. store = rdbStore;
if (rdbStore.version == 0) { // When an RDB store is created, the default version is 0.
rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null) if (store.version == 0) {
// Set the RDB store version. The input parameter must be an integer greater than 0. store.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null);
rdbStore.version = 3 // Set the RDB store version. The input parameter must be an integer greater than 0.
} store.version = 3;
}
// When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2. // When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2.
if (rdbStore.version != 3 && rdbStore.version == 1) { if (store.version != 3 && store.version == 1) {
// version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score) // version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score)
rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null) store.executeSql("ALTER TABLE student ADD COLUMN score REAL", null);
rdbStore.version = 2 store.version = 2;
} }
// When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3. // When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3.
if (rdbStore.version != 3 && rdbStore.version == 2) { if (store.version != 3 && store.version == 2) {
// version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score) // version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score)
rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null) store.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null);
rdbStore.version = 3 store.version = 3;
} }
}) })
``` ```
Stage model: Stage model:
```ts ```ts
import data_rdb from '@ohos.data.relationalStore' import relationalStore from '@ohos.data.relationalStore'
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
const STORE_CONFIG = { var store;
name: "rdbstore.db", const STORE_CONFIG = {
securityLevel: data_rdb.SecurityLevel.S1 name: "RdbTest.db",
} securityLevel: relationalStore.SecurityLevel.S1
};
// Assume that the current RDB store version is 3. // Assume that the current RDB store version is 3.
data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) { relationalStore.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) {
// When an RDB store is created, the default version is 0. store = rdbStore;
if (rdbStore.version == 0) { // When an RDB store is created, the default version is 0.
rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null) if (store.version == 0) {
// Set the RDB store version. The input parameter must be an integer greater than 0. store.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null);
rdbStore.version = 3 // Set the RDB store version. The input parameter must be an integer greater than 0.
} store.version = 3;
}
// When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2. // When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2.
if (rdbStore.version != 3 && rdbStore.version == 1) { if (store.version != 3 && store.version == 1) {
// version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score) // version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score)
rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null) store.executeSql("ALTER TABLE student ADD COLUMN score REAL", null);
rdbStore.version = 2 store.version = 2;
} }
// When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3. // When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3.
if (rdbStore.version != 3 && rdbStore.version == 2) { if (store.version != 3 && store.version == 2) {
// version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score) // version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score)
rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null) store.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null);
rdbStore.version = 3 store.version = 3;
} }
}) })
} }
} }
``` ```
...@@ -284,23 +289,24 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -284,23 +289,24 @@ You can obtain the distributed table name for a remote device based on the local
The sample code is as follows: The sample code is as follows:
```js ```js
let u8 = new Uint8Array([1, 2, 3]) let u8 = new Uint8Array([1, 2, 3]);
const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 } const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 };
let insertPromise = rdbStore.insert("test", valueBucket) let insertPromise = store.insert("test", valueBucket);
``` ```
```js ```js
// Use a transaction to insert data. // Use a transaction to insert data.
beginTransaction()
try { try {
let u8 = new Uint8Array([1, 2, 3]) store.beginTransaction();
const valueBucket1 = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 } let u8 = new Uint8Array([1, 2, 3]);
const valueBucket2 = { "name": "Jam", "age": 19, "salary": 200.5, "blobType": u8 } const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 };
let insertPromise1 = rdbStore.insert("test", valueBucket1) let promise = store.insert("test", valueBucket);
let insertPromise2 = rdbStore.insert("test", valueBucket2) promise.then(() => {
commit() store.commit();
} catch (e) { })
rollBack() } catch (err) {
console.error(`Transaction failed, err: ${err}`);
store.rollBack();
} }
``` ```
...@@ -315,17 +321,17 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -315,17 +321,17 @@ You can obtain the distributed table name for a remote device based on the local
The sample code is as follows: The sample code is as follows:
```js ```js
let predicates = new data_rdb.RdbPredicates("test"); let predicates = new relationalStore.RdbPredicates("test");
predicates.equalTo("name", "Tom") predicates.equalTo("name", "Tom");
let promisequery = rdbStore.query(predicates) let promisequery = store.query(predicates);
promisequery.then((resultSet) => { promisequery.then((resultSet) => {
resultSet.goToFirstRow() resultSet.goToFirstRow();
const id = resultSet.getLong(resultSet.getColumnIndex("id")) const id = resultSet.getLong(resultSet.getColumnIndex("id"));
const name = resultSet.getString(resultSet.getColumnIndex("name")) const name = resultSet.getString(resultSet.getColumnIndex("name"));
const age = resultSet.getLong(resultSet.getColumnIndex("age")) const age = resultSet.getLong(resultSet.getColumnIndex("age"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("salary")) const salary = resultSet.getDouble(resultSet.getColumnIndex("salary"));
const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType"));
resultSet.close() resultSet.close();
}) })
``` ```
...@@ -335,9 +341,9 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -335,9 +341,9 @@ You can obtain the distributed table name for a remote device based on the local
```json ```json
"requestPermissions": "requestPermissions":
{ {
"name": "ohos.permission.DISTRIBUTED_DATASYNC" "name": "ohos.permission.DISTRIBUTED_DATASYNC"
} }
``` ```
(2) Obtain the required permissions. (2) Obtain the required permissions.
...@@ -351,13 +357,13 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -351,13 +357,13 @@ You can obtain the distributed table name for a remote device based on the local
```js ```js
let context = featureAbility.getContext(); let context = featureAbility.getContext();
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
console.info(`result.requestCode=${result.requestCode}`) console.info(`result.requestCode=${result.requestCode}`);
}) })
let promise = rdbStore.setDistributedTables(["test"]) let promise = store.setDistributedTables(["test"]);
promise.then(() => { promise.then(() => {
console.info("setDistributedTables success.") console.info(`setDistributedTables success.`);
}).catch((err) => { }).catch((err) => {
console.info("setDistributedTables failed.") console.error(`setDistributedTables failed, ${err}`);
}) })
``` ```
...@@ -372,16 +378,16 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -372,16 +378,16 @@ You can obtain the distributed table name for a remote device based on the local
The sample code is as follows: The sample code is as follows:
```js ```js
let predicate = new data_rdb.RdbPredicates('test') let predicate = new relationalStore.RdbPredicates('test');
predicate.inDevices(['12345678abcde']) predicate.inDevices(['12345678abcde']);
let promise = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicate) let promise = store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicate);
promise.then((result) => { promise.then((result) => {
console.log('sync done.') console.info(`sync done.`);
for (let i = 0; i < result.length; i++) { for (let i = 0; i < result.length; i++) {
console.log('device=' + result[i][0] + 'status=' + result[i][1]) console.info(`device=${result[i][0]}, status=${result[i][1]}`);
} }
}).catch((err) => { }).catch((err) => {
console.log('sync failed') console.error(`sync failed, err: ${err}`);
}) })
``` ```
...@@ -395,15 +401,15 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -395,15 +401,15 @@ You can obtain the distributed table name for a remote device based on the local
```js ```js
function storeObserver(devices) { function storeObserver(devices) {
for (let i = 0; i < devices.length; i++) { for (let i = 0; i < devices.length; i++) {
console.log('device=' + device[i] + 'data changed') console.info(`device= ${devices[i]} data changed`);
} }
} }
try { try {
rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) store.on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver);
} catch (err) { } catch (err) {
console.log('register observer failed') console.error(`register observer failed, err: ${err}`);
} }
``` ```
...@@ -416,8 +422,24 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -416,8 +422,24 @@ You can obtain the distributed table name for a remote device based on the local
The sample code is as follows: The sample code is as follows:
```js ```js
let tableName = rdbStore.obtainDistributedTableName(deviceId, "test"); import deviceManager from '@ohos.distributedHardware.deviceManager'
let resultSet = rdbStore.querySql("SELECT * FROM " + tableName)
let deviceIds = [];
deviceManager.createDeviceManager('bundleName', (err, value) => {
if (!err) {
let devManager = value;
if (devManager != null) {
// Obtain device IDs.
let devices = devManager.getTrustedDeviceListSync();
for (let i = 0; i < devices.length; i++) {
deviceIds[i] = devices[i].deviceId;
}
}
}
})
let tableName = store.obtainDistributedTableName(deviceIds[0], "test");
let resultSet = store.querySql("SELECT * FROM " + tableName);
``` ```
8. Query data of a remote device. 8. Query data of a remote device.
...@@ -429,19 +451,19 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -429,19 +451,19 @@ You can obtain the distributed table name for a remote device based on the local
The sample code is as follows: The sample code is as follows:
```js ```js
let rdbPredicate = new data_rdb.RdbPredicates('employee') let rdbPredicate = new relationalStore.RdbPredicates('employee');
predicates.greaterThan("id", 0) predicates.greaterThan("id", 0) ;
let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate) let promiseQuery = store.remoteQuery('12345678abcde', 'employee', rdbPredicate);
promiseQuery.then((resultSet) => { promiseQuery.then((resultSet) => {
while (resultSet.goToNextRow()) { while (resultSet.goToNextRow()) {
let idx = resultSet.getLong(0); let idx = resultSet.getLong(0);
let name = resultSet.getString(1); let name = resultSet.getString(1);
let age = resultSet.getLong(2); let age = resultSet.getLong(2);
console.info(idx + " " + name + " " + age); console.info(`indx: ${idx}, name: ${name}, age: ${age}`);
} }
resultSet.close(); resultSet.close();
}).catch((err) => { }).catch((err) => {
console.info("failed to remoteQuery, err: " + err) console.error(`failed to remoteQuery, err: ${err}`);
}) })
``` ```
...@@ -452,11 +474,11 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -452,11 +474,11 @@ You can obtain the distributed table name for a remote device based on the local
The sample code is as follows: The sample code is as follows:
```js ```js
let promiseBackup = rdbStore.backup("dbBackup.db") let promiseBackup = store.backup("dbBackup.db");
promiseBackup.then(() => { promiseBackup.then(() => {
console.info('Backup success.') console.info(`Backup success.`);
}).catch((err) => { }).catch((err) => {
console.info('Backup failed, err: ' + err) console.error(`Backup failed, err: ${err}`);
}) })
``` ```
...@@ -465,10 +487,10 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -465,10 +487,10 @@ You can obtain the distributed table name for a remote device based on the local
The sample code is as follows: The sample code is as follows:
```js ```js
let promiseRestore = rdbStore.restore("dbBackup.db") let promiseRestore = store.restore("dbBackup.db");
promiseRestore.then(() => { promiseRestore.then(() => {
console.info('Restore success.') console.info(`Restore success.`);
}).catch((err) => { }).catch((err) => {
console.info('Restore failed, err: ' + err) console.error(`Restore failed, err: ${err}`);
}) })
``` ```
...@@ -36,5 +36,5 @@ Currently you can have access to statistics on the application usage, and the no ...@@ -36,5 +36,5 @@ Currently you can have access to statistics on the application usage, and the no
Deregister the callback for application group changes. Deregister the callback for application group changes.
## Required Permissions ## Required Permissions
- Before calling the following system APIs, you need to apply for the **ohos.permission.BUNDLE_ACTIVE_INFO** permission: **queryBundleActiveStates**, **queryBundleStateInfos**, **queryBundleStateInfoByInterval**, **queryBundleActiveEventStates**, **queryAppNotificationNumber**, **queryAppUsagePriorityGroup(bundleName?)**, **setBundleGroup**, **registerGroupCallBack**, and **unRegisterGroupCallBack**. - Before calling the following system APIs, you must request the **ohos.permission.BUNDLE_ACTIVE_INFO** permission: **isIdleState**, **queryBundleEvents**, **queryBundleStatsInfos**, **queryBundleStatsInfoByInterval**, **queryDeviceEventStats**, **queryNotificationEventStats**, **queryAppGroup(bundleName)**, **setAppGroup**, **registerAppGroupCallBack**, **unregisterAppGroupCallBack**, **queryModuleUsageRecords**, and **queryModuleUsageRecords(maxnum)**.
- This permission is not required for calling third-party APIs: **queryCurrentBundleActiveStates**, **queryAppUsagePriorityGroup()**, and **isIdleState**. - You do not need to request this permission before calling **queryCurrentBundleEvents** and **queryAppGroup()**, which are third-party APIs.
...@@ -225,7 +225,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -225,7 +225,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
} }
``` ```
7. Check whether the application specified by **bundleName** is in the idle state. This requires no permission to be configured. A third-party application can only check the idle status of itself. 7. Check whether the application specified by **bundleName** is in the idle state. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured.
```js ```js
import usageStatistics from '@ohos.resourceschedule.usageStatistics' import usageStatistics from '@ohos.resourceschedule.usageStatistics'
...@@ -531,4 +531,4 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -531,4 +531,4 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack throw error, code is: ' + error.code + ',message is: ' + error.message);
} }
``` ```
\ No newline at end of file
# Device # Device Management
- USB Service - USB Service
- [USB Service Overview](usb-overview.md) - [USB Service Overview](usb-overview.md)
...@@ -17,3 +17,5 @@ ...@@ -17,3 +17,5 @@
- Update Service - Update Service
- [Sample Server Overview](sample-server-overview.md) - [Sample Server Overview](sample-server-overview.md)
- [Sample Server Development](sample-server-guidelines.md) - [Sample Server Development](sample-server-guidelines.md)
- Stationary
- [Stationary Development](stationary-guidelines.md)
# Stationary Development
## When to Use
An application can call the **Stationary** module to obtain the device status, for example, whether the device is absolutely or relatively still.
For details about the APIs, see [Stationary](../reference/apis/js-apis-stationary.md).
## Device Status Type Parameters
| Name| Description|
| -------- | -------- |
| still | Absolutely still.|
| relativeStill | Relatively still.|
## Parameters for Subscribing to Device Status events
| Name | Value | Description |
| ------------------------------ | ---- | ---------------------------------------- |
| ENTER | 1 | Event indicating entering device status. |
| EXIT | 2 | Event indicating exiting device status.|
| ENTER_EXIT | 3 | Event indicating entering and exiting device status.|
## Returned Device Status Parameters
| Name | Value | Description |
| ------------------------------ | ---- | ---------------------------------------- |
| ENTER | 1 | Entering device status. |
| EXIT | 2 | Exiting device status.|
## Available APIs
| Module | Name | Description |
| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ohos.stationary | on(activity: ActivityType, event: ActivityEvent, reportLatencyNs: number, callback: Callback&lt;ActivityResponse&gt;): void | Subscribes to the device status. This API uses an asynchronous callback to return the result.|
| ohos.stationary | once(activity: ActivityType, callback: Callback&lt;ActivityResponse&gt;): void | Obtains the device status. This API uses an asynchronous callback to return the result.|
| ohos.stationary | off(activity: ActivityType, event: ActivityEvent, callback?: Callback&lt;ActivityResponse&gt;): void | Unsubscribes from the device status. |
## Constraints
The device must support the acceleration sensor.
## How to Develop
1. Subscribe to the event indicating entering the absolute still state, and the event is reported every 1 second.
```js
import stationary from '@ohos.stationary';
var reportLatencyNs = 1000000000;
try {
stationary.on('still', stationary.ActivityEvent.ENTER, reportLatencyNs, (data) => {
console.log('data='+ JSON.stringify(data));
})
} catch (err) {
console.error('errCode: ' + err.code + ' ,msg: ' + err.message);
}
```
2. Obtain the event indicating entering the absolute still state.
```js
import stationary from '@ohos.stationary';
try {
stationary.once('still', (data) => {
console.log('data='+ JSON.stringify(data));
})
} catch (err) {
console.error('errCode: ' + err.code + ' ,msg: ' + err.message);
}
```
3. Unsubscribe from the event indicating entering the absolute still state.
```js
import stationary from '@ohos.stationary';
try {
stationary.off('still', stationary.ActivityEvent.ENTER, (data) => {
console.log('data='+ JSON.stringify(data));
})
} catch (err) {
console.error('errCode: ' + err.code + ' ,msg: ' + err.message);
}
```
...@@ -39,8 +39,8 @@ When an asynchronous callback is used, the return value can be processed directl ...@@ -39,8 +39,8 @@ When an asynchronous callback is used, the return value can be processed directl
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import errorManager from '@ohos.app.ability.errorManager'; import errorManager from '@ohos.app.ability.errorManager';
var registerId = -1; let registerId = -1;
var callback = { let callback = {
onUnhandledException: function (errMsg) { onUnhandledException: function (errMsg) {
console.log(errMsg); console.log(errMsg);
} }
...@@ -48,13 +48,13 @@ var callback = { ...@@ -48,13 +48,13 @@ var callback = {
export default class EntryAbility extends Ability { export default class EntryAbility extends Ability {
onCreate(want, launchParam) { onCreate(want, launchParam) {
console.log("[Demo] EntryAbility onCreate") console.log("[Demo] EntryAbility onCreate")
registerId = errorManager.registerErrorObserver(callback); registerId = errorManager.on("error", callback);
globalThis.abilityWant = want; globalThis.abilityWant = want;
} }
onDestroy() { onDestroy() {
console.log("[Demo] EntryAbility onDestroy") console.log("[Demo] EntryAbility onDestroy")
errorManager.unregisterErrorObserver(registerId, (result) => { errorManager.off("error", registerId, (result) => {
console.log("[Demo] result " + result.code + ";" + result.message) console.log("[Demo] result " + result.code + ";" + result.message)
}); });
} }
......
...@@ -9,11 +9,10 @@ FilePicker provides the following modes: ...@@ -9,11 +9,10 @@ FilePicker provides the following modes:
## Development Guidelines ## Development Guidelines
> **NOTE** > **NOTE**
>
> FilePicker supports only the applications developed based on the stage model. > FilePicker supports only the applications developed based on the stage model.
> For details about the stage model, see [Interpretation of the Application Model](../application-models/application-model-description.md). > For details about the stage model, see [Interpretation of the Application Model](../application-models/application-model-description.md).
You can use [AbilityContext.startAbilityForResult(want, options)](../reference/apis/js-apis-ability-context.md##abilitycontextstartabilityforresult-1) with different parameters to start different FilePicker modes. You can use [AbilityContext.startAbilityForResult(want, options)](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilityforresult-1) with different parameters to start FilePicker in different modes.
You need to use [Want](../reference/apis/js-apis-application-want.md) to specify **bundleName** and **abilityName** to start FilePicker. For details, see the following sample code. You need to use [Want](../reference/apis/js-apis-application-want.md) to specify **bundleName** and **abilityName** to start FilePicker. For details, see the following sample code.
...@@ -32,8 +31,7 @@ ArkTS sample code: ...@@ -32,8 +31,7 @@ ArkTS sample code:
// Start FilePicker to select a file. // Start FilePicker to select a file.
globalThis.context.startAbilityForResult( globalThis.context.startAbilityForResult(
{ {
bundleName: "com.ohos.filepicker", action: "ohos.want.action.OPEN_FILE",
abilityName: "MainAbility",
parameters: { parameters: {
'startMode': 'choose', //choose or save 'startMode': 'choose', //choose or save
} }
...@@ -44,8 +42,7 @@ globalThis.context.startAbilityForResult( ...@@ -44,8 +42,7 @@ globalThis.context.startAbilityForResult(
// Start FilePicker to save a file. // Start FilePicker to save a file.
globalThis.context.startAbilityForResult( globalThis.context.startAbilityForResult(
{ {
bundleName: "com.ohos.filepicker", action: "ohos.want.action.CREATE_FILE",
abilityName: "MainAbility",
parameters: { parameters: {
'startMode': 'save', //choose or save 'startMode': 'save', //choose or save
'saveFile': 'test.jpg', 'saveFile': 'test.jpg',
......
...@@ -39,19 +39,19 @@ The following describes how to create an album named **myAlbum**. ...@@ -39,19 +39,19 @@ The following describes how to create an album named **myAlbum**.
```ts ```ts
async function example() { async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE; let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_IMAGE); const path = await media.getPublicDirectory(DIR_IMAGE);
// myAlbum is the path for storing the new file and the name of the new album. // myAlbum is the path for storing the new file and the name of the new album.
media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => { media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => {
if (fileAsset != undefined) { if (fileAsset === undefined) {
console.info('createAlbum successfully, message = ' + fileAsset); console.error('createAlbum failed, message = ' + err);
} else { } else {
console.info('createAlbum failed, message = ' + err); console.info('createAlbum successfully, message = ' + JSON.stringify(fileAsset));
} }
}); });
} }
``` ```
...@@ -75,20 +75,20 @@ The following describes how to rename the album **newAlbum**. ...@@ -75,20 +75,20 @@ The following describes how to rename the album **newAlbum**.
```ts ```ts
async function example() { async function example() {
let AlbumNoArgsfetchOp = { let AlbumNoArgsfetchOp = {
selections: '', selections: '',
selectionArgs: [], selectionArgs: [],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let albumList = await media.getAlbums(AlbumNoArgsfetchOp); let albumList = await media.getAlbums(AlbumNoArgsfetchOp);
let album = albumList[0]; let album = albumList[0];
album.albumName = 'newAlbum'; album.albumName = 'newAlbum';
// Void callback. // Void callback.
album.commitModify().then(function() { album.commitModify().then(() => {
console.info("albumRename successfully"); console.info("albumRename successfully");
}).catch(function(err){ }).catch((err) => {
console.info("albumRename failed with error: " + err); console.error("albumRename failed with error: " + err);
}); });
} }
``` ```
...@@ -37,15 +37,15 @@ The following describes how to obtain the public directory that stores camera fi ...@@ -37,15 +37,15 @@ The following describes how to obtain the public directory that stores camera fi
```ts ```ts
async function example(){ async function example(){
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
const dicResult = await media.getPublicDirectory(DIR_CAMERA); const dicResult = await media.getPublicDirectory(DIR_CAMERA);
if (dicResult == 'Camera/') { if (dicResult == 'Camera/') {
console.info('mediaLibraryTest : getPublicDirectory passed'); console.info('mediaLibraryTest : getPublicDirectory passed');
} else { } else {
console.info('mediaLibraryTest : getPublicDirectory failed'); console.error('mediaLibraryTest : getPublicDirectory failed');
} }
} }
``` ```
...@@ -59,47 +59,52 @@ Users can access files stored in the public directories through the system appli ...@@ -59,47 +59,52 @@ Users can access files stored in the public directories through the system appli
You can call [mediaLibrary.FileAsset.open](../reference/apis/js-apis-medialibrary.md#open8-1) to open a file in a public directory. You can call [mediaLibrary.FileAsset.open](../reference/apis/js-apis-medialibrary.md#open8-1) to open a file in a public directory.
You can call [fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7) to open a file in the application sandbox. The sandbox directory can be accessed only through the application context. You can call [fs.open](../reference/apis/js-apis-file-fs.md#fsopen) to open a file in the application sandbox. The sandbox directory can be accessed only through the application context.
**Prerequisites** **Prerequisites**
- You have obtained a **MediaLibrary** instance. - You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**. - You have granted the permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA**.
- You have imported the module [@ohos.fileio](../reference/apis/js-apis-fileio.md) in addition to @ohos.multimedia.mediaLibrary. - You have imported the module [@ohos.file.fs](../reference/apis/js-apis-file-fs.md) in addition to @ohos.multimedia.mediaLibrary.
- The **testFile.txt** file has been created and contains content.
**How to Develop** **How to Develop**
1. Call [context.filesDir](../reference/apis/js-apis-inner-app-context.md#contextgetfilesdir) to obtain the directory of the application sandbox. 1. Call [context.filesDir](../reference/apis/js-apis-file-fs.md) to obtain the directory of the application sandbox.
2. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory. 2. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory.
3. Call **fileio.open** to open the file in the sandbox. 3. Call **fs.open** to open the file in the sandbox.
4. Call **fileAsset.open** to open the file in the public directory. 4. Call **fileAsset.open** to open the file in the public directory.
5. Call **fileio.copyfile** to copy the file. 5. Call [fs.copyfile](../reference/apis/js-apis-file-fs.md#fscopyfile) to copy the file.
6. Call **fileAsset.close** and **fileio.close** to close the file. 6. Call **fileAsset.close** and [fs.close](../reference/apis/js-apis-file-fs.md#fsclose) to close the file.
**Example 1: Copying Files from the Public Directory to the Sandbox** **Example 1: Copying Files from the Public Directory to the Sandbox**
```ts ```ts
async function copyPublic2Sandbox() { async function copyPublic2Sandbox() {
try {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let sandboxDirPath = globalThis.context.filesDir; let sandboxDirPath = context.filesDir;
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?', selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile.txt'], selectionArgs: ['testFile.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
let fileAsset = await fetchResult.getFirstObject(); let fileAsset = await fetchResult.getFirstObject();
let fdPub = await fileAsset.open('rw'); let fdPub = await fileAsset.open('rw');
let fdSand = await fileio.open(sandboxDirPath + '/testFile.txt', 0o2 | 0o100, 0o666); let fdSand = await fs.open(sandboxDirPath + '/testFile.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
await fileio.copyFile(fdPub, fdSand); await fs.copyFile(fdPub, fdSand.fd);
await fileAsset.close(fdPub); await fileAsset.close(fdPub);
await fileio.close(fdSand); await fs.close(fdSand.fd);
let content_sand = await fileio.readText(sandboxDirPath + '/testFile.txt'); let content_sand = await fs.readText(sandboxDirPath + '/testFile.txt');
console.log('content read from sandbox file: ', content_sand) console.info('content read from sandbox file: ', content_sand)
} catch (err) {
console.info('[demo] copyPublic2Sandbox fail, err: ', err);
}
} }
``` ```
...@@ -107,81 +112,81 @@ async function copyPublic2Sandbox() { ...@@ -107,81 +112,81 @@ async function copyPublic2Sandbox() {
```ts ```ts
async function copySandbox2Public() { async function copySandbox2Public() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let sandboxDirPath = globalThis.context.filesDir; let sandboxDirPath = context.filesDir;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const publicDirPath = await media.getPublicDirectory(DIR_DOCUMENTS); const publicDirPath = await media.getPublicDirectory(DIR_DOCUMENTS);
try { try {
let fileAsset = await media.createAsset(mediaLibrary.MediaType.FILE, 'testFile02.txt', publicDirPath); let fileAsset = await media.createAsset(mediaLibrary.MediaType.FILE, 'testFile02.txt', publicDirPath);
console.info('createFile successfully, message = ' + fileAsset); console.info('createFile successfully, message = ' + fileAsset);
} catch (err) { } catch (err) {
console.info('createFile failed, message = ' + err); console.error('createFile failed, message = ' + err);
} }
try { try {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?', selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile02.txt'], selectionArgs: ['testFile02.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
var fileAsset = await fetchResult.getFirstObject(); var fileAsset = await fetchResult.getFirstObject();
} catch (err) { } catch (err) {
console.info('file asset get failed, message = ' + err); console.error('file asset get failed, message = ' + err);
} }
let fdPub = await fileAsset.open('rw'); let fdPub = await fileAsset.open('rw');
let fdSand = await fileio.open(sandboxDirPath + 'testFile.txt', 0o2); let fdSand = await fs.open(sandboxDirPath + 'testFile.txt', OpenMode.READ_WRITE);
await fileio.copyFile(fdSand, fdPub); await fs.copyFile(fdSand.fd, fdPub);
await fileio.close(fdPub); await fileAsset.close(fdPub);
await fileio.close(fdSand); await fs.close(fdSand.fd);
let fdPubRead = await fileAsset.open('rw'); let fdPubRead = await fileAsset.open('rw');
try { try {
let arrayBuffer = new ArrayBuffer(4096); let arrayBuffer = new ArrayBuffer(4096);
await fileio.read(fdPubRead, arrayBuffer); await fs.read(fdPubRead, arrayBuffer);
var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer)); var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer));
fileAsset.close(fdPubRead); fileAsset.close(fdPubRead);
} catch (err) { } catch (err) {
console.log('read text failed, message = ', err); console.error('read text failed, message = ', err);
} }
console.log('content read from public file: ', content_pub); console.info('content read from public file: ', content_pub);
} }
``` ```
### Reading and Writing a File ### Reading and Writing a File
You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../reference/apis/js-apis-medialibrary.md) to open and close a file, and use **fileio.read** and **fileio.write** of [fileio](../reference/apis/js-apis-fileio.md) to read and write a file. You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../reference/apis/js-apis-medialibrary.md) to open and close a file, and use **fs.read** and **fs.write** in [file.fs](../reference/apis/js-apis-file-fs.md) to read and write the file.
**Prerequisites** **Prerequisites**
- You have obtained a **MediaLibrary** instance. - You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**. - You have granted the permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA**.
- You have imported the module [@ohos.fileio](../reference/apis/js-apis-fileio.md) in addition to @ohos.multimedia.mediaLibrary. - You have imported the module [@ohos.file.fs](../reference/apis/js-apis-file-fs.md) in addition to @ohos.multimedia.mediaLibrary.
**How to Develop** **How to Develop**
1. Create a file. 1. Create a file.
```ts ```ts
async function example() { async function example() {
let mediaType = mediaLibrary.MediaType.FILE; let mediaType = mediaLibrary.MediaType.FILE;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS); const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.text", path).then (function (asset) { media.createAsset(mediaType, "testFile.text", path).then((asset) => {
console.info("createAsset successfully:" + JSON.stringify(asset)); console.info("createAsset successfully:" + JSON.stringify(asset));
}).catch(function(err){ }).catch((err) => {
console.info("createAsset failed with error: " + err); console.error("createAsset failed with error: " + err);
}); });
} }
``` ```
2. Call **FileAsset.open** to open the file. 2. Call **FileAsset.open** to open the file.
3. Call **fileio.write** to write a string to the file. 3. Call [fs.write](../reference/apis/js-apis-file-fs.md#fswrite) to write a string to the file.
4. Call **fileio.read** to read the file and save the data read in an array buffer. 4. Call [fs.read](../reference/apis/js-apis-file-fs.md#fsread) to read the file and save the data read in an array buffer.
5. Convert the array buffer to a string. 5. Convert the array buffer to a string.
...@@ -191,25 +196,25 @@ You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../refe ...@@ -191,25 +196,25 @@ You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../refe
```ts ```ts
async function writeOnlyPromise() { async function writeOnlyPromise() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?', selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile.txt'], selectionArgs: ['testFile.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
let fileAsset = await fetchResult.getFirstObject(); let fileAsset = await fetchResult.getFirstObject();
console.info('fileAssetName: ', fileAsset.displayName); console.info('fileAssetName: ', fileAsset.displayName);
try { try {
let fd = await fileAsset.open('w'); let fd = await fileAsset.open('w');
console.info('file descriptor: ', fd); console.info('file descriptor: ', fd);
await fileio.write(fd, "Write file test content."); await fs.write(fd, "Write file test content.");
await fileAsset.close(fd); await fileAsset.close(fd);
} catch (err) { } catch (err) {
console.info('write file failed, message = ', err); console.error('write file failed, message = ', err);
} }
} }
``` ```
...@@ -217,28 +222,28 @@ async function writeOnlyPromise() { ...@@ -217,28 +222,28 @@ async function writeOnlyPromise() {
```ts ```ts
async function readOnlyPromise() { async function readOnlyPromise() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' , selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
selectionArgs: ['testFile.txt'], selectionArgs: ['testFile.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
let fileAsset = await fetchResult.getFirstObject(); let fileAsset = await fetchResult.getFirstObject();
console.info('fileAssetName: ', fileAsset.displayName); console.info('fileAssetName: ', fileAsset.displayName);
try { try {
let fd = await fileAsset.open('r'); let fd = await fileAsset.open('r');
let arrayBuffer = new ArrayBuffer(4096); let arrayBuffer = new ArrayBuffer(4096);
await fileio.read(fd, arrayBuffer); await fs.read(fd, arrayBuffer);
let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer)); let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer));
globalThis.fileContent = fileContent; globalThis.fileContent = fileContent;
globalThis.fileName = fileAsset.displayName; globalThis.fileName = fileAsset.displayName;
console.info('file content: ', fileContent); console.info('file content: ', fileContent);
await fileAsset.close(fd); await fileAsset.close(fd);
} catch (err) { } catch (err) {
console.info('read file failed, message = ', err); console.error('read file failed, message = ', err);
} }
} }
``` ```
...@@ -64,64 +64,64 @@ After configuring the permissions in the **module.json5** file, the application ...@@ -64,64 +64,64 @@ After configuring the permissions in the **module.json5** file, the application
1. Declare the permissions in the **module.json5** file. Add the **requestPermissions** tag under **module** in the file, and set the tag based on the project requirements. For details about the tag, see [Guide for Requesting Permissions from User](../security/accesstoken-guidelines.md). 1. Declare the permissions in the **module.json5** file. Add the **requestPermissions** tag under **module** in the file, and set the tag based on the project requirements. For details about the tag, see [Guide for Requesting Permissions from User](../security/accesstoken-guidelines.md).
```json ```json
{ {
"module": { "module": {
"requestPermissions": [ "requestPermissions": [
{ {
"name": "ohos.permission.MEDIA_LOCATION", "name": "ohos.permission.MEDIA_LOCATION",
"reason": "$string:reason", "reason": "$string:reason",
"usedScene": { "usedScene": {
"abilities": [ "abilities": [
"EntryAbility" "EntryAbility"
], ],
"when": "always" "when": "always"
} }
}, },
{ {
"name": "ohos.permission.READ_MEDIA", "name": "ohos.permission.READ_MEDIA",
"reason": "$string:reason", "reason": "$string:reason",
"usedScene": { "usedScene": {
"abilities": [ "abilities": [
"EntryAbility" "EntryAbility"
], ],
"when": "always" "when": "always"
} }
}, },
{ {
"name": "ohos.permission.WRITE_MEDIA", "name": "ohos.permission.WRITE_MEDIA",
"reason": "$string:reason", "reason": "$string:reason",
"usedScene": { "usedScene": {
"abilities": [ "abilities": [
"EntryAbility" "EntryAbility"
], ],
"when": "always" "when": "always"
} }
} }
] ]
} }
} }
``` ```
2. In the **Ability.ts** file, call **requestPermissionsFromUser** in the **onWindowStageCreate** callback to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box. 2. In the **Ability.ts** file, call **requestPermissionsFromUser** in the **onWindowStageCreate** callback to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
let list : Array<Permissions> = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA']; let list : Array<Permissions> = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA'];
let permissionRequestResult; let permissionRequestResult;
let atManager = abilityAccessCtrl.createAtManager(); let atManager = abilityAccessCtrl.createAtManager();
atManager.requestPermissionsFromUser(this.context, list, (err, result) => { atManager.requestPermissionsFromUser(this.context, list, (err, result) => {
if (err) { if (err) {
console.log('requestPermissionsFromUserError: ' + JSON.stringify(err)); console.error('requestPermissionsFromUserError: ' + JSON.stringify(err));
} else { } else {
permissionRequestResult=result; permissionRequestResult = result;
console.log('permissionRequestResult: ' + JSON.stringify(permissionRequestResult)); console.info('permissionRequestResult: ' + JSON.stringify(permissionRequestResult));
} }
}); });
} }
} }
``` ```
...@@ -33,30 +33,33 @@ To specify the image as the media type, set **selectionArgs** to **MediaType.IMA ...@@ -33,30 +33,33 @@ To specify the image as the media type, set **selectionArgs** to **MediaType.IMA
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE; let fileType = mediaLibrary.MediaType.IMAGE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getFirstObject().then((fileAsset) => {
fetchFileResult.getNextObject((err, fileAsset) => { console.log('getFirstObject.displayName : ' + fileAsset.displayName);
if (err) { for (let i = 1; i < fetchFileResult.getCount(); i++) {
console.error('Failed '); fetchFileResult.getNextObject().then((fileAsset) => {
return; console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
} }).catch((err) => {
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.error('Failed to get next object: ' + err);
}) });
} }
}).catch((err) => {
console.error('Failed to get first object: ' + err);
});
} }
``` ```
### Querying Media Assets with the Specified Date ### Querying Media Assets with the Specified Date
The following describes how to obtain media assets that are added on the specified date. You can also use the modification date and shooting date as the retrieval conditions. The following describes how to obtain all the media assets that are added from the specified date. You can also use the modification date and shooting date as the retrieval conditions.
To specify the date when the files are added as the retrieval condition, set **selections** to **FileKey.DATE_ADDED**. To specify the date when the files are added as the retrieval condition, set **selections** to **FileKey.DATE_ADDED**.
...@@ -64,23 +67,26 @@ To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**. ...@@ -64,23 +67,26 @@ To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**.
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let option = { let option = {
selections: fileKeyObj.DATE_ADDED + '= ?', selections: fileKeyObj.DATE_ADDED + '> ?',
selectionArgs: ['2022-8-5'], selectionArgs: ['2022-8-5'],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getFirstObject().then((fileAsset) => {
fetchFileResult.getNextObject((err, fileAsset) => { console.info('getFirstObject.displayName : ' + fileAsset.displayName);
if (err) { for (let i = 1; i < fetchFileResult.getCount(); i++) {
console.error('Failed '); fetchFileResult.getNextObject().then((fileAsset) => {
return; console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
} }).catch((err) => {
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.error('Failed to get next object: ' + err);
}) });
} }
}).catch((err) => {
console.error('Failed to get first object: ' + err);
});
} }
``` ```
...@@ -92,25 +98,28 @@ To sort files in descending order by the date when they are added, set **order** ...@@ -92,25 +98,28 @@ To sort files in descending order by the date when they are added, set **order**
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE; let fileType = mediaLibrary.MediaType.IMAGE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + " DESC",
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getFirstObject().then((fileAsset) => {
fetchFileResult.getNextObject((err, fileAsset) => { console.info('getFirstObject.displayName : ' + fileAsset.displayName);
if (err) { for (let i = 1; i < fetchFileResult.getCount(); i++) {
console.error('Failed '); fetchFileResult.getNextObject().then((fileAsset) => {
return; console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
} }).catch((err) => {
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.error('Failed to get next object: ' + err);
}) });
} }
}).catch((err) => {
console.error('Failed to get first object: ' + err);
});
} }
``` ```
...@@ -124,31 +133,29 @@ To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**. ...@@ -124,31 +133,29 @@ To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**.
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE; let option = {
let option = { selections: fileKeyObj.ALBUM_NAME + '= ?',
selections: fileKeyObj.ALBUM_NAME + '= ?', selectionArgs: ['myAlbum'],
selectionArgs: ['myAlbum'], };
}; const context = getContext(this);
const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option);
const fetchFileResult = await media.getFileAssets(option); if (albumList.length > 0) {
for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getFirstObject().then((album) => {
fetchFileResult.getNextObject((err, fileAsset) => { console.info('getFirstObject.displayName : ' + album.albumName);
if (err) { }).catch((err) => {
console.error('Failed '); console.error('Failed to get first object: ' + err);
return; });
} } else {
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.info('getAlbum list is: 0');
}) }
}
} }
``` ```
## Obtaining Images and Videos in an Album ## Obtaining Images and Videos in an Album
You can obtain media assets in an album in either of the following ways: You can obtain media assets in an album in either of the following ways:
- Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified, as described in [Querying Media Assets with the Specfied Album Name](#querying-media-assets-with-the-specified-album-name). - Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified, as described in [Querying Media Assets with the Specfied Album Name](#querying-media-assets-with-the-specified-album-name).
- Call [Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3) to obtain an **Album** instance, so as to obtain the media assets in it. - Call [Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3) to obtain an **Album** instance, so as to obtain the media assets in it.
...@@ -163,24 +170,24 @@ The following describes how to obtain videos in an album named **New Album 1**. ...@@ -163,24 +170,24 @@ The following describes how to obtain videos in an album named **New Album 1**.
1. Create a retrieval condition for obtaining the target **Album** instance. 1. Create a retrieval condition for obtaining the target **Album** instance.
```ts ```ts
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let AlbumNoArgsFetchOp = { let AlbumNoArgsFetchOp = {
selections: fileKeyObj.ALBUM_NAME + '= ?', selections: fileKeyObj.ALBUM_NAME + '= ?',
selectionArgs:['New Album 1'] selectionArgs:['New Album 1']
} }
``` ```
2. Create a retrieval condition for obtaining videos in the target album. 2. Create a retrieval condition for obtaining videos in the target album.
```ts ```ts
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.VIDEO; let videoType = mediaLibrary.MediaType.VIDEO;
let imagesFetchOp = { let videoFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [videoType.toString()],
} }
``` ```
3. Call **Album.getFileAssets** to obtain the videos in the target album. 3. Call **Album.getFileAssets** to obtain the videos in the target album.
...@@ -188,28 +195,28 @@ Complete sample code: ...@@ -188,28 +195,28 @@ Complete sample code:
```ts ```ts
async function getCameraImagePromise() { async function getCameraImagePromise() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let videoType = mediaLibrary.MediaType.VIDEO;
let imagesFetchOp = { let videoFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [videoType.toString()],
} }
let AlbumNoArgsFetchOp = { let AlbumNoArgsFetchOp = {
selections: fileKeyObj.ALBUM_NAME + '= ?', selections: fileKeyObj.ALBUM_NAME + '= ?',
selectionArgs:['New Album 1'] selectionArgs:['New Album 1']
} }
let albumList = await media.getAlbums(AlbumNoArgsFetchOp); let albumList = await media.getAlbums(AlbumNoArgsFetchOp);
if (albumList.length > 0) { if (albumList.length > 0) {
const album = albumList[0]; const album = albumList[0];
let fetchFileResult = await album.getFileAssets(imagesFetchOp); let fetchFileResult = await album.getFileAssets(videoFetchOp);
let count = fetchFileResult.getCount(); let count = fetchFileResult.getCount();
console.info("get mediaLibrary IMAGE number", count); console.info("get mediaLibrary VIDEO number", count);
} else { } else {
console.info('getAlbum list is: 0'); console.info('getAlbum list is: 0');
} }
} }
``` ```
...@@ -235,31 +242,32 @@ The following describes how to obtain the thumbnail (size: 720 x 720) of the fir ...@@ -235,31 +242,32 @@ The following describes how to obtain the thumbnail (size: 720 x 720) of the fir
```ts ```ts
async function getFirstThumbnailPromise() { async function getFirstThumbnailPromise() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let imagesFetchOp = { let imagesFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
} }
let size = { width: 720, height: 720 }; let size = { width: 720, height: 720 };
const fetchFileResult = await media.getFileAssets(imagesFetchOp); const fetchFileResult = await media.getFileAssets(imagesFetchOp);
if (fetchFileResult != undefined) { if (fetchFileResult === undefined) {
const asset = await fetchFileResult.getFirstObject(); console.error("get image failed with error");
asset.getThumbnail(size).then((pixelMap) => { return;
pixelMap.getImageInfo().then((info) => { } else {
console.info('get Thumbnail info: ' + "width: " + info.size.width + " height: " + info.size.height); const asset = await fetchFileResult.getFirstObject();
}).catch((err) => { asset.getThumbnail(size).then((pixelMap) => {
console.info("getImageInfo failed with error:" + err); pixelMap.getImageInfo().then((info) => {
}); console.info('get Thumbnail info: ' + "width: " + info.size.width + " height: " + info.size.height);
}).catch((err) => { }).catch((err) => {
console.info("getImageInfo failed with error:" + err); console.error("getImageInfo failed with error: " + err);
}); });
} else { }).catch((err) => {
console.info("get image failed with error"); console.error("getImageInfo failed with error: " + err);
} });
}
} }
``` ```
...@@ -277,16 +285,16 @@ The following describes how to create a file of the **MediaType.FILE** type. ...@@ -277,16 +285,16 @@ The following describes how to create a file of the **MediaType.FILE** type.
```ts ```ts
async function example() { async function example() {
let mediaType = mediaLibrary.MediaType.FILE; let mediaType = mediaLibrary.MediaType.FILE;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS); const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.text", path).then ((asset) => { media.createAsset(mediaType, "testFile.text", path).then((asset) => {
console.info("createAsset successfully:"+ JSON.stringify(asset)); console.info("createAsset successfully:"+ JSON.stringify(asset));
}).catch((err) => { }).catch((err) => {
console.info("createAsset failed with error:"+ err); console.error("createAsset failed with error: " + err);
}); });
} }
``` ```
...@@ -312,26 +320,26 @@ The following describes how to move the first file in the result set to the recy ...@@ -312,26 +320,26 @@ The following describes how to move the first file in the result set to the recy
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE; let fileType = mediaLibrary.MediaType.FILE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject(); let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) { if (asset === undefined) {
console.error('asset not exist'); console.error('asset not exist');
return; return;
} }
// Void callback. // Void callback.
asset.trash(true).then(() => { asset.trash(true).then(() => {
console.info("trash successfully"); console.info("trash successfully");
}).catch((err) => { }).catch((err) => {
console.info("trash failed with error: " + err); console.error("trash failed with error: " + err);
}); });
} }
``` ```
...@@ -346,7 +354,7 @@ Before renaming a file, you must obtain the file, for example, by calling [Fetch ...@@ -346,7 +354,7 @@ Before renaming a file, you must obtain the file, for example, by calling [Fetch
- You have obtained a **MediaLibrary** instance. - You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**. - You have granted the permission **ohos.permission.WRITE_MEDIA**.
The following describes how to rename the first file in the result set as **newtitle.text**. The following describes how to rename the first file in the result set as **newImage.jpg**.
**How to Develop** **How to Develop**
...@@ -358,28 +366,28 @@ The following describes how to rename the first file in the result set as **newt ...@@ -358,28 +366,28 @@ The following describes how to rename the first file in the result set as **newt
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE; let fileType = mediaLibrary.MediaType.IMAGE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject(); let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) { if (asset === undefined) {
console.error('asset not exist'); console.error('asset not exist');
return;
}
asset.displayName = 'newImage.jpg';
// Void callback.
asset.commitModify((err) => {
if (err) {
console.error('fileRename Failed ');
return; return;
} }
asset.displayName = 'newImage.jpg'; console.info('fileRename successful.');
// Void callback. });
asset.commitModify((err) => {
if (err) {
console.error('fileRename Failed ');
return;
}
console.log('fileRename successful.');
});
} }
``` ```
# Media # Media
- Audio - Audio and Video
- [Audio Overview](audio-overview.md) - [Audio Overview](audio-overview.md)
- [Audio Playback Development](audio-playback.md)
- [Audio Recording Development](audio-recorder.md)
- [Audio Rendering Development](audio-renderer.md) - [Audio Rendering Development](audio-renderer.md)
- [Audio Stream Management Development](audio-stream-manager.md) - [Audio Stream Management Development](audio-stream-manager.md)
- [Audio Capture Development](audio-capturer.md) - [Audio Capture Development](audio-capturer.md)
...@@ -12,8 +10,10 @@ ...@@ -12,8 +10,10 @@
- [Audio Interruption Mode Development](audio-interruptmode.md) - [Audio Interruption Mode Development](audio-interruptmode.md)
- [Volume Management Development](audio-volume-manager.md) - [Volume Management Development](audio-volume-manager.md)
- [Audio Routing and Device Management Development](audio-routing-manager.md) - [Audio Routing and Device Management Development](audio-routing-manager.md)
- [AVPlayer Development (Recommended)](avplayer-playback.md)
- Video - [AVRecorder Development (Recommended)](avrecorder.md)
- [Audio Playback Development](audio-playback.md)
- [Audio Recording Development](audio-recorder.md)
- [Video Playback Development](video-playback.md) - [Video Playback Development](video-playback.md)
- [Video Recording Development](video-recorder.md) - [Video Recording Development](video-recorder.md)
......
...@@ -72,7 +72,7 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference ...@@ -72,7 +72,7 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
} }
await audioCapturer.start(); await audioCapturer.start();
let state = audioCapturer.state; state = audioCapturer.state;
if (state == audio.AudioState.STATE_RUNNING) { if (state == audio.AudioState.STATE_RUNNING) {
console.info('AudioRecLog: Capturer started'); console.info('AudioRecLog: Capturer started');
} else { } else {
...@@ -86,7 +86,7 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference ...@@ -86,7 +86,7 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
The following example shows how to write recorded data into a file. The following example shows how to write recorded data into a file.
```js ```js
import fileio from '@ohos.fileio'; import fs from '@ohos.file.fs';
let state = audioCapturer.state; let state = audioCapturer.state;
// The read operation can be performed only when the state is STATE_RUNNING. // The read operation can be performed only when the state is STATE_RUNNING.
...@@ -96,31 +96,36 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference ...@@ -96,31 +96,36 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
} }
const path = '/data/data/.pulse_dir/capture_js.wav'; // Path for storing the collected audio file. const path = '/data/data/.pulse_dir/capture_js.wav'; // Path for storing the collected audio file.
let fd = fileio.openSync(path, 0o102, 0o777); let file = fs.openSync(filePath, 0o2);
if (fd !== null) { let fd = file.fd;
console.info('AudioRecLog: file fd created'); if (file !== null) {
} console.info('AudioRecLog: file created');
else{ } else {
console.info('AudioRecLog: file fd create : FAILED'); console.info('AudioRecLog: file create : FAILED');
return; return;
} }
fd = fileio.openSync(path, 0o2002, 0o666);
if (fd !== null) { if (fd !== null) {
console.info('AudioRecLog: file fd opened in append mode'); console.info('AudioRecLog: file fd opened in append mode');
} }
let numBuffersToCapture = 150; // Write data for 150 times. let numBuffersToCapture = 150; // Write data for 150 times.
let count = 0;
while (numBuffersToCapture) { while (numBuffersToCapture) {
let bufferSize = await audioCapturer.getBufferSize();
let buffer = await audioCapturer.read(bufferSize, true); let buffer = await audioCapturer.read(bufferSize, true);
let options = {
offset: count * this.bufferSize,
length: this.bufferSize
}
if (typeof(buffer) == undefined) { if (typeof(buffer) == undefined) {
console.info('AudioRecLog: read buffer failed'); console.info('AudioRecLog: read buffer failed');
} else { } else {
let number = fileio.writeSync(fd, buffer); let number = fs.writeSync(fd, buffer, options);
console.info(`AudioRecLog: data written: ${number}`); console.info(`AudioRecLog: data written: ${number}`);
} }
numBuffersToCapture--; numBuffersToCapture--;
count++;
} }
``` ```
...@@ -189,7 +194,7 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference ...@@ -189,7 +194,7 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
let audioTime : number = await audioCapturer.getAudioTime(); let audioTime : number = await audioCapturer.getAudioTime();
// Obtain a proper minimum buffer size. // Obtain a proper minimum buffer size.
let bufferSize : number = await audioCapturer.getBuffersize(); let bufferSize : number = await audioCapturer.getBufferSize();
``` ```
7. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event. 7. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event.
......
...@@ -38,7 +38,7 @@ For details about the **src** types supported by **AudioPlayer**, see the [src a ...@@ -38,7 +38,7 @@ For details about the **src** types supported by **AudioPlayer**, see the [src a
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
// Print the stream track information. // Print the stream track information.
function printfDescription(obj) { function printfDescription(obj) {
...@@ -112,14 +112,8 @@ async function audioPlayerDemo() { ...@@ -112,14 +112,8 @@ async function audioPlayerDemo() {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3' let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path);
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + file.fd;
console.info('open fd success fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
``` ```
...@@ -128,7 +122,7 @@ async function audioPlayerDemo() { ...@@ -128,7 +122,7 @@ async function audioPlayerDemo() {
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
export class AudioDemo { export class AudioDemo {
// Set the player callbacks. // Set the player callbacks.
...@@ -154,14 +148,8 @@ export class AudioDemo { ...@@ -154,14 +148,8 @@ export class AudioDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3' let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path);
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + file.fd;
console.info('open fd success fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
} }
...@@ -171,7 +159,7 @@ export class AudioDemo { ...@@ -171,7 +159,7 @@ export class AudioDemo {
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
export class AudioDemo { export class AudioDemo {
// Set the player callbacks. // Set the player callbacks.
...@@ -202,14 +190,8 @@ export class AudioDemo { ...@@ -202,14 +190,8 @@ export class AudioDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\02.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\02.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let nextpath = pathDir + '/02.mp3' let nextpath = pathDir + '/02.mp3'
await fileIO.open(nextpath).then((fdNumber) => { let nextFile = await fs.open(nextpath);
nextFdPath = nextFdPath + '' + fdNumber; nextFdPath = nextFdPath + '' + nextFile.fd;
console.info('open fd success fd is' + nextFdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = nextFdPath; // Set the src attribute and trigger the 'dataLoad' event callback. audioPlayer.src = nextFdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
...@@ -220,14 +202,8 @@ export class AudioDemo { ...@@ -220,14 +202,8 @@ export class AudioDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3' let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path);
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + file.fd;
console.info('open fd success fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
} }
...@@ -237,7 +213,7 @@ export class AudioDemo { ...@@ -237,7 +213,7 @@ export class AudioDemo {
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
export class AudioDemo { export class AudioDemo {
// Set the player callbacks. // Set the player callbacks.
...@@ -259,14 +235,8 @@ export class AudioDemo { ...@@ -259,14 +235,8 @@ export class AudioDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3' let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path);
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + file.fd;
console.info('open fd success fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
} }
......
...@@ -33,31 +33,30 @@ The following figure shows the audio renderer state transitions. ...@@ -33,31 +33,30 @@ The following figure shows the audio renderer state transitions.
For details about the APIs, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8). For details about the APIs, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8).
1. Use **createAudioRenderer()** to create an **AudioRenderer** instance. 1. Use **createAudioRenderer()** to create an **AudioRenderer** instance.
Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification. Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification.
```js ```js
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
let audioStreamInfo = { let audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1, channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
} }
let audioRendererInfo = { let audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_SPEECH, content: audio.ContentType.CONTENT_TYPE_SPEECH,
usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
rendererFlags: 0 // 0 is the extended flag bit of the audio renderer. The default value is 0. rendererFlags: 0 // 0 is the extended flag bit of the audio renderer. The default value is 0.
}
let audioRendererOptions = {
streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo
} }
let audioRendererOptions = {
streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo
}
let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); let audioRenderer = await audio.createAudioRenderer(audioRendererOptions);
console.log("Create audio renderer success."); console.log("Create audio renderer success.");
``` ```
2. Use **start()** to start audio rendering. 2. Use **start()** to start audio rendering.
...@@ -90,7 +89,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th ...@@ -90,7 +89,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
Read the audio data to be played to the buffer. Call **write()** repeatedly to write the data to the buffer. Read the audio data to be played to the buffer. Call **write()** repeatedly to write the data to the buffer.
```js ```js
import fileio from '@ohos.fileio'; import fs from '@ohos.file.fs';
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
async function writeBuffer(buf) { async function writeBuffer(buf) {
...@@ -109,35 +108,33 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th ...@@ -109,35 +108,33 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
// Set a proper buffer size for the audio renderer. You can also select a buffer of another size. // Set a proper buffer size for the audio renderer. You can also select a buffer of another size.
const bufferSize = await audioRenderer.getBufferSize(); const bufferSize = await audioRenderer.getBufferSize();
let dir = globalThis.fileDir; // You must use the sandbox path. let dir = globalThis.fileDir; // You must use the sandbox path.
const path = dir + '/file_example_WAV_2MG.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/file_example_WAV_2MG.wav const filePath = dir + '/file_example_WAV_2MG.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/file_example_WAV_2MG.wav
console.info(`file path: ${ path}`); console.info(`file filePath: ${ filePath}`);
let ss = fileio.createStreamSync(path, 'r');
const totalSize = fileio.statSync(path).size; // Size of the file to render. let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
let discardHeader = new ArrayBuffer(bufferSize); let stat = await fs.stat(filePath); // Music file information.
ss.readSync(discardHeader); let buf = new ArrayBuffer(bufferSize);
let rlen = 0; let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1);
rlen += bufferSize; for (let i = 0;i < len; i++) {
let options = {
let id = setInterval(() => { offset: i * this.bufferSize,
if (audioRenderer.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state. length: this.bufferSize
ss.closeSync();
await audioRenderer.stop();
clearInterval(id);
}
if (audioRenderer.state == audio.AudioState.STATE_RUNNING) {
if (rlen >= totalSize) { // The rendering stops if the file finishes reading.
ss.closeSync();
await audioRenderer.stop();
clearInterval(id);
}
let buf = new ArrayBuffer(bufferSize);
rlen += ss.readSync(buf);
console.info(`Total bytes read from file: ${rlen}`);
writeBuffer(buf);
} else {
console.info('check after next interval');
} }
}, 30); // The timer interval is set based on the audio format. The unit is millisecond. let readsize = await fs.read(file.fd, buf, options)
let writeSize = await new Promise((resolve,reject)=>{
this.audioRenderer.write(buf,(err,writeSize)=>{
if(err){
reject(err)
}else{
resolve(writeSize)
}
})
})
}
fs.close(file)
await audioRenderer.stop(); // Stop rendering.
await audioRenderer.release(); // Releases the resources.
``` ```
4. (Optional) Call **pause()** or **stop()** to pause or stop rendering. 4. (Optional) Call **pause()** or **stop()** to pause or stop rendering.
...@@ -192,7 +189,6 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th ...@@ -192,7 +189,6 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
} }
await audioRenderer.drain(); await audioRenderer.drain();
state = audioRenderer.state; state = audioRenderer.state;
} }
``` ```
...@@ -209,7 +205,6 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th ...@@ -209,7 +205,6 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
console.info('Renderer already released'); console.info('Renderer already released');
return; return;
} }
await audioRenderer.release(); await audioRenderer.release();
state = audioRenderer.state; state = audioRenderer.state;
...@@ -242,7 +237,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th ...@@ -242,7 +237,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
let audioTime : number = await audioRenderer.getAudioTime(); let audioTime : number = await audioRenderer.getAudioTime();
// Obtain a proper minimum buffer size. // Obtain a proper minimum buffer size.
let bufferSize : number = await audioRenderer.getBuffersize(); let bufferSize : number = await audioRenderer.getBufferSize();
// Obtain the audio renderer rate. // Obtain the audio renderer rate.
let renderRate : audio.AudioRendererRate = await audioRenderer.getRenderRate(); let renderRate : audio.AudioRendererRate = await audioRenderer.getRenderRate();
...@@ -424,35 +419,31 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th ...@@ -424,35 +419,31 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
let dir = globalThis.fileDir; // You must use the sandbox path. let dir = globalThis.fileDir; // You must use the sandbox path.
const path1 = dir + '/music001_48000_32_1.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/music001_48000_32_1.wav const path1 = dir + '/music001_48000_32_1.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/music001_48000_32_1.wav
console.info(`audioRender1 file path: ${ path1}`); console.info(`audioRender1 file path: ${ path1}`);
let ss1 = await fileio.createStream(path1,'r'); let file1 = fs.openSync(path1, fs.OpenMode.READ_ONLY);
const totalSize1 = fileio.statSync(path1).size; // Size of the file to render. let stat = await fs.stat(path1); // Music file information.
console.info(`totalSize1 -------: ${totalSize1}`); let buf = new ArrayBuffer(bufferSize);
let discardHeader = new ArrayBuffer(bufferSize); let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1);
ss1.readSync(discardHeader);
let rlen = 0;
rlen += bufferSize;
// 1.7 Render the original audio data in the buffer by using audioRender. // 1.7 Render the original audio data in the buffer by using audioRender.
let id = setInterval(async () => { for (let i = 0;i < len; i++) {
if (audioRenderer1.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state. let options = {
ss1.closeSync(); offset: i * this.bufferSize,
audioRenderer1.stop(); length: this.bufferSize
clearInterval(id);
} }
if (audioRenderer1.state == audio.AudioState.STATE_RUNNING) { let readsize = await fs.read(file.fd, buf, options)
if (rlen >= totalSize1) { // The rendering stops if the file finishes reading. let writeSize = await new Promise((resolve,reject)=>{
ss1.closeSync(); this.audioRenderer1.write(buf,(err,writeSize)=>{
await audioRenderer1.stop(); if(err){
clearInterval(id); reject(err)
} }else{
let buf = new ArrayBuffer(bufferSize); resolve(writeSize)
rlen += ss1.readSync(buf); }
console.info(`Total bytes read from file: ${rlen}`); })
await writeBuffer(buf, that.audioRenderer1); })
} else { }
console.info('check after next interval'); fs.close(file1)
} await audioRenderer1.stop(); // Stop rendering.
}, 30); // The timer interval is set based on the audio format. The unit is millisecond. await audioRenderer1.release(); Releases the resources.
} }
async runningAudioRender2(){ async runningAudioRender2(){
...@@ -499,36 +490,32 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th ...@@ -499,36 +490,32 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
// 2.6 Read the original audio data file. // 2.6 Read the original audio data file.
let dir = globalThis.fileDir; // You must use the sandbox path. let dir = globalThis.fileDir; // You must use the sandbox path.
const path2 = dir + '/music002_48000_32_1.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/music002_48000_32_1.wav const path2 = dir + '/music002_48000_32_1.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/music002_48000_32_1.wav
console.error(`audioRender1 file path: ${ path2}`); console.info(`audioRender2 file path: ${ path2}`);
let ss2 = await fileio.createStream(path2,'r'); let file2 = fs.openSync(path2, fs.OpenMode.READ_ONLY);
const totalSize2 = fileio.statSync(path2).size; // Size of the file to render. let stat = await fs.stat(path2); // Music file information.
console.error(`totalSize2 -------: ${totalSize2}`); let buf = new ArrayBuffer(bufferSize);
let discardHeader2 = new ArrayBuffer(bufferSize); let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1);
ss2.readSync(discardHeader2);
let rlen = 0;
rlen += bufferSize;
// 2.7 Render the original audio data in the buffer by using audioRender. // 2.7 Render the original audio data in the buffer by using audioRender.
let id = setInterval(async () => { for (let i = 0;i < len; i++) {
if (audioRenderer2.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state. let options = {
ss2.closeSync(); offset: i * this.bufferSize,
that.audioRenderer2.stop(); length: this.bufferSize
clearInterval(id);
}
if (audioRenderer1.state == audio.AudioState.STATE_RUNNING) {
if (rlen >= totalSize2) { // The rendering stops if the file finishes reading.
ss2.closeSync();
await audioRenderer2.stop();
clearInterval(id);
}
let buf = new ArrayBuffer(bufferSize);
rlen += ss2.readSync(buf);
console.info(`Total bytes read from file: ${rlen}`);
await writeBuffer(buf, that.audioRenderer2);
} else {
console.info('check after next interval');
} }
}, 30); // The timer interval is set based on the audio format. The unit is millisecond. let readsize = await fs.read(file.fd, buf, options)
let writeSize = await new Promise((resolve,reject)=>{
this.audioRenderer2.write(buf,(err,writeSize)=>{
if(err){
reject(err)
}else{
resolve(writeSize)
}
})
})
}
fs.close(file2)
await audioRenderer2.stop(); // Stop rendering.
await audioRenderer2.release(); // Releases the resources.
} }
async writeBuffer(buf, audioRender) { async writeBuffer(buf, audioRender) {
......
...@@ -104,7 +104,7 @@ The full playback process includes creating an instance, setting resources, sett ...@@ -104,7 +104,7 @@ The full playback process includes creating an instance, setting resources, sett
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
const TAG = 'AVPlayerDemo:' const TAG = 'AVPlayerDemo:'
export class AVPlayerDemo { export class AVPlayerDemo {
...@@ -223,14 +223,8 @@ export class AVPlayerDemo { ...@@ -223,14 +223,8 @@ export class AVPlayerDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
let path = pathDir + '/H264_AAC.mp4' let path = pathDir + '/H264_AAC.mp4'
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path)
fdPath = fdPath + '' + fdNumber fdPath = fdPath + '' + file.fd
console.info('open fd success fd is' + fdPath)
}, (err) => {
console.info('open fd failed err is' + err)
}).catch((err) => {
console.info('open fd failed err is' + err)
});
this.avPlayer.url = fdPath this.avPlayer.url = fdPath
} }
} }
...@@ -240,7 +234,7 @@ export class AVPlayerDemo { ...@@ -240,7 +234,7 @@ export class AVPlayerDemo {
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
const TAG = 'AVPlayerDemo:' const TAG = 'AVPlayerDemo:'
export class AVPlayerDemo { export class AVPlayerDemo {
...@@ -280,7 +274,7 @@ export class AVPlayerDemo { ...@@ -280,7 +274,7 @@ export class AVPlayerDemo {
break; break;
case 'stopped': // This state is reported upon a successful callback of stop(). case 'stopped': // This state is reported upon a successful callback of stop().
console.info(TAG + 'state stopped called') console.info(TAG + 'state stopped called')
this.avPlayer.reset() // Call reset() to initialize the AVPlayer state. this.avPlayer.release() // Call reset() to initialize the AVPlayer state.
break; break;
case 'released': case 'released':
console.info(TAG + 'state released called') console.info(TAG + 'state released called')
...@@ -302,24 +296,18 @@ export class AVPlayerDemo { ...@@ -302,24 +296,18 @@ export class AVPlayerDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
let path = pathDir + '/H264_AAC.mp4' let path = pathDir + '/H264_AAC.mp4'
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path)
fdPath = fdPath + '' + fdNumber fdPath = fdPath + '' + file.fd
console.info('open fd success fd is' + fdPath)
}, (err) => {
console.info('open fd failed err is' + err)
}).catch((err) => {
console.info('open fd failed err is' + err)
});
this.avPlayer.url = fdPath this.avPlayer.url = fdPath
} }
} }
``` ```
### Switching to the Next Video Clip ### Looping a Song
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
const TAG = 'AVPlayerDemo:' const TAG = 'AVPlayerDemo:'
export class AVPlayerDemo { export class AVPlayerDemo {
...@@ -362,7 +350,7 @@ export class AVPlayerDemo { ...@@ -362,7 +350,7 @@ export class AVPlayerDemo {
break; break;
case 'stopped': // This state is reported upon a successful callback of stop(). case 'stopped': // This state is reported upon a successful callback of stop().
console.info(TAG + 'state stopped called') console.info(TAG + 'state stopped called')
this.avPlayer.reset() // Call reset() to initialize the AVPlayer state. this.avPlayer.release() // Call reset() to initialize the AVPlayer state.
break; break;
case 'released': case 'released':
console.info(TAG + 'state released called') console.info(TAG + 'state released called')
...@@ -393,23 +381,17 @@ export class AVPlayerDemo { ...@@ -393,23 +381,17 @@ export class AVPlayerDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
let path = pathDir + '/H264_AAC.mp4' let path = pathDir + '/H264_AAC.mp4'
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path)
fdPath = fdPath + '' + fdNumber fdPath = fdPath + '' + file.fd
console.info('open fd success fd is' + fdPath)
}, (err) => {
console.info('open fd failed err is' + err)
}).catch((err) => {
console.info('open fd failed err is' + err)
});
this.avPlayer.url = fdPath this.avPlayer.url = fdPath
} }
} }
``` ```
### Looping a Song ### Switching to the Next Video Clip
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
const TAG = 'AVPlayerDemo:' const TAG = 'AVPlayerDemo:'
export class AVPlayerDemo { export class AVPlayerDemo {
...@@ -422,14 +404,8 @@ export class AVPlayerDemo { ...@@ -422,14 +404,8 @@ export class AVPlayerDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_MP3.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_MP3.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
let path = pathDir + '/H264_MP3.mp4' let path = pathDir + '/H264_MP3.mp4'
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path)
fdPath = fdPath + '' + fdNumber fdPath = fdPath + '' + file.fd
console.info('open fd success fd is' + fdPath)
}, (err) => {
console.info('open fd failed err is' + err)
}).catch((err) => {
console.info('open fd failed err is' + err)
});
this.avPlayer.url = fdPath // The initialized state is reported again. this.avPlayer.url = fdPath // The initialized state is reported again.
} }
...@@ -493,14 +469,8 @@ export class AVPlayerDemo { ...@@ -493,14 +469,8 @@ export class AVPlayerDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
let path = pathDir + '/H264_AAC.mp4' let path = pathDir + '/H264_AAC.mp4'
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path)
fdPath = fdPath + '' + fdNumber fdPath = fdPath + '' + file.fd
console.info('open fd success fd is' + fdPath)
}, (err) => {
console.info('open fd failed err is' + err)
}).catch((err) => {
console.info('open fd failed err is' + err)
});
this.avPlayer.url = fdPath this.avPlayer.url = fdPath
} }
} }
......
...@@ -69,14 +69,14 @@ export class AVRecorderDemo { ...@@ -69,14 +69,14 @@ export class AVRecorderDemo {
let surfaceID; // The surface ID is obtained by calling getInputSurface and transferred to the videoOutput object of the camera. let surfaceID; // The surface ID is obtained by calling getInputSurface and transferred to the videoOutput object of the camera.
await this.getFd('01.mp4'); await this.getFd('01.mp4');
// Configure the parameters related to audio and video recording. // Configure the parameters related to audio and video recording based on those supported by the hardware device.
let avProfile = { let avProfile = {
audioBitrate : 48000, audioBitrate : 48000,
audioChannels : 2, audioChannels : 2,
audioCodec : media.CodecMimeType.AUDIO_AAC, audioCodec : media.CodecMimeType.AUDIO_AAC,
audioSampleRate : 48000, audioSampleRate : 48000,
fileFormat : media.ContainerFormatType.CFT_MPEG_4, fileFormat : media.ContainerFormatType.CFT_MPEG_4,
videoBitrate : 48000, videoBitrate : 2000000,
videoCodec : media.CodecMimeType.VIDEO_MPEG4, videoCodec : media.CodecMimeType.VIDEO_MPEG4,
videoFrameWidth : 640, videoFrameWidth : 640,
videoFrameHeight : 480, videoFrameHeight : 480,
...@@ -365,10 +365,10 @@ export class VideoRecorderDemo { ...@@ -365,10 +365,10 @@ export class VideoRecorderDemo {
let surfaceID; // The surface ID is obtained by calling getInputSurface and transferred to the videoOutput object of the camera. let surfaceID; // The surface ID is obtained by calling getInputSurface and transferred to the videoOutput object of the camera.
await this.getFd('01.mp4'); await this.getFd('01.mp4');
// Configure the parameters related to video recording. // Configure the parameters related to pure video recording based on those supported by the hardware device.
let videoProfile = { let videoProfile = {
fileFormat : media.ContainerFormatType.CFT_MPEG_4, fileFormat : media.ContainerFormatType.CFT_MPEG_4,
videoBitrate : 48000, videoBitrate : 2000000,
videoCodec : media.CodecMimeType.VIDEO_MPEG4, videoCodec : media.CodecMimeType.VIDEO_MPEG4,
videoFrameWidth : 640, videoFrameWidth : 640,
videoFrameHeight : 480, videoFrameHeight : 480,
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
You can call the APIs provided by the **Camera** module to develop a distributed camera that provides the basic camera functions such as shooting and video recording. You can call the APIs provided by the **Camera** module to develop a distributed camera that provides the basic camera functions such as shooting and video recording.
## How to Develop ## How to Develop
Connect your calculator to a distributed device. Your calculator will call **getCameras()** to obtain the camera list and traverse the returned camera list to check **ConnectionType** of the **Camera** objects. If **ConnectionType** of a **Camera** object is **CAMERA_CONNECTION_REMOTE**, your calculator will use this object to create a **CameraInput** object. The subsequent call process is the same as that of the local camera development. For details about the local camera development, see [Camera Development](./camera.md). Connect your calculator to a distributed device. Your calculator will call **getSupportedCameras()** to obtain the camera list and traverse the returned camera list to check **ConnectionType** of the **Camera** objects. If **ConnectionType** of a **Camera** object is **CAMERA_CONNECTION_REMOTE**, your calculator will use this object to create a **cameraInput** object. The subsequent call process is the same as that of the local camera development. For details about the local camera development, see [Camera Development](./camera.md).
For details about the APIs, see [Camera Management](../reference/apis/js-apis-camera.md). For details about the APIs, see [Camera Management](../reference/apis/js-apis-camera.md).
...@@ -24,15 +24,11 @@ import media from '@ohos.multimedia.media' ...@@ -24,15 +24,11 @@ import media from '@ohos.multimedia.media'
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
// Create a CameraManager object. // Create a CameraManager object.
let cameraManager let cameraManager = camera.getCameraManager(globalThis.Context)
await camera.getCameraManager(globalThis.Context, (err, manager) => { if (!cameraManager) {
if (err) { console.error("camera.getCameraManager error")
console.error('Failed to get the CameraManager instance ${err.message}'); return;
return; }
}
console.log('Callback returned with the CameraManager instance');
cameraManager = manager
})
// Register a callback to listen for camera status changes and obtain the updated camera status information. // Register a callback to listen for camera status changes and obtain the updated camera status information.
cameraManager.on('cameraStatus', (cameraStatusInfo) => { cameraManager.on('cameraStatus', (cameraStatusInfo) => {
...@@ -41,16 +37,12 @@ cameraManager.on('cameraStatus', (cameraStatusInfo) => { ...@@ -41,16 +37,12 @@ cameraManager.on('cameraStatus', (cameraStatusInfo) => {
}) })
// Obtain the camera list. // Obtain the camera list.
let cameraArray
let remoteCamera let remoteCamera
await cameraManager.getCameras((err, cameras) => { let cameraArray = cameraManager.getSupportedCameras();
if (err) { if (cameraArray.length <= 0) {
console.error('Failed to get the cameras. ${err.message}'); console.error("cameraManager.getSupportedCameras error")
return; return;
} }
console.log('Callback returned with an array of supported cameras: ' + cameras.length);
cameraArray = cameras
})
for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) { for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) {
console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // Obtain the camera ID. console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // Obtain the camera ID.
...@@ -58,15 +50,16 @@ for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) { ...@@ -58,15 +50,16 @@ for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) {
console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type. console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type.
console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) // Obtain the camera connection type. console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) // Obtain the camera connection type.
if (cameraArray[cameraIndex].connectionType == CAMERA_CONNECTION_REMOTE) { if (cameraArray[cameraIndex].connectionType == CAMERA_CONNECTION_REMOTE) {
remoteCamera = cameraArray[cameraIndex].cameraId remoteCamera = cameraArray[cameraIndex]
} }
} }
// Create a camera input stream. // Create a camera input stream.
let cameraInput let cameraInput
await cameraManager.createCameraInput(remoteCamera).then((input) => { try {
console.log('Promise returned with the CameraInput instance'); cameraInput = cameraManager.createCameraInput(remoteCamera);
cameraInput = input } catch () {
}) console.error('Failed to createCameraInput errorCode = ' + error.code);
}
``` ```
For details about the subsequent steps, see [Camera Development](./camera.md). For details about the subsequent steps, see [Camera Development](./camera.md).
...@@ -51,7 +51,7 @@ For details about how to create an XComponent, see [XComponent](../reference/ark ...@@ -51,7 +51,7 @@ For details about how to create an XComponent, see [XComponent](../reference/ark
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
export class VideoPlayerDemo { export class VideoPlayerDemo {
// Report an error in the case of a function invocation failure. // Report an error in the case of a function invocation failure.
failureCallback(error) { failureCallback(error) {
...@@ -82,14 +82,8 @@ export class VideoPlayerDemo { ...@@ -82,14 +82,8 @@ export class VideoPlayerDemo {
let fdPath = 'fd://' let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4'; let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4';
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path);
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + file.fd;
console.info('open fd success fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
// Call createVideoPlayer to create a VideoPlayer instance. // Call createVideoPlayer to create a VideoPlayer instance.
await media.createVideoPlayer().then((video) => { await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') { if (typeof (video) != 'undefined') {
...@@ -180,7 +174,7 @@ export class VideoPlayerDemo { ...@@ -180,7 +174,7 @@ export class VideoPlayerDemo {
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
export class VideoPlayerDemo { export class VideoPlayerDemo {
// Report an error in the case of a function invocation failure. // Report an error in the case of a function invocation failure.
failureCallback(error) { failureCallback(error) {
...@@ -211,14 +205,8 @@ export class VideoPlayerDemo { ...@@ -211,14 +205,8 @@ export class VideoPlayerDemo {
let fdPath = 'fd://' let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4'; let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4';
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path);
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + file.fd;
console.info('open fd success fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
// Call createVideoPlayer to create a VideoPlayer instance. // Call createVideoPlayer to create a VideoPlayer instance.
await media.createVideoPlayer().then((video) => { await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') { if (typeof (video) != 'undefined') {
...@@ -267,7 +255,7 @@ export class VideoPlayerDemo { ...@@ -267,7 +255,7 @@ export class VideoPlayerDemo {
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
export class VideoPlayerDemo { export class VideoPlayerDemo {
// Report an error in the case of a function invocation failure. // Report an error in the case of a function invocation failure.
failureCallback(error) { failureCallback(error) {
...@@ -299,14 +287,8 @@ export class VideoPlayerDemo { ...@@ -299,14 +287,8 @@ export class VideoPlayerDemo {
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4'; let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4';
let nextPath = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/MP4_AAC.mp4'; let nextPath = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/MP4_AAC.mp4';
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path);
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + file.fd;
console.info('open fd success fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
// Call createVideoPlayer to create a VideoPlayer instance. // Call createVideoPlayer to create a VideoPlayer instance.
await media.createVideoPlayer().then((video) => { await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') { if (typeof (video) != 'undefined') {
...@@ -341,14 +323,8 @@ export class VideoPlayerDemo { ...@@ -341,14 +323,8 @@ export class VideoPlayerDemo {
// Obtain the next video FD address. // Obtain the next video FD address.
fdPath = 'fd://' fdPath = 'fd://'
await fileIO.open(nextPath).then((fdNumber) => { let nextFile = await fs.open(nextPath);
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + nextFile.fd;
console.info('open fd success fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
// Set the second video playback source. // Set the second video playback source.
videoPlayer.url = fdPath; videoPlayer.url = fdPath;
...@@ -378,7 +354,7 @@ export class VideoPlayerDemo { ...@@ -378,7 +354,7 @@ export class VideoPlayerDemo {
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fs from '@ohos.file.fs'
export class VideoPlayerDemo { export class VideoPlayerDemo {
// Report an error in the case of a function invocation failure. // Report an error in the case of a function invocation failure.
failureCallback(error) { failureCallback(error) {
...@@ -409,14 +385,8 @@ export class VideoPlayerDemo { ...@@ -409,14 +385,8 @@ export class VideoPlayerDemo {
let fdPath = 'fd://' let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4'; let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4';
await fileIO.open(path).then((fdNumber) => { let file = await fs.open(path);
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + file.fd;
console.info('open fd success fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
// Call createVideoPlayer to create a VideoPlayer instance. // Call createVideoPlayer to create a VideoPlayer instance.
await media.createVideoPlayer().then((video) => { await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') { if (typeof (video) != 'undefined') {
......
...@@ -76,14 +76,14 @@ export class VideoRecorderDemo { ...@@ -76,14 +76,14 @@ export class VideoRecorderDemo {
let surfaceID = null; // Used to save the surface ID returned by getInputSurface. let surfaceID = null; // Used to save the surface ID returned by getInputSurface.
// Obtain the FD address of the video to be recorded. // Obtain the FD address of the video to be recorded.
await this.getFd('01.mp4'); await this.getFd('01.mp4');
// Recording-related parameter settings // Configure the parameters related to video recording based on those supported by the hardware device.
let videoProfile = { let videoProfile = {
audioBitrate : 48000, audioBitrate : 48000,
audioChannels : 2, audioChannels : 2,
audioCodec : 'audio/mp4a-latm', audioCodec : 'audio/mp4a-latm',
audioSampleRate : 48000, audioSampleRate : 48000,
fileFormat : 'mp4', fileFormat : 'mp4',
videoBitrate : 48000, videoBitrate : 2000000,
videoCodec : 'video/mp4v-es', videoCodec : 'video/mp4v-es',
videoFrameWidth : 640, videoFrameWidth : 640,
videoFrameHeight : 480, videoFrameHeight : 480,
......
...@@ -4,9 +4,7 @@ OpenHarmony applications use JavaScript (JS) when calling native APIs. The nativ ...@@ -4,9 +4,7 @@ OpenHarmony applications use JavaScript (JS) when calling native APIs. The nativ
## How to Develop ## How to Develop
The DevEco Studio has a default project that uses NAPIs. The DevEco Studio has a default project that uses NAPIs. You can choose **File** > **New** > **Create Project** to create a **Native C++** project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **ace_napi** repository for development.
You can choose **File** > **New** > **Create Project** to create a **Native C++** project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **ace_napi** repository for development.
You can import the native .so that contains the JS processing logic. For example, **import hello from 'libhello.so'** to use the **libhello.so** capability. Then, the JS object created using the NAPI can be passed to the **hello** object of the application to call the native capability. You can import the native .so that contains the JS processing logic. For example, **import hello from 'libhello.so'** to use the **libhello.so** capability. Then, the JS object created using the NAPI can be passed to the **hello** object of the application to call the native capability.
...@@ -19,7 +17,10 @@ You can import the native .so that contains the JS processing logic. For example ...@@ -19,7 +17,10 @@ You can import the native .so that contains the JS processing logic. For example
### .so Naming Rules ### .so Naming Rules
Each module has a .so file. For example, if the module name is **hello**, name the .so file **libhello.so**. The **nm_modname** field in **napi_module** must be **hello**, which is the same as the module name. The sample code for importing the .so file is **import hello from 'libhello.so'**. The .so file names must comply with the following rules:
* Each module has a .so file.
* The **nm_modname** field in **napi_module** must be the same as the module name. For example, if the module name is **hello**, name the .so file **libhello.so**. The sample code for importing the .so file is **import hello from 'libhello.so'**.
### JS Objects and Threads ### JS Objects and Threads
......
...@@ -13,6 +13,7 @@ The **app** tag contains application-wide configuration. The internal structure ...@@ -13,6 +13,7 @@ The **app** tag contains application-wide configuration. The internal structure
| apiVersion | OpenHarmony API version on which the application depends.| Object| Yes (initial value: left empty)| | apiVersion | OpenHarmony API version on which the application depends.| Object| Yes (initial value: left empty)|
| smartWindowSize | Screen size used when the application runs in the emulator.| String| Yes (initial value: left empty)| | smartWindowSize | Screen size used when the application runs in the emulator.| String| Yes (initial value: left empty)|
| smartWindowDeviceType | Types of emulated devcies on which the application can run.| String array| Yes (initial value: left empty)| | smartWindowDeviceType | Types of emulated devcies on which the application can run.| String array| Yes (initial value: left empty)|
| assanEnabled | Whether to enable AddressSanitizer (ASan) to detect memory corruption issues such as buffer overflows.<br>- **true**: ASan is enabled.<br>- **false**: ASan is disabled. Note that ASan is not available in the Release version.| Boolean| Yes (initial value: **false**)|
## Internal Structure of the version Atttribute ## Internal Structure of the version Atttribute
......
...@@ -123,7 +123,7 @@ export default class EntryAbility extends UIAbility { ...@@ -123,7 +123,7 @@ export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
// storage is passed to the loadContent API as a parameter. // storage is passed to the loadContent API as a parameter.
windowStage.loadContent('pages/index', this.storage) windowStage.loadContent('pages/Index', this.storage)
} }
onWindowStageDestroy() { onWindowStageDestroy() {
...@@ -143,7 +143,7 @@ export default class EntryAbility extends UIAbility { ...@@ -143,7 +143,7 @@ export default class EntryAbility extends UIAbility {
The **@Component** decorated component obtains data. The **@Component** decorated component obtains data.
```ts ```ts
// index.ets // Index.ets
let storage = LocalStorage.GetShared() let storage = LocalStorage.GetShared()
@Entry(storage) @Entry(storage)
......
...@@ -494,7 +494,7 @@ struct CompA { ...@@ -494,7 +494,7 @@ struct CompA {
this.updateTotal() this.updateTotal()
} }
updateTotal(): number { updateTotal(): void {
let sum = 0; let sum = 0;
this.shopBasket.forEach((i) => { this.shopBasket.forEach((i) => {
sum += i sum += i
......
...@@ -3,25 +3,27 @@ ...@@ -3,25 +3,27 @@
DevEco Studio allows you to develop and build multiple HAP files in one application project, as shown below. DevEco Studio allows you to develop and build multiple HAP files in one application project, as shown below.
**Figure 1** Multi-HAP build view
**Figure 1** Multi-HAP build view
![hap-multi-view](figures/hap-multi-view.png) ![hap-multi-view](figures/hap-multi-view.png)
1. Development view in DevEco Studio 1. Development view in DevEco Studio
- AppScope folder - **AppScope** folder
- [app.json5](app-configuration-file.md): application-wide configuration, such as the application bundle name, version number, application icon, application name, and dependent SDK version number.
- **[app.json5](app-configuration-file.md)**: stores application-wide configuration, such as the application bundle name, version number, application icon, application name, and dependent SDK version number.
- **resources** folder: stores application icon resources and application name string resources. - **resources** folder: stores application icon resources and application name string resources.
**NOTE** **NOTE**
- The folder is automatically generated by DevEco Studio and its name cannot be changed.
- The file names in the **AppScope** folder cannot be the same as those in the entry- or feature-type module directories. Otherwise, DevEco Studio reports an error. - The folder is automatically generated by DevEco Studio and its name cannot be changed.
- Entry- or feature-type module directories (the names are customizable) - The file names in the **AppScope** folder cannot be the same as those in the entry- or feature-type module folder. Otherwise, an error will be reported.
- You implement service logic of your application in these module directories. In this example, the module folders are **entry.hap** and **feature.hap**. - **entry** or **feature** folder (whose name is customizable)
- **resources** directory: stores the resources used by the module. - A module folder created by the developer by following the creation wizard of DevEco Studio. It stores the service logic implementation of the application. Multiple module folders can be created. In the preceding figure, **entry** and **feature** are two created module folders.
- **resources** folder: stores the resources used by the module.
- **ets** folder: stores the service logic. - **ets** folder: stores the service logic.
- [module.json5](module-configuration-file.md): module configuration, such as the module name, entry code path of the module, and component information. - **[module.json5](module-configuration-file.md)**: stores module configuration, such as the module name, entry code path of the module, and component information.
2. View after build and packaging 2. View after build and packaging
- After a module is built, a HAP file for deployment is generated. Each module corresponds to a HAP file. - After a module is built, a HAP file for deployment is generated. Each module corresponds to a HAP file.
- The **module.json** file in the HAP file is composed of the **app.json5** and **module.json5** files in the development view. - The **module.json** file in the HAP file is composed of the **app.json5** and **module.json5** files in the development view.
......
...@@ -6,32 +6,40 @@ Below is the process of developing, debugging, releasing, and deploying multiple ...@@ -6,32 +6,40 @@ Below is the process of developing, debugging, releasing, and deploying multiple
![hap-release](figures/hap-release.png) ![hap-release](figures/hap-release.png)
## Development ## Development
You can use [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio) to create multiple modules based on service requirements and develop services in independent modules. You can use [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio) to create multiple modules as needed and develop services in respective modules.
## Debugging ## Debugging
You can use DevEco Studio to build code into one or more HAP files. Then, you can debug the HAP files. After building code into one or more HAP files and installing or updating these HAP files, you can debug them by using the methods:
* Using DevEco Studio for debugging * Using DevEco Studio for debugging
Follow the instructions in [Debugging Configuration](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-debugging-and-running-0000001263040487#section10491183521520). Follow the instructions in [Debugging Configuration](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-debugging-and-running-0000001263040487#section10491183521520).
* Using [hdc_std](../../device-dev/subsystems/subsys-toolchain-hdc-guide.md) for debugging * Using [hdc](../../device-dev/subsystems/subsys-toolchain-hdc-guide.md) (which can be obtained in the **toolchains** directory of the OpenHarmony SDK) for debugging
Before debugging HAP files, install or update them using either of the methods:
1. Use hdc to install and update the HAP files.
When specifying the HAP files, use the paths of the files on the operating system, for example, Windows.
You can obtain the hdc_std tool from the **toolchains** directory of the SDK. When using this tool to install an HAP file, the HAP file path is the one on the operating platform. In this example, the Windows operating platform is used. The command reference is as follows:
``` ```
// Installation and update: Multiple file paths can be specified. // Installation and update: Multiple file paths can be specified.
hdc_std install C:\entry.hap C:\feature.hap hdc install C:\entry.hap C:\feature.hap
// The execution result is as follows: // The execution result is as follows:
install bundle successfully. install bundle successfully.
// Uninstall // Uninstall
hdc_std uninstall com.example.myapplication hdc uninstall com.example.myapplication
// The execution result is as follows: // The execution result is as follows:
uninstall bundle successfully. uninstall bundle successfully.
``` ```
2. Run the hdc shell command, and then use the Bundle Manager (bm) tool to install and update the HAP files.
* Using [Bundle Manager (bm)](../../application-dev/tools/bm-tool.md) for debugging When specifying the HAP files, use the paths of the files on the real device. The sample code is as follows:
When using bm to install or update an HAP file, the HAP file path is the one on the real device. The command reference is as follows:
``` ```
// Run the hdc shell command before using the bm tool.
hdc shell
// Installation and update: Multiple file paths can be specified. // Installation and update: Multiple file paths can be specified.
bm install -p /data/app/entry.hap /data/app/feature.hap bm install -p /data/app/entry.hap /data/app/feature.hap
// The execution result is as follows: // The execution result is as follows:
...@@ -41,6 +49,8 @@ You can use DevEco Studio to build code into one or more HAP files. Then, you ca ...@@ -41,6 +49,8 @@ You can use DevEco Studio to build code into one or more HAP files. Then, you ca
// The execution result is as follows: // The execution result is as follows:
uninstall bundle successfully. uninstall bundle successfully.
``` ```
After the HAP files are installed or updated, you can debug them by following the instructions in [Ability Assistant](https://docs.openharmony.cn/pages/v3.2Beta/en/application-dev/tools/aa-tool.md/).
## Release ## Release
When your application package meets the release requirements, you can package and build it into an App Pack and release it to the application market on the cloud. The application market verifies the signature of the App Pack. If the signature verification is successful, the application market obtains the HAP files from the App Pack, signs them, and distributes the signed HAP files. When your application package meets the release requirements, you can package and build it into an App Pack and release it to the application market on the cloud. The application market verifies the signature of the App Pack. If the signature verification is successful, the application market obtains the HAP files from the App Pack, signs them, and distributes the signed HAP files.
......
# Multi-HAP Usage Rules # Multi-HAP Usage Rules
- The App Pack cannot be directly installed on the device. It is only a unit that is released to AppGallery. - The App Pack cannot be directly installed on a device. It is only used to be released to the application market.
- All HAP files in the App Pack must share the same **bundleName** value in the configuration files. - All HAP files in the App Pack must share the same **bundleName** value in the configuration files.
- All HAP files in the App Pack must share the same **versionCode** value in the configuration files. - All HAP files in the App Pack must share the same **versionCode** value in the configuration files.
- In an application, each type of device supports only one HAP of the entry type. Each application can contain zero, one, or more HAP files of the feature type. - In an App Pack, each type of device supports only one HAP file of the entry type and zero, one, or more HAP files of the feature type.
- Each HAP file in the App Pack must have **moduleName** configured. The **moduleName** value corresponding to all HAP files of the same device type must be unique. - Each HAP file in the App Pack must have **moduleName** configured. Among HAP files of the same device type, the **moduleName** value must be unique.
- The signing certificates of all HAP files in the same application must be the same. Applications are released to the application market in the form of App Pack after being signed. Before distribution, the application market splits an App Pack into HAP files and resigns them to ensure the consistency of all HAP file signing certificates. Before installing HAP files on a device through the CLI or DevEco Studio for debugging, you must ensure that their signing certificates are the same. Otherwise, the installation will fail. - The signing certificates of all HAP files in the same application must be the same. Applications are released to the application market in the form of App Pack after being signed. Before distribution, the application market splits an App Pack into HAP files and resigns them to ensure the consistency of HAP file signing certificates. Before installing HAP files on a device through the CLI or DevEco Studio for debugging, ensure that their signing certificates are the same. Otherwise, the installation will fail.
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
> >
> To use ArkTS, your DevEco Studio must be V3.0.0.601 Beta1 or later. > To use ArkTS, your DevEco Studio must be V3.0.0.601 Beta1 or later.
> >
> For best possible results, use [DevEco Studio V3.1.0.100](https://developer.harmonyos.com/cn/develop/deveco-studio) for your development. > For best possible results, use [DevEco Studio 3.1 Beta1](https://developer.harmonyos.com/cn/develop/deveco-studio) for your development.
## Creating an ArkTS Project ## Creating an ArkTS Project
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
> >
> To use ArkTS, your DevEco Studio must be V3.0.0.900 Beta3 or later. > To use ArkTS, your DevEco Studio must be V3.0.0.900 Beta3 or later.
> >
> For best possible results, use [DevEco Studio V3.1.0.100](https://developer.harmonyos.com/cn/develop/deveco-studio) for your development. > For best possible results, use [DevEco Studio 3.1 Beta1](https://developer.harmonyos.com/cn/develop/deveco-studio) for your development.
## Creating an ArkTS Project ## Creating an ArkTS Project
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
> **NOTE** > **NOTE**
> >
> For best possible results, use [DevEco Studio V3.0.0.993](https://developer.harmonyos.com/cn/develop/deveco-studio#download) for your development. > For best possible results, use [DevEco Studio 3.1 Beta1](https://developer.harmonyos.com/cn/develop/deveco-studio#download) for your development.
## Creating a JavaScript Project ## Creating a JavaScript Project
......
...@@ -921,3 +921,7 @@ Indicates that the SPN displayed has been updated. ...@@ -921,3 +921,7 @@ Indicates that the SPN displayed has been updated.
Indicates the result of applying a quick fix to the application. Indicates the result of applying a quick fix to the application.
- Value: **usual.event.QUICK_FIX_APPLY_RESULT** - Value: **usual.event.QUICK_FIX_APPLY_RESULT**
- Required subscriber permissions: none - Required subscriber permissions: none
## COMMON_EVENT_HTTP_PROXY_CHANGE<sup>10+<sup>
Indicates that the HTTP proxy configuration has changed.
- Value: **usual.event.HTTP_PROXY_CHANGE**
- Required subscriber permissions: none
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册