提交 5a5a8391 编写于 作者: S shawn_he 提交者: Gitee

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

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
...@@ -17,3 +17,4 @@ OpenHarmony_Icons.zip filter=lfs diff=lfs merge=lfs -text ...@@ -17,3 +17,4 @@ OpenHarmony_Icons.zip filter=lfs diff=lfs merge=lfs -text
zip filter=lfs diff=lfs merge=lfs -text zip filter=lfs diff=lfs merge=lfs -text
figures/OpenHarmony_Icons.zip filter=lfs diff=lfs merge=lfs -text figures/OpenHarmony_Icons.zip filter=lfs diff=lfs merge=lfs -text
figures/OpenHarmony应用图标模版.zip filter=lfs diff=lfs merge=lfs -text figures/OpenHarmony应用图标模版.zip filter=lfs diff=lfs merge=lfs -text
figures/OpenHarmony_天气应用UX设计交付件_V1.0.zip filter=lfs diff=lfs merge=lfs -text
...@@ -199,9 +199,9 @@ zh-cn/application-dev/reference/apis/js-apis-appmanager.md @littlejerry1 @RayShi ...@@ -199,9 +199,9 @@ zh-cn/application-dev/reference/apis/js-apis-appmanager.md @littlejerry1 @RayShi
zh-cn/application-dev/reference/apis/js-apis-arraylist.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh zh-cn/application-dev/reference/apis/js-apis-arraylist.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
zh-cn/application-dev/reference/apis/js-apis-audio.md @liuyuehua1 @zengyawen @magekkkk @currydavids zh-cn/application-dev/reference/apis/js-apis-audio.md @liuyuehua1 @zengyawen @magekkkk @currydavids
zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-battery-info.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-battery-info.md @zengyawen @alien0208
zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125
zh-cn/application-dev/reference/apis/js-apis-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-brightness.md @zengyawen @alien0208
zh-cn/application-dev/reference/apis/js-apis-buffer.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh zh-cn/application-dev/reference/apis/js-apis-buffer.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
zh-cn/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @shuaytao @RayShih @wangzhen107 @inter515
...@@ -321,7 +321,7 @@ zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @han-zhengshi @ge-yaf ...@@ -321,7 +321,7 @@ zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @han-zhengshi @ge-yaf
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-oh zh-cn/application-dev/reference/apis/js-apis-plainarray.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
zh-cn/application-dev/reference/apis/js-apis-pointer.md @yuanxinying @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-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 @zengyawen @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-oh zh-cn/application-dev/reference/apis/js-apis-process.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
zh-cn/application-dev/reference/apis/js-apis-processrunninginfo.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-processrunninginfo.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
...@@ -334,7 +334,7 @@ zh-cn/application-dev/reference/apis/js-apis-request.md @feng-aiwen @ningningW @ ...@@ -334,7 +334,7 @@ zh-cn/application-dev/reference/apis/js-apis-request.md @feng-aiwen @ningningW @
zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @Buda-Liu @ningningW @mengjingzhimo @yangqing3 zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @Buda-Liu @ningningW @mengjingzhimo @yangqing3
zh-cn/application-dev/reference/apis/js-apis-router.md @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-router.md @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-rpc.md @xuepianpian @RayShih @zhaopeng_gitee @vagrant_world zh-cn/application-dev/reference/apis/js-apis-rpc.md @xuepianpian @RayShih @zhaopeng_gitee @vagrant_world
zh-cn/application-dev/reference/apis/js-apis-runninglock.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-runninglock.md @zengyawen @alien0208
zh-cn/application-dev/reference/apis/js-apis-screen.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers zh-cn/application-dev/reference/apis/js-apis-screen.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers
zh-cn/application-dev/reference/apis/js-apis-screenshot.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers zh-cn/application-dev/reference/apis/js-apis-screenshot.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers
zh-cn/application-dev/reference/apis/js-apis-securityLabel.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-securityLabel.md @panqinxu @zengyawen @bubble_mao @jinhaihw
...@@ -349,9 +349,9 @@ zh-cn/application-dev/reference/apis/js-apis-stack.md @gongjunsong @ge-yafang @f ...@@ -349,9 +349,9 @@ zh-cn/application-dev/reference/apis/js-apis-stack.md @gongjunsong @ge-yafang @f
zh-cn/application-dev/reference/apis/js-apis-statfs.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-statfs.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-storage-statistics.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-storage-statistics.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-system-app.md @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-system-app.md @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-system-battery.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-system-battery.md @zengyawen @alien0208
zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125
zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @zengyawen @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-date-time.md @feng-aiwen @ningningW @illybyy @murphy1984
...@@ -374,7 +374,7 @@ zh-cn/application-dev/reference/apis/js-apis-system-timer.md @feng-aiwen @ningni ...@@ -374,7 +374,7 @@ zh-cn/application-dev/reference/apis/js-apis-system-timer.md @feng-aiwen @ningni
zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain
zh-cn/application-dev/reference/apis/js-apis-telephony-data.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-telephony-data.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-testRunner.md @inter515 @littlejerry1 @RayShih @inter515 @jiyong zh-cn/application-dev/reference/apis/js-apis-testRunner.md @inter515 @littlejerry1 @RayShih @inter515 @jiyong
zh-cn/application-dev/reference/apis/js-apis-thermal.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-thermal.md @zengyawen @alien0208
zh-cn/application-dev/reference/apis/js-apis-timer.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh zh-cn/application-dev/reference/apis/js-apis-timer.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
zh-cn/application-dev/reference/apis/js-apis-touchevent.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-touchevent.md @mayunteng_1 @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-shortKey.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-shortKey.md @mayunteng_1 @ningningW @cococoler @alien0208
...@@ -425,7 +425,7 @@ zh-cn/application-dev/reference/apis/js-apis-application-configuration.md @littl ...@@ -425,7 +425,7 @@ zh-cn/application-dev/reference/apis/js-apis-application-configuration.md @littl
zh-cn/application-dev/reference/apis/js-apis-application-configurationConstant.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-application-configurationConstant.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-application-quickFixManager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-application-quickFixManager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-avsession.md @liuyuehua1 @zengyawen @saga2020 @currydavids zh-cn/application-dev/reference/apis/js-apis-avsession.md @liuyuehua1 @zengyawen @saga2020 @currydavids
zh-cn/application-dev/reference/apis/js-apis-batteryStatistics.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-batteryStatistics.md @zengyawen @alien0208
zh-cn/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md @shuaytao @RayShih @wangzhen107 @inter515
......
# Multi-device Collaboration (for System Applications Only) # Multi-device Collaboration
## When to Use ## When to Use
...@@ -57,29 +57,31 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -57,29 +57,31 @@ On device A, touch the **Start** button provided by the initiator application to
3. Obtain the device ID of the target device. 3. Obtain the device ID of the target device.
```ts ```ts
import deviceManager from '@ohos.distributedHardware.deviceManager'; import deviceManager from '@ohos.distributedDeviceManager';
let dmClass; let dmClass: deviceManager.DeviceManager;
function initDmClass() { function initDmClass() {
// createDeviceManager is a system API. // createDeviceManager is a system API.
deviceManager.createDeviceManager('ohos.samples.demo', (err, dm) => { try{
if (err) { dmClass = deviceManager.createDeviceManager('ohos.samples.demo');
... } catch(err) {
return console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
} }
dmClass = dm
})
} }
function getRemoteDeviceId() { function getRemoteDeviceId() {
if (typeof dmClass === 'object' && dmClass !== null) { if (typeof dmClass === 'object' && dmClass !== null) {
let list = dmClass.getTrustedDeviceListSync() let list = dmClass.getAvailableDeviceListSync();
if (typeof (list) === 'undefined' || typeof (list.length) === 'undefined') { if (typeof (list) === 'undefined' || typeof (list.length) === 'undefined') {
console.info('EntryAbility onButtonClick getRemoteDeviceId err: list is null') console.info('getRemoteDeviceId err: list is null');
return;
}
if (list.length === 0) {
console.info("getRemoteDeviceId err: list is empty");
return; return;
} }
return list[0].deviceId return list[0].networkId;
} else { } else {
console.info('EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null') console.info('getRemoteDeviceId err: dmClass is null');
} }
} }
``` ```
...@@ -90,8 +92,8 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -90,8 +92,8 @@ On device A, touch the **Start** button provided by the initiator application to
let want = { let want = {
deviceId: getRemoteDeviceId(), deviceId: getRemoteDeviceId(),
bundleName: 'com.example.myapplication', bundleName: 'com.example.myapplication',
abilityName: 'FuncAbility', abilityName: 'EntryAbility',
moduleName: 'module1', // moduleName is optional. moduleName: 'entry', // moduleName is optional.
} }
// context is the AbilityContext of the initiator UIAbility. // context is the AbilityContext of the initiator UIAbility.
this.context.startAbility(want).then(() => { this.context.startAbility(want).then(() => {
...@@ -217,7 +219,7 @@ A system application can connect to a service on another device by calling [conn ...@@ -217,7 +219,7 @@ A system application can connect to a service on another device by calling [conn
2. Display a dialog box to ask for authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization). 2. Display a dialog box to ask for authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization).
3. (Optional) [Implement a background service](serviceextensionability.md#implementing-a-background-service). Perform this operation only if no background service is available. 3. (Optional) [Implement a background service](serviceextensionability.md#implementing-a-background-service-for-system-applications-only). Perform this operation only if no background service is available.
4. Connect to the background service. 4. Connect to the background service.
- Implement the **IAbilityConnection** class. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a service is connected, **onDisconnect()** is invoked when a service is unexpectedly disconnected, and **onFailed()** is invoked when the connection to a service fails. - Implement the **IAbilityConnection** class. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a service is connected, **onDisconnect()** is invoked when a service is unexpectedly disconnected, and **onFailed()** is invoked when the connection to a service fails.
...@@ -477,8 +479,8 @@ The following describes how to implement multi-device collaboration through cros ...@@ -477,8 +479,8 @@ The following describes how to implement multi-device collaboration through cros
```ts ```ts
const MSG_SEND_METHOD: string = 'CallSendMsg'; const MSG_SEND_METHOD: string = 'CallSendMsg';
originMsg: string = ''; let originMsg: string = '';
backMsg: string = ''; let backMsg: string = '';
async onButtonCallWithResult(originMsg, backMsg) { async onButtonCallWithResult(originMsg, backMsg) {
try { try {
let msg = new MyParcelable(1, originMsg); let msg = new MyParcelable(1, originMsg);
......
...@@ -20,12 +20,15 @@ In OpenHarmony, distributed operations across devices are called continuation (a ...@@ -20,12 +20,15 @@ In OpenHarmony, distributed operations across devices are called continuation (a
- **Multi-device collaboration** - **Multi-device collaboration**
Multi-device collaboration provides users with more efficient and immersive experience than with a single device. A typical multi-device collaboration scenario is as follows: You open the same note on devices A and B. On device A, you select images from the local Gallery, insert them to the note, and edit them. On device B, you edit the text. Another typical scenario is as follows: You are chatting with a customer on device A, and the customer asks for a file, which is stored on device B. You can use the chat software to open the file application on device B, select the required file, and send it back to device A. Then, you use the chat software to send it to the customer. From the perspective of application development, multi-device collaboration enables different UIAbility or ServiceExtensionAbility components to run simultaneously or alternately on multiple devices to provide a complete service, or enables the same UIAbility and ServiceExtensionAbility component to run simultaneously on multiple devices to provide a complete service. Multi-device collaboration provides users with more efficient and immersive experience than with a single device. Multi-device collaboration is used in the following typical scenarios:
- Scenario 1: You open the same note on devices A and B. On device A, you select images from the local Gallery, insert them to the note, and edit them. On device B, you edit the text.
- Scenario 2: : You are chatting with a customer on device A, and the customer asks for a file, which is stored on device B. You can use the chat software to open the file application on device B, select the required file, and send it back to device A. Then, you use the chat software to send it to the customer. From the perspective of application development, multi-device collaboration enables different UIAbility or ServiceExtensionAbility components to run simultaneously or alternately on multiple devices to provide a complete service, or enables the same UIAbility and ServiceExtensionAbility component to run simultaneously on multiple devices to provide a complete service.
## Continuation Architecture ## Continuation Architecture
OpenHarmony provides a set of APIs for you to implement continuation in your applications. The continuation architecture has the following advantages: OpenHarmony provides APIs for you to implement continuation in your applications. The continuation architecture has the following advantages:
- Capabilities such as remote service invocation to facilitate service design - Capabilities such as remote service invocation to facilitate service design
...@@ -39,9 +42,9 @@ The following figure shows the continuation architecture. ...@@ -39,9 +42,9 @@ The following figure shows the continuation architecture.
![hop-structure](figures/hop-structure.png) ![hop-structure](figures/hop-structure.png)
- Cross-device migration mission management: The initiator accepts a migration request from the user, provides a migration entry, and displays the migration result. (This capability is unavailable yet.) - Cross-device migration mission management: The initiator accepts a migration request from the user, provides a migration entry, and displays the migration result.
- Multi-device collaboration mission management: The initiator accepts an application registration request and provides management capabilities such as starting or stopping collaboration and status display. (This capability is unavailable yet.) - Multi-device collaboration mission management: The initiator accepts an application registration request and provides management capabilities such as starting or stopping collaboration and status display.
- Distributed component management: provides capabilities such as remote service startup, remote service connection, and remote migration, and provides applications with cross-device migration or multi-device collaboration based on a combination of these capabilities. - Distributed component management: provides capabilities such as remote service startup, remote service connection, and remote migration, and provides applications with cross-device migration or multi-device collaboration based on a combination of these capabilities.
......
...@@ -6,16 +6,16 @@ ...@@ -6,16 +6,16 @@
| onShow?(): void; | \@ohos.window.d.ts | [on(eventType: 'windowStageEvent', callback: Callback&lt;WindowStageEventType&gt;): void;](../reference/apis/js-apis-window.md#onwindowstageevent9)<br>Listens for the switching to the [foreground](../reference/apis/js-apis-window.md#windowstageeventtype9).| | onShow?(): void; | \@ohos.window.d.ts | [on(eventType: 'windowStageEvent', callback: Callback&lt;WindowStageEventType&gt;): void;](../reference/apis/js-apis-window.md#onwindowstageevent9)<br>Listens for the switching to the [foreground](../reference/apis/js-apis-window.md#windowstageeventtype9).|
| onHide?(): void; | \@ohos.window.d.ts | [on(eventType: 'windowStageEvent', callback: Callback&lt;WindowStageEventType&gt;): void;](../reference/apis/js-apis-window.md#onwindowstageevent9)<br>Listens for the switching to the [background](../reference/apis/js-apis-window.md#windowstageeventtype9).| | onHide?(): void; | \@ohos.window.d.ts | [on(eventType: 'windowStageEvent', callback: Callback&lt;WindowStageEventType&gt;): void;](../reference/apis/js-apis-window.md#onwindowstageevent9)<br>Listens for the switching to the [background](../reference/apis/js-apis-window.md#windowstageeventtype9).|
| onDestroy?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onDestroy(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityondestroy) | | onDestroy?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onDestroy(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityondestroy) |
| onCreate?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate) | | onCreate?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate) |
| onWindowDisplayModeChanged?(isShownInMultiWindow: boolean, newConfig: resourceManager.Configuration): void; | There is no corresponding API in the stage model.| No corresponding API is provided.| | onWindowDisplayModeChanged?(isShownInMultiWindow: boolean, newConfig: resourceManager.Configuration): void; | There is no corresponding API in the stage model.| No corresponding API is provided.|
| onStartContinuation?(): boolean; | There is no corresponding API in the stage model.| In the stage model, an application does not need to detect whether the continuation is successful (detected when the application initiates the continuation request). Therefore, the **onStartContinuation()** callback is deprecated.| | onStartContinuation?(): boolean; | There is no corresponding API in the stage model.| In the stage model, an application does not need to detect whether the continuation is successful (detected when the application initiates the continuation request). Therefore, the **onStartContinuation()** callback is deprecated.|
| onSaveData?(data: Object): boolean; | \@ohos.app.ability.UIAbility.d.ts | [onContinue(wantParam : {[key: string]: Object}): AbilityConstant.OnContinueResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) | | onSaveData?(data: Object): boolean; | \@ohos.app.ability.UIAbility.d.ts | [onContinue(wantParam : {[key: string]: Object}): AbilityConstant.OnContinueResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) |
| onCompleteContinuation?(result: number): void; | application\ContinueCallback.d.ts | [onContinueDone(result: number): void;](../reference/apis/js-apis-distributedMissionManager.md#continuecallback) | | onCompleteContinuation?(result: number): void; | application\ContinueCallback.d.ts | [onContinueDone(result: number): void;](../reference/apis/js-apis-distributedMissionManager.md#continuecallback) |
| onRestoreData?(data: Object): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)<br>[onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)<br>In multiton or singleton mode, the target ability completes data restoration in the **onCreate()** callback. In the callback, **launchParam.launchReason** is used to determine whether it is a continuation-based launch scenario. If it is, the data saved before continuation can be obtained from the **want** parameter.| | onRestoreData?(data: Object): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)<br>[onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)<br>In multiton or singleton mode, the target ability completes data restoration in the **onCreate()** callback. In the callback, **launchParam.launchReason** is used to determine whether it is a continuation-based launch scenario. If it is, the data saved before continuation can be obtained from the **want** parameter.|
| onRemoteTerminated?(): void; | application\ContinueCallback.d.ts | [onContinueDone(result: number): void;](../reference/apis/js-apis-distributedMissionManager.md#continuecallback) | | onRemoteTerminated?(): void; | application\ContinueCallback.d.ts | [onContinueDone(result: number): void;](../reference/apis/js-apis-distributedMissionManager.md#continuecallback) |
| onSaveAbilityState?(outState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: Object}): AbilityConstant.OnSaveResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonsavestate) | | onSaveAbilityState?(outState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: Object}): AbilityConstant.OnSaveResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonsavestate) |
| onRestoreAbilityState?(inState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)<br>After an application is restarted, the **onCreate()** callback is triggered. In the callback, **launchParam.launchReason** is used to determine whether it is a self-recovery scenario. If it is, the data saved before the restart can be obtained from the **want** parameter.| | onRestoreAbilityState?(inState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)<br>After an application is restarted, the **onCreate()** callback is triggered. In the callback, **launchParam.launchReason** is used to determine whether it is a self-recovery scenario. If it is, the data saved before the restart can be obtained from the **want** parameter.|
| onInactive?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onBackground(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonbackground) | | onInactive?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onBackground(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonbackground) |
| onActive?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onForeground(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonforeground) | | onActive?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onForeground(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonforeground) |
| onNewWant?(want: Want): void; | \@ohos.app.ability.UIAbility.d.ts | [onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) | | onNewWant?(want: Want): void; | \@ohos.app.ability.UIAbility.d.ts | [onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) |
| onMemoryLevel?(level: number): void | \@ohos.app.ability.UIAbility.d.ts | [onMemoryLevel(level: AbilityConstant.MemoryLevel): void;](../reference/apis/js-apis-app-ability-ability.md#abilityonmemorylevel) | | onMemoryLevel?(level: number): void | \@ohos.app.ability.UIAbility.d.ts | [onMemoryLevel(level: AbilityConstant.MemoryLevel): void;](../reference/apis/js-apis-app-ability-ability.md#abilityonmemorylevel) |
...@@ -8,30 +8,30 @@ The PageAbility component in the FA model corresponds to the UIAbility component ...@@ -8,30 +8,30 @@ The PageAbility component in the FA model corresponds to the UIAbility component
2. Migrate the PageAbility code to the UIAbility. 2. Migrate the PageAbility code to the UIAbility.
The PageAbility lifecycle is basically the same as the UIAbility lifecycle. The table below describes the details. The PageAbility lifecycle is basically the same as the UIAbility lifecycle. The table below describes the details.
| PageAbility| UIAbility| Mapping Description| | PageAbility| UIAbility| Mapping Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| onCreate(): void| onCreate(want: Want, param: AbilityConstant.LaunchParam): void | The two methods have the same meaning and invoking time. In the stage model, parameters are added to the callback so that you can obtain startup-related data during creation.| | onCreate(): void| onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void | The two methods have the same meaning and invoking time. In the stage model, parameters are added to the callback so that you can obtain startup-related data during creation.|
| NA | onWindowStageCreate(windowStage: window.WindowStage): void| This method is available only in the stage model. The callback is invoked when a window is created.| | NA | onWindowStageCreate(windowStage: window.WindowStage): void| This method is available only in the stage model. The callback is invoked when a window is created.|
| onActive(): void | on(eventType: 'windowStageEvent', callback: Callback&lt;WindowStageEventType&gt;): void;<br>WindowStageEventType.ACTIVE | The two methods have the same meaning and invoking time. In the stage model, this method is moved to the window object.| | onActive(): void | on(eventType: 'windowStageEvent', callback: Callback&lt;WindowStageEventType&gt;): void;<br>WindowStageEventType.ACTIVE | The two methods have the same meaning and invoking time. In the stage model, this method is moved to the window object.|
| onShow(): void | onForeground(): void | The two methods have the same meaning, invoking time, and parameters.| | onShow(): void | onForeground(): void | The two methods have the same meaning, invoking time, and parameters.|
| onNewWant(want: Want): void| onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void| The two methods have the same meaning and invoking time. In the stage model, the **LaunchParam** parameter is added to notify the application of the startup cause.| | onNewWant(want: Want): void| onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void | The two methods have the same meaning and invoking time. In the stage model, the **LaunchParam** parameter is added to notify the application of the startup cause.|
| onInactive(): void| on(eventType: 'windowStageEvent', callback: Callback&lt;WindowStageEventType&gt;): void;<br>WindowStageEventType.INACTIVE | The two methods have the same meaning and invoking time. In the stage model, this method is moved to the window object.| | onInactive(): void| on(eventType: 'windowStageEvent', callback: Callback&lt;WindowStageEventType&gt;): void;<br>WindowStageEventType.INACTIVE | The two methods have the same meaning and invoking time. In the stage model, this method is moved to the window object.|
| onHide(): void | onBackground(): void | The two methods have the same meaning, invoking time, and parameters.| | onHide(): void | onBackground(): void | The two methods have the same meaning, invoking time, and parameters.|
| NA | onWindowStageDestroy(): void | This method is available only in the stage model. The callback is invoked when a window is destroyed.| | NA | onWindowStageDestroy(): void | This method is available only in the stage model. The callback is invoked when a window is destroyed.|
| onDestroy(): void | onDestroy(): void | The two methods have the same meaning, invoking time, and parameters.| | onDestroy(): void | onDestroy(): void | The two methods have the same meaning, invoking time, and parameters.|
![pageability-switch](figures/pageability-switch.png) ![pageability-switch](figures/pageability-switch.png)
3. Adjust the migrated code, since the methods of loading pages are different. 3. Adjust the migrated code, since the methods of loading pages are different.
- In the FA model, you can configure the page to be loaded by setting page information in **config.json**. - In the FA model, you can configure the page to be loaded by setting page information in **config.json**.
- In the stage model, call **windowStage.loadContent** in the **onWindowStageCreate** callback to load a page. - In the stage model, call **windowStage.loadContent** in the **onWindowStageCreate** callback to load a page.
For example, to load the **pages/Index** page after the ability is started, use the following code in the **config.json** file in the FA model: For example, to load the **pages/Index** page after the ability is started, use the following code in the **config.json** file in the FA model:
```json ```json
"pages" : [ "pages" : [
"pages/Index" "pages/Index"
...@@ -39,8 +39,7 @@ The PageAbility lifecycle is basically the same as the UIAbility lifecycle. The ...@@ -39,8 +39,7 @@ The PageAbility lifecycle is basically the same as the UIAbility lifecycle. The
``` ```
In the stage model, implement the following method in **MainAbility**: In the stage model, implement the following method in **MainAbility**:
```ts ```ts
import Window from '@ohos.window' import Window from '@ohos.window'
...@@ -53,4 +52,4 @@ The PageAbility lifecycle is basically the same as the UIAbility lifecycle. The ...@@ -53,4 +52,4 @@ The PageAbility lifecycle is basically the same as the UIAbility lifecycle. The
} }
}); });
} }
``` ```
\ No newline at end of file
# Service Widget Overview # Service Widget Overview
A service widget (also called widget) is a set of UI components that display important information or operations specific to an application. It provides users with direct access to a desired application service, without the need to open the application first. A widget usually appears as a part of the UI of another application (which currently can only be a system application, such as the home screen) and provides basic interactive features such as opening a UI page or sending a message. A service widget (also called widget) is a set of UI components that display important information or operations specific to an application. It provides users with direct access to a desired application service, without the need to open the application first. A widget is usually displayed as part of the UI of another application (which can only be a system application, such as the home screen) and provides basic interactive features such as opening a UI page or sending a message.
## Service Widget Architecture ## Service Widget Architecture
...@@ -14,17 +14,17 @@ Before you get started, it would be helpful if you have a basic understanding of ...@@ -14,17 +14,17 @@ Before you get started, it would be helpful if you have a basic understanding of
- Widget host: an application that displays the widget content and controls the widget location. An example is the home screen in the preceding figure. - Widget host: an application that displays the widget content and controls the widget location. An example is the home screen in the preceding figure.
- Application icon: an application entry icon, clicking which starts the application process. The icon content does not support interactions. - Application icon: an icon for entry to an application, clicking which starts the application process. The icon content does not support interactions.
- Widget: an interactive UI in various sizes. It may provide buttons to implement different functions, such as the button to [update the widget content](arkts-ui-widget-event-formextensionability.md) or [switch to an application](arkts-ui-widget-event-router.md). - Widget: an interactive UI in various sizes. It may provide buttons to implement different features, such as the button to [update the widget content](arkts-ui-widget-event-formextensionability.md) or [switch to an application](arkts-ui-widget-event-router.md).
- Card provider: an application that provides service widget content to be displayed. It controls the display content, display logic, and component click events triggered on a service widget. - Widget provider: an application that provides widget content to be displayed. It controls the display content, display logic, and component click events triggered on a widget.
- FormExtensionAbility: widget service logic module, which provides lifecycle callbacks invoked when a widget is created, destroyed, or updated. - FormExtensionAbility: a widget service logic module, which provides lifecycle callbacks invoked when a widget is created, destroyed, or updated.
- Widget page: widget UI module, which contains display and interaction information such as components, layouts, and events. - Widget page: a widget UI module, which contains display and interaction information such as components, layouts, and events.
Below is the typical procedure of using the widget: Below is the typical procedure of using a widget:
**Figure 2** Typical procedure of using the widget **Figure 2** Typical procedure of using a widget
![WidgetUse](figures/WidgetUse.png) ![WidgetUse](figures/WidgetUse.png)
...@@ -35,7 +35,7 @@ Below is the typical procedure of using the widget: ...@@ -35,7 +35,7 @@ Below is the typical procedure of using the widget:
3. Touch the **Add to home** button. The widget is then added to the home screen. 3. Touch the **Add to home** button. The widget is then added to the home screen.
## Widget UI Development Mode ## Widget UI Development Modes
In the stage model, the UI of a widget can be developed in [ArkTS](arkts-ui-widget-working-principles.md) or [JS](js-ui-widget-development.md). In the stage model, the UI of a widget can be developed in [ArkTS](arkts-ui-widget-working-principles.md) or [JS](js-ui-widget-development.md).
...@@ -45,7 +45,7 @@ In the stage model, the UI of a widget can be developed in [ArkTS](arkts-ui-widg ...@@ -45,7 +45,7 @@ In the stage model, the UI of a widget can be developed in [ArkTS](arkts-ui-widg
ArkTS widgets and JS widgets have different implementation principles and features. The following table lists the differences in capabilities. ArkTS widgets and JS widgets have different implementation principles and features. The following table lists the differences in capabilities.
| Category| JS widget| ArkTS widget| | Category| JS Widget| ArkTS Widget|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| Development paradigm| Web-like paradigm| Declarative paradigm| | Development paradigm| Web-like paradigm| Declarative paradigm|
| Component capability| Supported| Supported| | Component capability| Supported| Supported|
......
...@@ -29,7 +29,7 @@ This scenario is possible when an application contains multiple UIAbility compon ...@@ -29,7 +29,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. To start FuncAbility from EntryAbility, proceed as follows: Assume that your application has two UIAbility components: EntryAbility and FuncAbility, either in the same module or different modules. To start FuncAbility from EntryAbility, proceed as follows:
1. In EntryAbility, call [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) and pass the [want](../reference/apis/js-apis-app-ability-want.md) parameter to start 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 from EntryAbility; **parameters** is used to carry custom information. For details about how to obtain the context in the example, 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) and pass the [want](../reference/apis/js-apis-app-ability-want.md) parameter to start 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 from EntryAbility; **parameters** is used to carry custom information. For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
```ts ```ts
let context = ...; // UIAbilityContext let context = ...; // UIAbilityContext
let want = { let want = {
...@@ -48,12 +48,12 @@ Assume that your application has two UIAbility components: EntryAbility and Func ...@@ -48,12 +48,12 @@ Assume that your application has two UIAbility components: EntryAbility and Func
console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`);
}) })
``` ```
2. In FuncAbility, use [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) to receive the parameters passed in by EntryAbility. 2. In FuncAbility, use [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) to receive the parameters passed in by EntryAbility.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
export default class FuncAbility extends UIAbility { export default class FuncAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
// Receive the parameters passed by the initiator UIAbility. // Receive the parameters passed by the initiator UIAbility.
...@@ -63,16 +63,16 @@ Assume that your application has two UIAbility components: EntryAbility and Func ...@@ -63,16 +63,16 @@ Assume that your application has two UIAbility components: EntryAbility and Func
} }
} }
``` ```
> **NOTE** > **NOTE**
> >
> In FuncAbility started, you can obtain the PID and bundle name of the UIAbility through **parameters** in the passed **want** parameter. > In FuncAbility started, you can obtain the PID and bundle name of the UIAbility through **parameters** in the passed **want** parameter.
3. To stop the **UIAbility** instance after the FuncAbility service is not needed, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) in FuncAbility. 3. To stop the **UIAbility** instance after the FuncAbility service is not needed, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) in FuncAbility.
```ts ```ts
let context = ...; // UIAbilityContext let context = ...; // UIAbilityContext
// context is the UIAbilityContext of the UIAbility instance to stop. // context is the UIAbilityContext of the UIAbility instance to stop.
context.terminateSelf((err) => { context.terminateSelf((err) => {
if (err.code) { if (err.code) {
...@@ -81,11 +81,11 @@ Assume that your application has two UIAbility components: EntryAbility and Func ...@@ -81,11 +81,11 @@ Assume that your application has two UIAbility components: EntryAbility and Func
} }
}); });
``` ```
> **NOTE** > **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. > 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). 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).
...@@ -94,7 +94,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func ...@@ -94,7 +94,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func
When starting FuncAbility from EntryAbility, you may want the result to be returned after the FuncAbility service is finished. For example, after the sign-in operation is finished in the sign-in UIAbility of your application, you want the sign-in result to be returned to the entry UIAbility. When starting FuncAbility from EntryAbility, you may want the result to be returned after the FuncAbility service is finished. For example, after the sign-in operation is finished in the sign-in UIAbility of your application, you want the sign-in result to be returned to the entry 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 in the example, 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 in the example, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
```ts ```ts
let context = ...; // UIAbilityContext let context = ...; // UIAbilityContext
let want = { let want = {
...@@ -113,9 +113,9 @@ When starting FuncAbility from EntryAbility, you may want the result to be retur ...@@ -113,9 +113,9 @@ When starting FuncAbility from EntryAbility, you may want the result to be retur
console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`);
}) })
``` ```
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. 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
let context = ...; // UIAbilityContext let context = ...; // UIAbilityContext
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
...@@ -138,15 +138,15 @@ When starting FuncAbility from EntryAbility, you may want the result to be retur ...@@ -138,15 +138,15 @@ When starting FuncAbility from EntryAbility, you may want the result to be retur
} }
}); });
``` ```
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 that specified in the preceding step. 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 that specified in the preceding step.
```ts ```ts
let context = ...; // UIAbilityContext let context = ...; // UIAbilityContext
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
... ...
// context is the UIAbilityContext of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
context.startAbilityForResult(want).then((data) => { context.startAbilityForResult(want).then((data) => {
if (data?.resultCode === RESULT_CODE) { if (data?.resultCode === RESULT_CODE) {
...@@ -173,7 +173,7 @@ There are two ways to start **UIAbility**: [explicit and implicit](want-overview ...@@ -173,7 +173,7 @@ There are two ways to start **UIAbility**: [explicit and implicit](want-overview
The following example describes how to start the UIAbility of another application through implicit Want. The following example 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](../quick-start/module-configuration-file.md) of each UIAbility component, configure **entities** and **actions** 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
{ {
"module": { "module": {
...@@ -199,7 +199,7 @@ The following example describes how to start the UIAbility of another applicatio ...@@ -199,7 +199,7 @@ The following example describes how to start the UIAbility of another applicatio
``` ```
2. Include **entities** and **actions** of the initiator UIAbility's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. After the system identifies the UIAbility instances that match the **entities** and **actions** information, a dialog box is displayed, showing the list of matching UIAbility instances for users to select. For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). 2. Include **entities** and **actions** of the initiator UIAbility's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. After the system identifies the UIAbility instances that match the **entities** and **actions** information, a dialog box is displayed, showing the list of matching UIAbility instances for users to select. For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
```ts ```ts
let context = ...; // UIAbilityContext let context = ...; // UIAbilityContext
let want = { let want = {
...@@ -210,7 +210,7 @@ The following example describes how to start the UIAbility of another applicatio ...@@ -210,7 +210,7 @@ The following example describes how to start the UIAbility of another applicatio
// entities can be omitted. // entities can be omitted.
entities: ['entity.system.default'], entities: ['entity.system.default'],
} }
// context is the UIAbilityContext of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
context.startAbility(want).then(() => { context.startAbility(want).then(() => {
console.info('Succeeded in starting ability.'); console.info('Succeeded in starting ability.');
...@@ -218,16 +218,16 @@ The following example describes how to start the UIAbility of another applicatio ...@@ -218,16 +218,16 @@ The following example describes how to start the UIAbility of another applicatio
console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`);
}) })
``` ```
The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select the application to use. The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select the application to use.
![](figures/uiability-intra-device-interaction.png) ![](figures/uiability-intra-device-interaction.png)
3. To stop the **UIAbility** instance when the document application is not in use, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself). 3. To stop the **UIAbility** instance when the document application is not in use, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself).
```ts ```ts
let context = ...; // UIAbilityContext let context = ...; // UIAbilityContext
// context is the UIAbilityContext of the UIAbility instance to stop. // context is the UIAbilityContext of the UIAbility instance to stop.
context.terminateSelf((err) => { context.terminateSelf((err) => {
if (err.code) { if (err.code) {
...@@ -243,7 +243,7 @@ The following example describes how to start the UIAbility of another applicatio ...@@ -243,7 +243,7 @@ The following example describes how to start the UIAbility of another applicatio
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 your 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 your application needs to start a third-party payment application and obtain the payment result.
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**. 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
{ {
"module": { "module": {
...@@ -269,7 +269,7 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -269,7 +269,7 @@ If you want to obtain the return result when using implicit Want to start the UI
``` ```
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 initiator UIAbility'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 initiator UIAbility after the payment UIAbility stops itself. After the system identifies the UIAbility instances that match the **entities** and **actions** information, a dialog box is displayed, showing the list of matching 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 initiator UIAbility'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 initiator UIAbility after the payment UIAbility stops itself. After the system identifies the UIAbility instances that match the **entities** and **actions** information, a dialog box is displayed, showing the list of matching UIAbility instances for users to select.
```ts ```ts
let context = ...; // UIAbilityContext let context = ...; // UIAbilityContext
let want = { let want = {
...@@ -280,7 +280,7 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -280,7 +280,7 @@ If you want to obtain the return result when using implicit Want to start the UI
// entities can be omitted. // entities can be omitted.
entities: ['entity.system.default'] entities: ['entity.system.default']
} }
// context is the UIAbilityContext of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
context.startAbilityForResult(want).then((data) => { context.startAbilityForResult(want).then((data) => {
... ...
...@@ -288,9 +288,9 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -288,9 +288,9 @@ If you want to obtain the return result when using implicit Want to start the UI
console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`);
}) })
``` ```
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. 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
let context = ...; // UIAbilityContext let context = ...; // UIAbilityContext
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
...@@ -313,17 +313,17 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -313,17 +313,17 @@ If you want to obtain the return result when using implicit Want to start the UI
} }
}); });
``` ```
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). 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
let context = ...; // UIAbilityContext let context = ...; // UIAbilityContext
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
let want = { let want = {
// Want parameter information. // Want parameter information.
}; };
// context is the UIAbilityContext of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
context.startAbilityForResult(want).then((data) => { context.startAbilityForResult(want).then((data) => {
if (data?.resultCode === RESULT_CODE) { if (data?.resultCode === RESULT_CODE) {
...@@ -350,8 +350,8 @@ The window mode is specified by the **windowMode** field in the [StartOptions](. ...@@ -350,8 +350,8 @@ The window mode is specified by the **windowMode** field in the [StartOptions](.
> **NOTE** > **NOTE**
> >
> 1. If the **windowMode** field is not specified, the UIAbility is started in the default window mode. > - If the **windowMode** field is not specified, the UIAbility is started in the default window mode.
> 2. To ensure that the application can be displayed in the required window mode, check the **supportWindowMode** field under [abilities](../quick-start/module-configuration-file.md#abilities) in the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility and make sure the specified window mode is supported. > - To ensure that the application can be displayed in the required window mode, check the **supportWindowMode** field under [abilities](../quick-start/module-configuration-file.md#abilities) in the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility and make sure the specified window mode is supported.
The following describes how to start the FuncAbility from the EntryAbility page and display it in floating window mode. The following describes how to start the FuncAbility from the EntryAbility page and display it in floating window mode.
...@@ -472,7 +472,7 @@ U->>S: Open the SMS app. ...@@ -472,7 +472,7 @@ U->>S: Open the SMS app.
S-->>U: The home page of the SMS app is displayed. S-->>U: The home page of the SMS app is displayed.
U->>S: Return to the home screen. U->>S: Return to the home screen.
S->>S: The SMS app enters the background. S->>S: The SMS app enters the background.
U->>C: Open the Contacts app. U->>C: Open the Contacts app.
C-->>U: The page of the Contact app is displayed. C-->>U: The page of the Contact app is displayed.
U->>C: Touch the SMS button next to a contact. U->>C: Touch the SMS button next to a contact.
C->>S: Start the SMS app with Want. C->>S: Start the SMS app with Want.
...@@ -488,19 +488,19 @@ The development procedure is as follows: ...@@ -488,19 +488,19 @@ The development procedure is as follows:
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import Want from '@ohos.app.ability.Want'; import Want from '@ohos.app.ability.Want';
import window from '@ohos.window'; import window from '@ohos.window';
import { Router, UIContext } from '@ohos.arkui.UIContext'; import { Router, UIContext } from '@ohos.arkui.UIContext';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
funcAbilityWant: Want; funcAbilityWant: Want;
uiContext: UIContext; uiContext: UIContext;
... ...
onWindowStageCreate(windowStage: window.WindowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
// Main window is created. Set a main page for this UIAbility. // Main window is created. Set a main page for this UIAbility.
... ...
let windowClass: window.Window; let windowClass: window.Window;
windowStage.getMainWindow((err, data) => { windowStage.getMainWindow((err, data) => {
if (err.code) { if (err.code) {
...@@ -520,8 +520,8 @@ The development procedure is as follows: ...@@ -520,8 +520,8 @@ The development procedure is as follows:
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
funcAbilityWant: Want; funcAbilityWant: Want;
uiContext: UIContext; uiContext: UIContext;
onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam) { onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) {
if (want?.parameters?.router && want.parameters.router === 'funcA') { if (want?.parameters?.router && want.parameters.router === 'funcA') {
let funcAUrl = 'pages/Second'; let funcAUrl = 'pages/Second';
let router: Router = this.uiContext.getRouter(); let router: Router = this.uiContext.getRouter();
...@@ -532,7 +532,7 @@ The development procedure is as follows: ...@@ -532,7 +532,7 @@ The development procedure is as follows:
}) })
} }
} }
... ...
} }
``` ```
...@@ -580,9 +580,9 @@ The following figure shows the call process. ...@@ -580,9 +580,9 @@ The following figure shows the call process.
> **NOTE** > **NOTE**
> - Currently, only system applications can use the call. > - Currently, only system applications can use the call.
> >
> - The launch type of the CalleeAbility must be **singleton**. > - The launch type of the CalleeAbility must be **singleton**.
> >
> - Both local (intra-device) and cross-device calls are supported. The following describes how to initiate a local call. For details about how to initiate a cross-device call, see [Using Cross-Device Call](hop-multi-device-collaboration.md#using-cross-device-call). > - Both local (intra-device) and cross-device calls are supported. The following describes how to initiate a local call. For details about how to initiate a cross-device call, see [Using Cross-Device Call](hop-multi-device-collaboration.md#using-cross-device-call).
...@@ -614,24 +614,24 @@ The implementation of using the call for UIAbility interaction involves two part ...@@ -614,24 +614,24 @@ The implementation of using the call for UIAbility interaction involves two part
For the CalleeAbility, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener. For the CalleeAbility, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener.
1. Configure the launch type of the CalleeAbility. 1. Configure the launch type of the CalleeAbility.
For example, set the launch type of the CalleeAbility to **singleton**. For details, see [UIAbility Component Launch Type](uiability-launch-type.md). For example, set the launch type of the CalleeAbility to **singleton**. For details, see [UIAbility Component Launch Type](uiability-launch-type.md).
2. Import the **UIAbility** module. 2. Import the **UIAbility** module.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
``` ```
3. Define the agreed parcelable data. 3. Define the agreed parcelable data.
The data formats sent and received by the CallerAbility and CalleeAbility must be consistent. In the following example, the data formats are number and string.
The data formats sent and received by the CallerAbility and CalleeAbility must be consistent. In the following example, the data formats are number and string.
```ts ```ts
export default class MyParcelable { export default class MyParcelable {
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;
...@@ -650,9 +650,9 @@ For the CalleeAbility, implement the callback to receive data and the methods to ...@@ -650,9 +650,9 @@ For the CalleeAbility, implement the callback to receive data and the methods to
} }
} }
``` ```
4. Implement **Callee.on** and **Callee.off**.
4. Implement **Callee.on** and **Callee.off**.
The time to register a listener for the CalleeAbility 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 UIAbility and deregistered in **onDestroy**. After receiving parcelable 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 CalleeAbility 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 UIAbility and deregistered in **onDestroy**. After receiving parcelable 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:
...@@ -696,7 +696,7 @@ For the CalleeAbility, implement the callback to receive data and the methods to ...@@ -696,7 +696,7 @@ For the CalleeAbility, implement the callback to receive data and the methods to
### Accessing the CalleeAbility ### Accessing the CalleeAbility
1. Import the **UIAbility** module. 1. Import the **UIAbility** module.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
``` ```
...@@ -735,4 +735,4 @@ For the CalleeAbility, implement the callback to receive data and the methods to ...@@ -735,4 +735,4 @@ For the CalleeAbility, implement the callback to receive data and the methods to
console.err(`Failed to get caller. Code is ${err.code}, message is ${err.message}`); console.err(`Failed to get caller. Code is ${err.code}, message is ${err.message}`);
} }
} }
``` ```
\ No newline at end of file
...@@ -30,23 +30,23 @@ The preference persistent file of an application is stored in the application sa ...@@ -30,23 +30,23 @@ The preference persistent file of an application is stored in the application sa
The following table lists the APIs used for persisting user preference data. For more information about the APIs, see [User Preferences](../reference/apis/js-apis-data-preferences.md). The following table lists the APIs used for persisting user preference data. For more information about the APIs, see [User Preferences](../reference/apis/js-apis-data-preferences.md).
| API | Description | | API | Description |
|--------------------------------------------------------------------------------------------------|------------------------------------------------------------| | ------------------------------------------------------------ | ------------------------------------------------------------ |
| getPreferences(context: Context, name: string, callback: AsyncCallback&lt;Preferences&gt;): void | Obtain a **Preferences** instance. | | getPreferences(context: Context, name: string, callback: AsyncCallback&lt;Preferences&gt;): void | Obtains a **Preferences** instance. |
| putSync(key: string, value: ValueType): void | Writes data to the Preferences instance. You can use **flush()** to persist the **Preferences** instance data. An asynchronous API is also provided. | | putSync(key: string, value: ValueType): void | Writes data to the Preferences instance. You can use **flush()** to persist the **Preferences** instance data. An asynchronous API is also provided. |
| hasSync(key: string): void | Checks whether the **Preferences** instance contains a KV pair with the given key. The key cannot be empty. An asynchronous API is also provided. | | hasSync(key: string): void | Checks whether the **Preferences** instance contains a KV pair with the given key. The key cannot be empty. An asynchronous API is also provided. |
| getSync(key: string, defValue: ValueType): void | Obtains the value of the specified key. If the value is null or not of the default value type, **defValue** is returned. An asynchronous API is also provided. | | getSync(key: string, defValue: ValueType): void | Obtains the value of the specified key. If the value is null or not of the default value type, **defValue** is returned. An asynchronous API is also provided. |
| deleteSync(key: string): void | Deletes the KV pair with the given key from the **Preferences** instance. An asynchronous API is also provided. | | deleteSync(key: string): void | Deletes the KV pair with the given key from the **Preferences** instance. An asynchronous API is also provided. |
| flush(callback: AsyncCallback&lt;void&gt;): void | Flushes the data of this **Preferences** instance to a file for data persistence. | | flush(callback: AsyncCallback&lt;void&gt;): void | Flushes the data of this **Preferences** instance to a file for data persistence. |
| on(type: 'change', callback: Callback&lt;{ key : string }&gt;): void | Subscribes to data changes of the specified key. When the value of the specified key is changed and saved by **flush()**, a callback will be invoked to return the new data. | | on(type: 'change', callback: Callback&lt;{ key : string }&gt;): void | Subscribes to data changes of the specified key. When the value of the specified key is changed and saved by **flush()**, a callback will be invoked to return the new data. |
| off(type: 'change', callback?: Callback&lt;{ key : string }&gt;): void | Unsubscribes from data changes. | | off(type: 'change', callback?: Callback&lt;{ key : string }&gt;): void | Unsubscribes from data changes. |
| deletePreferences(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void | Deletes a **Preferences** instance from memory. If the **Preferences** instance has a persistent file, this API also deletes the persistent file.| | deletePreferences(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void | Deletes a **Preferences** instance from memory. If the **Preferences** instance has a persistent file, this API also deletes the persistent file. |
## How to Develop ## How to Develop
1. Import the **@ohos.data.preferences** module. 1. Import the **@ohos.data.preferences** module.
```js ```js
import dataPreferences from '@ohos.data.preferences'; import dataPreferences from '@ohos.data.preferences';
``` ```
...@@ -55,14 +55,16 @@ The following table lists the APIs used for persisting user preference data. For ...@@ -55,14 +55,16 @@ The following table lists the APIs used for persisting user preference data. For
Stage model: Stage model:
```js ```js
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base';
import window from '@ohos.window';
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
try { try {
dataPreferences.getPreferences(this.context, 'mystore', (err, preferences) => { dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: dataPreferences.Preferences) => {
if (err) { if (err) {
console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`); console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
return; return;
...@@ -79,15 +81,16 @@ The following table lists the APIs used for persisting user preference data. For ...@@ -79,15 +81,16 @@ The following table lists the APIs used for persisting user preference data. For
FA model: FA model:
```js ```js
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base';
// Obtain the context. // Obtain the context.
let context = featureAbility.getContext(); let context = featureAbility.getContext();
try { try {
dataPreferences.getPreferences(context, 'mystore', (err, preferences) => { dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: dataPreferences.Preferences) => {
if (err) { if (err) {
console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`); console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
return; return;
...@@ -102,7 +105,7 @@ The following table lists the APIs used for persisting user preference data. For ...@@ -102,7 +105,7 @@ The following table lists the APIs used for persisting user preference data. For
3. Write data. 3. Write data.
Use **putSync()** to write data to the cached **Preferences** instance. After data is written, you can use **flush()** to persist the **Preferences** instance data to a file if necessary. Use **putSync()** to save data to the cached **Preferences** instance. After data is written, you can use **flush()** to persist the **Preferences** instance data to a file if necessary.
> **NOTE** > **NOTE**
> >
...@@ -110,7 +113,7 @@ The following table lists the APIs used for persisting user preference data. For ...@@ -110,7 +113,7 @@ The following table lists the APIs used for persisting user preference data. For
Example: Example:
```js ```js
try { try {
if (preferences.hasSync('startup')) { if (preferences.hasSync('startup')) {
...@@ -142,7 +145,7 @@ The following table lists the APIs used for persisting user preference data. For ...@@ -142,7 +145,7 @@ The following table lists the APIs used for persisting user preference data. For
Use **deleteSync()** to delete a KV pair.<br>Example: Use **deleteSync()** to delete a KV pair.<br>Example:
```js ```js
try { try {
preferences.deleteSync('startup'); preferences.deleteSync('startup');
...@@ -157,7 +160,7 @@ The following table lists the APIs used for persisting user preference data. For ...@@ -157,7 +160,7 @@ The following table lists the APIs used for persisting user preference data. For
```js ```js
try { try {
preferences.flush((err) => { preferences.flush((err: BusinessError) => {
if (err) { if (err) {
console.error(`Failed to flush. Code:${err.code}, message:${err.message}`); console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
return; return;
...@@ -174,18 +177,20 @@ The following table lists the APIs used for persisting user preference data. For ...@@ -174,18 +177,20 @@ The following table lists the APIs used for persisting user preference data. For
Specify an observer as the callback to return the data changes for an application. When the value of the subscribed key is changed and saved by **flush()**, the observer callback will be invoked to return the new data. Example: Specify an observer as the callback to return the data changes for an application. When the value of the subscribed key is changed and saved by **flush()**, the observer callback will be invoked to return the new data. Example:
```js ```js
let observer = function (key) { interface observer {
console.info('The key' + key + 'changed.'); key: string
} }
preferences.on('change', observer); preferences.on('change', (key: observer) => {
console.info('The key' + key + 'changed.');
});
// The data is changed from 'auto' to 'manual'. // The data is changed from 'auto' to 'manual'.
preferences.put('startup', 'manual', (err) => { preferences.put('startup', 'manual', (err: BusinessError) => {
if (err) { if (err) {
console.error(`Failed to put the value of 'startup'. Code:${err.code},message:${err.message}`); console.error(`Failed to put the value of 'startup'. Code:${err.code},message:${err.message}`);
return; return;
} }
console.info("Succeeded in putting the value of 'startup'."); console.info("Succeeded in putting the value of 'startup'.");
preferences.flush((err) => { preferences.flush((err: BusinessError) => {
if (err) { if (err) {
console.error(`Failed to flush. Code:${err.code}, message:${err.message}`); console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
return; return;
...@@ -207,10 +212,10 @@ The following table lists the APIs used for persisting user preference data. For ...@@ -207,10 +212,10 @@ The following table lists the APIs used for persisting user preference data. For
Example: Example:
```js ```js
try { try {
dataPreferences.deletePreferences(this.context, 'mystore', (err, val) => { dataPreferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => {
if (err) { if (err) {
console.error(`Failed to delete preferences. Code:${err.code}, message:${err.message}`); console.error(`Failed to delete preferences. Code:${err.code}, message:${err.message}`);
return; return;
......
...@@ -32,7 +32,7 @@ The underlying devices manage the data by device. The device KV stores support d ...@@ -32,7 +32,7 @@ The underlying devices manage the data by device. The device KV stores support d
The **DatamgrService** provides the following synchronization types: The **DatamgrService** provides the following synchronization types:
- Manual synchronization: The application calls **sync()** to trigger a synchronization. The list of devices to be synchronized and the synchronization mode must be specified. The synchronization mode can be **PULL_ONLY** (pulling remote data to the local end), **PUSH_ONLY** (pushing local data to the remote end), or **PUSH_PULL** (pushing local data to the remote end and pulling remote data to the local end). You can use the [**sync()** with the **query** parameter](../reference/apis/js-apis-distributedKVStore.md#sync-1) to synchronize the data that meets the specified conditions. The manual synchronization is available only for system applications. - Manual synchronization: The application calls **sync()** to trigger a synchronization. The list of devices to be synchronized and the synchronization mode must be specified. The synchronization mode can be **PULL_ONLY** (pulling remote data to the local end), **PUSH_ONLY** (pushing local data to the remote end), or **PUSH_PULL** (pushing local data to the remote end and pulling remote data to the local end). You can use the [**sync()** with the **query** parameter](../reference/apis/js-apis-distributedKVStore.md#sync-1) to synchronize the data that meets the specified conditions.
- Automatic synchronization: The distributed database automatically pushes local data to the remote end and pulls remote data to the local end. An automatic synchronization is triggered when a device goes online or an application updates data. - Automatic synchronization: The distributed database automatically pushes local data to the remote end and pulls remote data to the local end. An automatic synchronization is triggered when a device goes online or an application updates data.
...@@ -72,8 +72,6 @@ When data is added, deleted, or modified, a notification is sent to the subscrib ...@@ -72,8 +72,6 @@ When data is added, deleted, or modified, a notification is sent to the subscrib
- Each KV store supports a maximum of eight callbacks for subscription of data change notifications. - Each KV store supports a maximum of eight callbacks for subscription of data change notifications.
- The manual synchronization is available only for system applications.
## Available APIs ## Available APIs
...@@ -247,32 +245,31 @@ The following uses a single KV store as an example to describe how to implement ...@@ -247,32 +245,31 @@ The following uses a single KV store as an example to describe how to implement
> **NOTE** > **NOTE**
> >
> If manual synchronization is used, **deviceIds** is obtained by using [devManager.getTrustedDeviceListSync](../reference/apis/js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are all system interfaces and available only to system applications. > If manual synchronization is used, **deviceIds** can be obtained by [devManager.getAvailableDeviceListSync](../reference/apis/js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
```js ```js
import deviceManager from '@ohos.distributedHardware.deviceManager'; import deviceManager from '@ohos.distributedDeviceManager';
let devManager; let devManager;
// create deviceManager try {
deviceManager.createDeviceManager('bundleName', (err, value) => { // create deviceManager
if (!err) { devManager = deviceManager.createDeviceManager(context.applicationInfo.name);
devManager = value; // deviceIds is obtained by devManager.getAvailableDeviceListSync.
// deviceIds is obtained by devManager.getTrustedDeviceListSync. let deviceIds = [];
let deviceIds = []; if (devManager != null) {
if (devManager !== null) { let devices = devManager.getAvailableDeviceListSync();
// The ohos.permission.ACCESS_SERVICE_DM permission is required. This permission is available only for system applications. for (let i = 0; i < devices.length; i++) {
let devices = devManager.getTrustedDeviceListSync(); deviceIds[i] = devices[i].networkId;
for (let i = 0; i < devices.length; i++) {
deviceIds[i] = devices[i].deviceId;
}
}
try {
// 1000 indicates the maximum delay, in ms.
kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000);
} catch (e) {
console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
} }
} }
}); try {
// 1000 indicates the maximum delay, in ms.
kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000);
} catch (e) {
console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
}
} catch (err) {
console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
\ No newline at end of file
...@@ -10,9 +10,16 @@ You can synchronize the application data in a local RDB store on a device to oth ...@@ -10,9 +10,16 @@ You can synchronize the application data in a local RDB store on a device to oth
OpenHamony supports synchronization of the relational data of an application across multiple devices. OpenHamony supports synchronization of the relational data of an application across multiple devices.
- Distributed table list<br>After a table is created for an application in an RDB store, you can set it as a distributed table. When querying the RDB store of a remote device, you can obtain the distributed table name of the remote device based on the local table name. - Distributed table list
- Synchronization mode<br>Data can be synchronized between devices in either of the following ways: <br>- Pushing data from a local device to a remote device. <br>- Pulling data from a remote device to a local device. After a table is created for an application in an RDB store, you can set it as a distributed table. When querying the RDB store of a remote device, you can obtain the distributed table name of the remote device based on the local table name.
- Synchronization mode
Data can be synchronized between devices in either of the following ways:
- Pushing data from a local device to a remote device.
- Pulling data from a remote device to a local device.
## Working Principles ## Working Principles
...@@ -44,12 +51,10 @@ When data is added, deleted, or modified, a notification is sent to the subscrib ...@@ -44,12 +51,10 @@ When data is added, deleted, or modified, a notification is sent to the subscrib
- Each RDB store supports a maximum of eight callbacks for subscription of data change notifications. - Each RDB store supports a maximum of eight callbacks for subscription of data change notifications.
- Third-party applications cannot call the distributed APIs that must be specified with the device.
## Available APIs ## Available APIs
The following table lists the APIs for cross-device data synchronization of RDB stores. Most of the APIs are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [RDB Store](../reference/apis/js-apis-data-relationalStore.md). Most of the APIs for cross-device data synchronization of RDB stores are executed asynchronously in callback or promise mode. The following table uses the callback-based APIs as an example. For more information about the APIs, see [RDB Store](../reference/apis/js-apis-data-relationalStore.md).
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
...@@ -73,7 +78,7 @@ The following table lists the APIs for cross-device data synchronization of RDB ...@@ -73,7 +78,7 @@ The following table lists the APIs for cross-device data synchronization of RDB
import relationalStore from '@ohos.data.relationalStore'; import relationalStore from '@ohos.data.relationalStore';
``` ```
2. Request permissions. 2. Apply for the required permission.
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization). 2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization).
...@@ -142,32 +147,33 @@ The following table lists the APIs for cross-device data synchronization of RDB ...@@ -142,32 +147,33 @@ The following table lists the APIs for cross-device data synchronization of RDB
> **NOTE** > **NOTE**
> >
> **deviceIds** is obtained by using [devManager.getTrustedDeviceListSync](../reference/apis/js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are all system interfaces and available only to system applications. > The value of **deviceIds** can be obtained by [deviceManager.getAvailableDeviceListSync](../reference/apis/js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
```js ```js
// Obtain device IDs. // Obtain device IDs.
import deviceManager from '@ohos.distributedHardware.deviceManager'; import deviceManager from '@ohos.distributedDeviceManager';
let dmInstance = null;
deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { let deviceId = null;
if (err) {
console.info(`Failed to create device manager. Code:${err.code},message:${err.message}`); try {
return; dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify");
} let devices = dmInstance.getAvailableDeviceListSync();
let devices = manager.getTrustedDeviceListSync(); deviceId = devices[0].networkId;
let deviceId = devices[0].deviceId;
// Construct a predicate object for querying the distributed table.
// Construct a predicate object for querying the distributed table. let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); // Query data from the specified remote device and return the query result.
// Query data from the specified remote device and return the query result. store.remoteQuery(deviceId, 'EMPLOYEE', predicates, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES'],
store.remoteQuery(deviceId, 'EMPLOYEE', predicates, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES'], function (err, resultSet) {
function (err, resultSet) { if (err) {
if (err) { console.error(`Failed to remoteQuery data. Code:${err.code},message:${err.message}`);
console.error(`Failed to remoteQuery data. Code:${err.code},message:${err.message}`); return;
return;
}
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
} }
) console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
}) }
``` )
} catch (err) {
console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
}
```
\ No newline at end of file
...@@ -57,15 +57,16 @@ Before implementing a **DataShare** service, you need to create a **DataShareExt ...@@ -57,15 +57,16 @@ Before implementing a **DataShare** service, you need to create a **DataShareExt
2. Right-click the **DataShareAbility** directory, and choose **New > TypeScript File** to create a file named **DataShareExtAbility.ts**. 2. Right-click the **DataShareAbility** directory, and choose **New > TypeScript File** to create a file named **DataShareExtAbility.ts**.
3. Import **@ohos.application.DataShareExtensionAbility** and other dependencies to the **DataShareExtAbility.ts** file, and 3. Import **@ohos.application.DataShareExtensionAbility** and other dependencies to the **DataShareExtAbility.ts** file, and override the service implementation as required. For example, if the data provider provides only the data insertion, deletion, and query services, you can override only these APIs.
override the service implementation as required. For example, if the data provider provides only the data insertion, deletion, and query services, you can override only these APIs.
```js ```js
import Extension from '@ohos.application.DataShareExtensionAbility'; import Extension from '@ohos.application.DataShareExtensionAbility';
import rdb from '@ohos.data.relationalStore'; import rdb from '@ohos.data.relationalStore';
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
import relationalStore from '@ohos.data.relationalStore';
import Want from '@ohos.app.ability.Want';
``` ```
4. 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. 4. 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.
```js ```js
...@@ -75,20 +76,20 @@ override the service implementation as required. For example, if the data provid ...@@ -75,20 +76,20 @@ override the service implementation as required. For example, if the data provid
+ 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: relationalStore.RdbStore;
let result; let result: string;
export default class DataShareExtAbility extends Extension { export default class DataShareExtAbility extends Extension {
private rdbStore_; private rdbStore_: relationalStore.RdbStore;
// Override onCreate(). // Override onCreate().
onCreate(want, callback) { onCreate(want: Want, callback: Function) {
result = this.context.cacheDir + '/datashare.txt'; result = this.context.cacheDir + '/datashare.txt';
// Create an RDB store. // Create an RDB store.
rdb.getRdbStore(this.context, { rdb.getRdbStore(this.context, {
name: DB_NAME, name: DB_NAME,
securityLevel: rdb.SecurityLevel.S1 securityLevel: rdb.SecurityLevel.S1
}, function (err, data) { }, (err, data) => {
rdbStore = data; rdbStore = data;
rdbStore.executeSql(DDL_TBL_CREATE, [], (err) => { rdbStore.executeSql(DDL_TBL_CREATE, [], (err) => {
console.info(`DataShareExtAbility onCreate, executeSql done err:${err}`); console.info(`DataShareExtAbility onCreate, executeSql done err:${err}`);
...@@ -100,7 +101,7 @@ override the service implementation as required. For example, if the data provid ...@@ -100,7 +101,7 @@ override the service implementation as required. For example, if the data provid
} }
// Override query(). // Override query().
query(uri, predicates, columns, callback) { query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: Function) {
if (predicates === null || predicates === undefined) { if (predicates === null || predicates === undefined) {
console.info('invalid predicates'); console.info('invalid predicates');
} }
...@@ -188,6 +189,8 @@ override the service implementation as required. For example, if the data provid ...@@ -188,6 +189,8 @@ override the service implementation as required. For example, if the data provid
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import dataShare from '@ohos.data.dataShare'; import dataShare from '@ohos.data.dataShare';
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { ValuesBucket } from '@ohos.data.ValuesBucket'
import window from '@ohos.window';
``` ```
2. Define the URI string for communicating with the data provider. 2. Define the URI string for communicating with the data provider.
...@@ -200,11 +203,11 @@ override the service implementation as required. For example, if the data provid ...@@ -200,11 +203,11 @@ override the service implementation as required. For example, if the data provid
3. Create a **DataShareHelper** instance. 3. Create a **DataShareHelper** instance.
```js ```js
let dsHelper; let dsHelper: dataShare.DataShareHelper;
let abilityContext; let abilityContext: Context;
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
abilityContext = this.context; abilityContext = this.context;
dataShare.createDataShareHelper(abilityContext, dseUri, (err, data) => { dataShare.createDataShareHelper(abilityContext, dseUri, (err, data) => {
dsHelper = data; dsHelper = data;
...@@ -217,8 +220,19 @@ override the service implementation as required. For example, if the data provid ...@@ -217,8 +220,19 @@ override the service implementation as required. For example, if the data provid
```js ```js
// Construct a piece of data. // Construct a piece of data.
let valuesBucket = { 'name': 'ZhangSan', 'age': 21, 'isStudent': false, 'Binary': new Uint8Array([1, 2, 3]) }; let key1 = 'name';
let updateBucket = { 'name': 'LiSi', 'age': 18, 'isStudent': true, 'Binary': new Uint8Array([1, 2, 3]) }; let key2 = 'age';
let key3 = 'isStudent';
let key4 = 'Binary';
let valueName1 = 'ZhangSan';
let valueName2 = 'LiSi';
let valueAge1 = 21;
let valueAge2 = 18;
let valueIsStudent1 = false;
let valueIsStudent2 = true;
let valueBinary = new Uint8Array([1, 2, 3]);
let valuesBucket: ValuesBucket = { key1: valueName1, key2: valueAge1, key3: valueIsStudent1, key4: valueBinary };
let updateBucket: ValuesBucket = { key1: valueName2, key2: valueAge2, key3: valueIsStudent2, key4: valueBinary };
let predicates = new dataSharePredicates.DataSharePredicates(); let predicates = new dataSharePredicates.DataSharePredicates();
let valArray = ['*']; let valArray = ['*'];
// Insert a piece of data. // Insert a piece of data.
...@@ -237,5 +251,4 @@ override the service implementation as required. For example, if the data provid ...@@ -237,5 +251,4 @@ override the service implementation as required. For example, if the data provid
dsHelper.delete(dseUri, predicates, (err, data) => { dsHelper.delete(dseUri, predicates, (err, data) => {
console.info(`dsHelper delete result:${data}`); console.info(`dsHelper delete result:${data}`);
}); });
``` ```
\ No newline at end of file
...@@ -29,7 +29,7 @@ Currently, the UDMF provides the public data channel for cross-application data ...@@ -29,7 +29,7 @@ Currently, the UDMF provides the public data channel for cross-application data
## Available APIs ## Available APIs
The following table lists the UDMF APIs. All of them are executed asynchronously in callback or promise mode. In the following table, callback-based APIs are used as an example. For more information about the APIs, see [UDMF](../reference/apis/js-apis-data-udmf.md). The following table lists the UDMF APIs. All of them are executed asynchronously in callback or promise mode. In the following table, callback-based APIs are used as an example. For more information about the APIs, see [Unified Data Channel](../reference/apis/js-apis-data-unifiedDataChannel.md) and [Standard Data Definition and Description](../reference/apis/js-apis-data-uniformTypeDescriptor.md).
| API | Description | | API | Description |
|-----------------------------------------------------------------------------------------|---------------------------------------------| |-----------------------------------------------------------------------------------------|---------------------------------------------|
...@@ -45,121 +45,131 @@ The following example describes how to implement many-to-many data sharing. The ...@@ -45,121 +45,131 @@ The following example describes how to implement many-to-many data sharing. The
### Data Provider ### Data Provider
1. Import the **@ohos.data.UDMF** module. 1. Import the **@ohos.data.unifiedDataChannel** and **@ohos.data.uniformTypeDescriptor** modules.
```ts ```ts
import UDMF from '@ohos.data.UDMF'; import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
``` ```
2. Create a **UnifiedData** object and insert it into the UDMF public data channel. 2. Create a **UnifiedData** object and insert it into the UDMF public data channel.
```ts ```ts
let plainText = new UDMF.PlainText(); import { BusinessError } from '@ohos.base';
let plainText = new unifiedDataChannel.PlainText();
plainText.textContent = 'hello world!'; plainText.textContent = 'hello world!';
let unifiedData = new UDMF.UnifiedData(plainText); let unifiedData = new unifiedDataChannel.UnifiedData(plainText);
// Specify the type of the data channel to which the data is to be inserted. // Specify the type of the data channel to which the data is to be inserted.
let options = { let options: unifiedDataChannel.Options = {
intention: UDMF.Intention.DATA_HUB intention: unifiedDataChannel.Intention.DATA_HUB
} }
try { try {
UDMF.insertData(options, unifiedData, (err, data) => { unifiedDataChannel.insertData(options, unifiedData, (err, data) => {
if (err === undefined) { if (err === undefined) {
console.info(`Succeeded in inserting data. key = ${data}`); console.info(`Succeeded in inserting data. key = ${data}`);
} else { } else {
console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `); console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `);
} }
}); });
} catch(e) { } catch (e) {
console.error(`Insert data throws an exception. code is ${e.code},message is ${e.message} `); let error: BusinessError = e as BusinessError;
console.error(`Insert data throws an exception. code is ${error.code},message is ${error.message} `);
} }
``` ```
3. Update the **UnifiedData** object inserted. 3. Update the **UnifiedData** object inserted.
```ts ```ts
let plainText = new UDMF.PlainText(); import { BusinessError } from '@ohos.base';
let plainText = new unifiedDataChannel.PlainText();
plainText.textContent = 'How are you!'; plainText.textContent = 'How are you!';
let unifiedData = new UDMF.UnifiedData(plainText); let unifiedData = new unifiedDataChannel.UnifiedData(plainText);
// Specify the URI of the UnifiedData object to update. // Specify the URI of the UnifiedData object to update.
let options = { let options: unifiedDataChannel.Options = {
key: 'udmf://DataHub/com.ohos.test/0123456789' key: 'udmf://DataHub/com.ohos.test/0123456789'
}; };
try { try {
UDMF.updateData(options, unifiedData, (err) => { unifiedDataChannel.updateData(options, unifiedData, (err) => {
if (err === undefined) { if (err === undefined) {
console.info('Succeeded in updating data.'); console.info('Succeeded in updating data.');
} else { } else {
console.error(`Failed to update data. code is ${err.code},message is ${err.message} `); console.error(`Failed to update data. code is ${err.code},message is ${err.message} `);
} }
}); });
} catch(e) { } catch (e) {
console.error(`Update data throws an exception. code is ${e.code},message is ${e.message} `); let error: BusinessError = e as BusinessError;
console.error(`Update data throws an exception. code is ${error.code},message is ${error.message} `);
} }
``` ```
4. Delete the **UnifiedData** object from the UDMF public data channel. 4. Delete the **UnifiedData** object from the UDMF public data channel.
```ts ```ts
import { BusinessError } from '@ohos.base';
// Specify the type of the data channel whose data is to be deleted. // Specify the type of the data channel whose data is to be deleted.
let options = { let options: unifiedDataChannel.Options = {
intention: UDMF.Intention.DATA_HUB intention: unifiedDataChannel.Intention.DATA_HUB
}; };
try { try {
UDMF.deleteData(options, (err, data) => { unifiedDataChannel.deleteData(options, (err, data) => {
if (err === undefined) { if (err === undefined) {
console.info(`Succeeded in deleting data. size = ${data.length}`); console.info(`Succeeded in deleting data. size = ${data.length}`);
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
let records = data[i].getRecords(); let records = data[i].getRecords();
for (let j = 0; j < records.length; j++) { for (let j = 0; j < records.length; j++) {
if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) { if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) {
let text = <UDMF.PlainText>(records[j]); let text = records[j] as unifiedDataChannel.PlainText;
console.info(`${i + 1}.${text.textContent}`); console.info(`${i + 1}.${text.textContent}`);
} }
}
}
} else {
console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `);
} }
}); }
} catch(e) { } else {
console.error(`Delete data throws an exception. code is ${e.code},message is ${e.message} `); console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `);
}
});
} catch (e) {
let error: BusinessError = e as BusinessError;
console.error(`Delete data throws an exception. code is ${error.code},message is ${error.message} `);
} }
``` ```
### Data Consumer ### Data Consumer
1. Import the **@ohos.data.UDMF** module. 1. Import the **@ohos.data.unifiedDataChannel** and **@ohos.data.uniformTypeDescriptor** modules.
```ts ```ts
import UDMF from '@ohos.data.UDMF'; import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
``` ```
2. Query the **UnifiedData** object in the UDMF public data channel. 2. Query the **UnifiedData** object in the UDMF public data channel.
```ts ```ts
import { BusinessError } from '@ohos.base';
// Specify the type of the data channel whose data is to be queried. // Specify the type of the data channel whose data is to be queried.
let options = { let options: unifiedDataChannel.Options = {
intention: UDMF.Intention.DATA_HUB intention: unifiedDataChannel.Intention.DATA_HUB
}; };
try { try {
UDMF.queryData(options, (err, data) => { unifiedDataChannel.queryData(options, (err, data) => {
if (err === undefined) { if (err === undefined) {
console.info(`Succeeded in querying data. size = ${data.length}`); console.info(`Succeeded in querying data. size = ${data.length}`);
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
let records = data[i].getRecords(); let records = data[i].getRecords();
for (let j = 0; j < records.length; j++) { for (let j = 0; j < records.length; j++) {
if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) { if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) {
let text = <UDMF.PlainText>(records[j]); let text = records[j] as unifiedDataChannel.PlainText;
console.info(`${i + 1}.${text.textContent}`); console.info(`${i + 1}.${text.textContent}`);
} }
}
}
} else {
console.error(`Failed to query data. code is ${err.code},message is ${err.message} `);
} }
}); }
} else {
console.error(`Failed to query data. code is ${err.code},message is ${err.message} `);
}
});
} catch(e) { } catch(e) {
console.error(`Query data throws an exception. code is ${e.code},message is ${e.message} `); let error: BusinessError = e as BusinessError;
console.error(`Query data throws an exception. code is ${error.code},message is ${error.message} `);
} }
``` ```
...@@ -5,28 +5,35 @@ ...@@ -5,28 +5,35 @@
To streamline cross-application data interaction of OpenHarmony and minimize the application/service data interaction costs, the Unified Data Management Framework (UDMF) provides standard data definitions to define common data types. Applications can use the APIs provided by the UDMF to create and use these data types. To streamline cross-application data interaction of OpenHarmony and minimize the application/service data interaction costs, the Unified Data Management Framework (UDMF) provides standard data definitions to define common data types. Applications can use the APIs provided by the UDMF to create and use these data types.
For example, in the cross-application drag scenario, the application of the drag source writes the data to be dragged to a [drag event](../reference/arkui-ts/ts-universal-events-drag-drop.md#dragevent) based on the standard data definitions. The application of the drop target reads the dragged data from the drag event and parses the data based on the standard data definitions. The data dragged between different applications complies with the same standard definitions, which avoids exhaustive data type adaptation and effectively reduces the development workload.
## Unified Data Types ## Unified Data Types
The UDMF provides the following unified data types: The UDMF provides the following unified data types:
**Basic data types**<br>Basic data types include File and Text, which can be used for cross-application and cross-platform data interaction. Figure 1 and Figure 2 illustrate the basic data types. **Basic data types**
Basic data types include File and Text, which can be used for cross-application and cross-platform data interaction. Figure 1 and Figure 2 illustrate the basic data types.
**Figure 1** UDMF File **Figure 1** UDMF File
![UDMF_FILE](figures/udmf_type_File.png) ![UDMF_FILE](figures/udmf_type_File.png)
Figure 2 UDMF Text **Figure 2** UDMF Text
![UDMF_TEXT](figures/udmf_type_Text.png) ![UDMF_TEXT](figures/udmf_type_Text.png)
**System Defined Types (SDTs)**<br>The SDTs are specific to the platform or operating system, such as Form (UI card information), AppItem (app description information), and PixelMap (thumbnail). This type of data can be used for cross-application data interaction in a system or platform. Figure 3 illustrates the SDT data. **System Defined Types (SDTs)**
The SDTs are specific to the platform or operating system, such as Form (UI card information), AppItem (app description information), and PixelMap (thumbnail). This type of data can be used for cross-application data interaction in a system or platform. Figure 3 illustrates the SDT data.
**Figure 3** UDMF SDT data **Figure 3** UDMF SDT data
![UDMF_SDT](figures/udmf_type_SDT.png) ![UDMF_SDT](figures/udmf_type_SDT.png)
**App Defined Type (ADT)**<br>The SDT data is application-specific. This type of data can be used for across-platform data interaction for an application. As shown in Figure 4, the MyFile file format can be defined for use in an application ecosystem. **App Defined Type (ADT)**
The SDT data is application-specific. This type of data can be used for across-platform data interaction for an application. As shown in Figure 4, the MyFile file format can be defined for use in an application ecosystem.
**Figure 4** UDMF ADT data **Figure 4** UDMF ADT data
...@@ -39,11 +46,11 @@ Figure 2 UDMF Text ...@@ -39,11 +46,11 @@ Figure 2 UDMF Text
## Available APIs ## Available APIs
The UDMF provides the unified data object **UnifiedData** to encapsulate a group of data records **UnifiedRecord**. **UnifiedRecord** is an abstract definition of data content supported by the UDMF, for example, a text record or an image record. The data content type in a data record corresponds to **UnifiedDataType**. The UDMF provides the unified data object **UnifiedData** to encapsulate a group of data records **UnifiedRecord**. **UnifiedRecord** is an abstract definition of data content supported by the UDMF, for example, a text record or an image record. The data content type in a data record corresponds to **UniformDataType**.
The following table describes common UDMF APIs. For more information, see [UDMF](../reference/apis/js-apis-data-udmf.md). The following table describes common UDMF APIs. For more information about the APIs, see [Unified Data Channel](../reference/apis/js-apis-data-unifiedDataChannel.md) and [Standard Data Definition and Description](../reference/apis/js-apis-data-uniformTypeDescriptor.md).
| Class | API | Description | | Class | API | Description |
|---------------|-------------------|-----------------------------------------------------------------------------------------------| |---------------|-------------------|-----------------------------------------------------------------------------------------------|
| UnifiedRecord | getType(): string | Obtains the data type of this data record.| | UnifiedRecord | getType(): string | Obtains the data type of this data record.|
| UnifiedData | constructor(record: UnifiedRecord) | A constructor used to create a **UnifiedData** object with a data record. | | UnifiedData | constructor(record: UnifiedRecord) | A constructor used to create a **UnifiedData** object with a data record. |
...@@ -55,17 +62,19 @@ The following table describes common UDMF APIs. For more information, see [UDMF] ...@@ -55,17 +62,19 @@ The following table describes common UDMF APIs. For more information, see [UDMF]
The following describes how to create a **UnifiedData** object containing two data records: image and plain text. The following describes how to create a **UnifiedData** object containing two data records: image and plain text.
1. Import the **@ohos.data.UDMF** module. 1. Import the **@ohos.data.unifiedDataChannel** and **@ohos.data.uniformTypeDescriptor** modules.
```ts ```ts
import UDMF from '@ohos.data.UDMF'; import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
``` ```
2. Create an image data record and initialize the **UnifiedData** object with the image data record. 2. Create an image data record and initialize the **UnifiedData** object with the image data record.
(1) Create an image data record. (1) Create an image data record.
```ts ```ts
let image = new UDMF.Image(); let image = new unifiedDataChannel.Image();
``` ```
(2) Modify object attributes. (2) Modify object attributes.
...@@ -84,12 +93,13 @@ The following describes how to create a **UnifiedData** object containing two da ...@@ -84,12 +93,13 @@ The following describes how to create a **UnifiedData** object containing two da
(4) Create a **UnifiedData** instance. (4) Create a **UnifiedData** instance.
```ts ```ts
let unifiedData = new UDMF.UnifiedData(image); let unifiedData = new unifiedDataChannel.UnifiedData(image);
``` ```
3. Create a plain text data record and add it to the **UnifiedData** instance created.
3. Create a plain text data record and add it to the **UnifiedData** instance created.
```ts ```ts
let plainText = new UDMF.PlainText(); let plainText = new unifiedDataChannel.PlainText();
plainText.textContent = 'this is textContent of plainText'; plainText.textContent = 'this is textContent of plainText';
plainText.abstract = 'abstract of plainText'; plainText.abstract = 'abstract of plainText';
plainText.details = { plainText.details = {
...@@ -98,25 +108,27 @@ The following describes how to create a **UnifiedData** object containing two da ...@@ -98,25 +108,27 @@ The following describes how to create a **UnifiedData** object containing two da
}; };
unifiedData.addRecord(plainText); unifiedData.addRecord(plainText);
``` ```
4. Obtain all data records in this **UnifiedData** instance. 4. Obtain all data records in this **UnifiedData** instance.
```ts ```ts
let records = unifiedData.getRecords(); let records = unifiedData.getRecords();
``` ```
5. Traverse each record, determine the data type of the record, and convert the record into a child class object to obtain the original data record. 5. Traverse each record, determine the data type of the record, and convert the record into a child class object to obtain the original data record.
```ts ```ts
for (let i = 0; i < records.length; i ++) { for (let i = 0; i < records.length; i ++) {
// Read the type of the data record. // Read the type of the data record.
let type = records[i].getType(); let type = records[i].getType();
switch (type) { switch (type) {
case UDMF.UnifiedDataType.IMAGE: case uniformTypeDescriptor.UniformDataType.IMAGE:
// Convert the data to obtain the original image data record. // Convert the data to obtain the original image data record.
let image = <UDMF.Image>(records[i]); let image = records[i] as unifiedDataChannel.Image;
break; break;
case UDMF.UnifiedDataType.PLAIN_TEXT: case uniformTypeDescriptor.UniformDataType.PLAIN_TEXT:
// Convert the data to obtain the original text record. // Convert the data to obtain the original text record.
let plainText = <UDMF.PlainText>(records[i]); let plainText = records[i] as unifiedDataChannel.PlainText;
break; break;
default: default:
break; break;
......
...@@ -36,7 +36,7 @@ You can use [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement ac ...@@ -36,7 +36,7 @@ You can use [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement ac
First, obtain the [application file path](../application-models/application-context-stage.md#obtaining-application-file-paths). The following example shows how to obtain a HAP file path using **UIAbilityContext**. For details about how to obtain **UIAbilityContext**, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability). First, obtain the [application file path](../application-models/application-context-stage.md#obtaining-application-file-paths). The following example shows how to obtain a HAP file path using **UIAbilityContext**. For details about how to obtain **UIAbilityContext**, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
Then, perform common file operations. Then, perform file operations.
### Creating, Reading, and Writing a File ### Creating, Reading, and Writing a File
...@@ -46,21 +46,29 @@ The following example demonstrates how to create a file, read data from it, and ...@@ -46,21 +46,29 @@ The following example demonstrates how to create a file, read data from it, and
// pages/xxx.ets // pages/xxx.ets
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
import buffer from '@ohos.buffer';
function createFile() { // Obtain the application file path.
// Obtain the application file path. let context = getContext(this) as common.UIAbilityContext;
let context = getContext(this) as common.UIAbilityContext; let filesDir = context.filesDir;
let filesDir = context.filesDir;
// Create a file and open it. function createFile() {
// Create a file and open it.
let file = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); let file = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
// Write data to the file. // Write data to the file.
let writeLen = fs.writeSync(file.fd, "Try to write str."); let writeLen = fs.writeSync(file.fd, "Try to write str.");
console.info("The length of str is: " + writeLen); console.info("The length of str is: " + writeLen);
// Read data from the file. // Read data from the file.
let buf = new ArrayBuffer(1024); let arrayBuffer = new ArrayBuffer(1024);
let readLen = fs.readSync(file.fd, buf, { offset: 0 }); class Option {
console.info("the content of file: " + String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))); public offset: number = 0;
public length: number;
}
let option = new Option();
option.length = arrayBuffer.byteLength;
let readLen = fs.readSync(file.fd, arrayBuffer, option);
let buf = buffer.from(arrayBuffer, 0, readLen);
console.info("the content of file: " + buf.toString());
// Close the file. // Close the file.
fs.closeSync(file); fs.closeSync(file);
} }
...@@ -75,11 +83,11 @@ function createFile() { ...@@ -75,11 +83,11 @@ function createFile() {
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
function readWriteFile() { // Obtain the application file path.
// Obtain the application file path. let context = getContext(this) as common.UIAbilityContext;
let context = getContext(this) as common.UIAbilityContext; let filesDir = context.filesDir;
let filesDir = context.filesDir;
function readWriteFile() {
// Open the source and destination files. // Open the source and destination files.
let srcFile = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE); let srcFile = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE);
let destFile = fs.openSync(filesDir + '/destFile.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); let destFile = fs.openSync(filesDir + '/destFile.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
...@@ -87,11 +95,18 @@ function readWriteFile() { ...@@ -87,11 +95,18 @@ function readWriteFile() {
let bufSize = 4096; let bufSize = 4096;
let readSize = 0; let readSize = 0;
let buf = new ArrayBuffer(bufSize); let buf = new ArrayBuffer(bufSize);
let readLen = fs.readSync(srcFile.fd, buf, { offset: readSize }); class Option {
public offset: number = 0;
public length: number = bufSize;
}
let option = new Option();
option.offset = readSize;
let readLen = fs.readSync(srcFile.fd, buf, option);
while (readLen > 0) { while (readLen > 0) {
readSize += readLen; readSize += readLen;
fs.writeSync(destFile.fd, buf); fs.writeSync(destFile.fd, buf);
readLen = fs.readSync(srcFile.fd, buf, { offset: readSize }); option.offset = readSize;
readLen = fs.readSync(srcFile.fd, buf, option);
} }
// Close the files. // Close the files.
fs.closeSync(srcFile); fs.closeSync(srcFile);
...@@ -112,11 +127,11 @@ The following example demonstrates how to read and write file data using a strea ...@@ -112,11 +127,11 @@ The following example demonstrates how to read and write file data using a strea
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
async function readWriteFileWithStream() { // Obtain the application file path.
// Obtain the application file path. let context = getContext(this) as common.UIAbilityContext;
let context = getContext(this) as common.UIAbilityContext; let filesDir = context.filesDir;
let filesDir = context.filesDir;
async function readWriteFileWithStream() {
// Open the file streams. // Open the file streams.
let inputStream = fs.createStreamSync(filesDir + '/test.txt', 'r+'); let inputStream = fs.createStreamSync(filesDir + '/test.txt', 'r+');
let outputStream = fs.createStreamSync(filesDir + '/destFile.txt', "w+"); let outputStream = fs.createStreamSync(filesDir + '/destFile.txt', "w+");
...@@ -124,11 +139,18 @@ async function readWriteFileWithStream() { ...@@ -124,11 +139,18 @@ async function readWriteFileWithStream() {
let bufSize = 4096; let bufSize = 4096;
let readSize = 0; let readSize = 0;
let buf = new ArrayBuffer(bufSize); let buf = new ArrayBuffer(bufSize);
let readLen = await inputStream.read(buf, { offset: readSize }); class Option {
public offset: number = 0;
public length: number = bufSize;
}
let option = new Option();
option.offset = readSize;
let readLen = await inputStream.read(buf, option);
readSize += readLen; readSize += readLen;
while (readLen > 0) { while (readLen > 0) {
await outputStream.write(buf); await outputStream.write(buf);
readLen = await inputStream.read(buf, { offset: readSize }); option.offset = readSize;
readLen = await inputStream.read(buf, option);
readSize += readLen; readSize += readLen;
} }
// Close the streams. // Close the streams.
...@@ -148,8 +170,7 @@ async function readWriteFileWithStream() { ...@@ -148,8 +170,7 @@ async function readWriteFileWithStream() {
The following example demonstrates how to list files that meet the specified conditions. The following example demonstrates how to list files that meet the specified conditions.
```ts ```ts
// List files. import fs, { Filter } from '@ohos.file.fs';
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
// Obtain the application file path. // Obtain the application file path.
...@@ -157,18 +178,20 @@ let context = getContext(this) as common.UIAbilityContext; ...@@ -157,18 +178,20 @@ let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir; let filesDir = context.filesDir;
// List files that meet the specified conditions. // List files that meet the specified conditions.
let options = { function getListFile() {
recursion: false, class ListFileOption {
listNum: 0, public recursion: boolean = false;
filter: { public listNum: number = 0;
suffix: ['.png', '.jpg', '.txt'], // The filename extension can be '.png', '.jpg', or '.txt'. public filter: Filter
displayName: ['test%'], // The filename starts with 'test'. }
fileSizeOver: 0, // The file size is greater than or equal to 0. let option = new ListFileOption();
lastModifiedAfter: new Date(0).getTime(), // The latest modification time of the file is later than January 1, 1970. option.filter.suffix = ['.png', '.jpg', '.txt']; // The filen ame extension can be '.png', '.jpg', or '.txt'.
}, option.filter.displayName = ['test%']; // The file name starts with 'test'.
} option.filter.fileSizeOver = 0; // The file size is greater than or equal to 0.
let files = fs.listFileSync(filesDir, options); option.filter.lastModifiedAfter = new Date(0).getTime(); // The latest modification time of the file is later than January 1, 1970.
for (let i = 0; i < files.length; i++) { let files = fs.listFileSync(filesDir, option);
console.info(`The name of file: ${files[i]}`); for (let i = 0; i < files.length; i++) {
console.info(`The name of file: ${files[i]}`);
}
} }
``` ```
...@@ -32,17 +32,25 @@ The capability file of an application contains the device type, device version, ...@@ -32,17 +32,25 @@ The capability file of an application contains the device type, device version,
Use **backup.getLocalCapabilities()** to obtain capability files. Use **backup.getLocalCapabilities()** to obtain capability files.
```js ```ts
import backup from '@ohos.file.backup';
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
async function getLocalCapabilities() { async function getLocalCapabilities() {
try { try {
let fileData = await backup.getLocalCapabilities(); let fileData = await backup.getLocalCapabilities();
console.info('getLocalCapabilities success'); console.info('getLocalCapabilities success');
let fpath = await globalThis.context.filesDir + '/localCapabilities.json'; let fpath = filesDir + '/localCapabilities.json';
fs.copyFileSync(fileData.fd, fpath); fs.copyFileSync(fileData.fd, fpath);
fs.closeSync(fileData.fd); fs.closeSync(fileData.fd);
} catch (err) { } catch (error) {
console.error('getLocalCapabilities failed with err: ' + err); let err: BusinessError = error as BusinessError;
console.error('getLocalCapabilities failed with err: ' + JSON.stringify(err));
} }
} }
``` ```
...@@ -88,17 +96,24 @@ You can save the file to a local directory as required. ...@@ -88,17 +96,24 @@ You can save the file to a local directory as required.
**Example** **Example**
```ts ```ts
import backup from '@ohos.file.backup';
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
// Obtain the sandbox path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// Create a SessionBackup instance for data backup. // Create a SessionBackup instance for data backup.
let g_session; let g_session: backup.SessionBackup;
function createSessionBackup() { function createSessionBackup() {
let sessionBackup = new backup.SessionBackup({ let generalCallbacks: backup.GeneralCallbacks = {
onFileReady: async (err, file) => { onFileReady: (err: BusinessError, file: backup.File) => {
if (err) { if (err) {
console.info('onFileReady err: ' + err); console.info('onFileReady err: ' + JSON.stringify(err));
} }
try { try {
let bundlePath = await globalThis.context.filesDir + '/' + file.bundleName; let bundlePath = filesDir + '/' + file.bundleName;
if (!fs.accessSync(bundlePath)) { if (!fs.accessSync(bundlePath)) {
fs.mkdirSync(bundlePath); fs.mkdirSync(bundlePath);
} }
...@@ -109,23 +124,23 @@ You can save the file to a local directory as required. ...@@ -109,23 +124,23 @@ You can save the file to a local directory as required.
console.error('onFileReady failed with err: ' + e); console.error('onFileReady failed with err: ' + e);
} }
}, },
onBundleBegin: (err, bundleName) => { onBundleBegin: (err: BusinessError, bundleName: string) => {
if (err) { if (err) {
console.info('onBundleBegin err: ' + err); console.info('onBundleBegin err: ' + JSON.stringify(err));
} else { } else {
console.info('onBundleBegin bundleName: ' + bundleName); console.info('onBundleBegin bundleName: ' + bundleName);
} }
}, },
onBundleEnd: (err, bundleName) => { onBundleEnd: (err: BusinessError, bundleName: string) => {
if (err) { if (err) {
console.info('onBundleEnd err: ' + err); console.info('onBundleEnd err: ' + JSON.stringify(err));
} else { } else {
console.info('onBundleEnd bundleName: ' + bundleName); console.info('onBundleEnd bundleName: ' + bundleName);
} }
}, },
onAllBundlesEnd: (err) => { onAllBundlesEnd: (err: BusinessError) => {
if (err) { if (err) {
console.info('onAllBundlesEnd err: ' + err); console.info('onAllBundlesEnd err: ' + JSON.stringify(err));
} else { } else {
console.info('onAllBundlesEnd'); console.info('onAllBundlesEnd');
} }
...@@ -133,16 +148,16 @@ You can save the file to a local directory as required. ...@@ -133,16 +148,16 @@ You can save the file to a local directory as required.
onBackupServiceDied: () => { onBackupServiceDied: () => {
console.info('onBackupServiceDied'); console.info('onBackupServiceDied');
}, },
}); }
let sessionBackup = new backup.SessionBackup(generalCallbacks);
return sessionBackup; return sessionBackup;
} }
async function sessionBackup () async function sessionBackup () {
{
g_session = createSessionBackup(); g_session = createSessionBackup();
// Select the application to be backed up based on the capability file obtained by backup.getLocalCapabilities(). // Select the application to be backed up based on the capability file obtained by backup.getLocalCapabilities().
// You can also back up data based on the application bundle name. // You can also back up data based on the application bundle name.
const backupApps = [ const backupApps: string[] = [
"com.example.hiworld", "com.example.hiworld",
] ]
await g_session.appendBundles(backupApps); await g_session.appendBundles(backupApps);
...@@ -161,24 +176,26 @@ When all the data of the application is ready, the service starts to restore the ...@@ -161,24 +176,26 @@ When all the data of the application is ready, the service starts to restore the
**Example** **Example**
```ts ```ts
import backup from '@ohos.file.backup';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
// Create a SessionRestore instance for data restoration. // Create a SessionRestore instance for data restoration.
let g_session; let g_session: backup.SessionRestore;
async function publishFile(file) async function publishFile(file: backup.File) {
{ let fileMeta: backup.FileMeta = {
await g_session.publishFile({
bundleName: file.bundleName, bundleName: file.bundleName,
uri: file.uri uri: file.uri
}); }
await g_session.publishFile(fileMeta);
} }
function createSessionRestore() { function createSessionRestore() {
let sessionRestore = new backup.SessionRestore({ let generalCallbacks: backup.GeneralCallbacks = {
onFileReady: (err, file) => { onFileReady: (err: BusinessError, file: backup.File) => {
if (err) { if (err) {
console.info('onFileReady err: ' + err); console.info('onFileReady err: ' + JSON.stringify(err));
} }
// Set bundlePath based on the actual situation. // Set bundlePath based on the actual situation.
let bundlePath; let bundlePath: string;
if (!fs.accessSync(bundlePath)) { if (!fs.accessSync(bundlePath)) {
console.info('onFileReady bundlePath err : ' + bundlePath); console.info('onFileReady bundlePath err : ' + bundlePath);
} }
...@@ -188,52 +205,51 @@ When all the data of the application is ready, the service starts to restore the ...@@ -188,52 +205,51 @@ When all the data of the application is ready, the service starts to restore the
publishFile(file); publishFile(file);
console.info('onFileReady success'); console.info('onFileReady success');
}, },
onBundleBegin: (err, bundleName) => { onBundleBegin: (err: BusinessError, bundleName: string) => {
if (err) { if (err) {
console.error('onBundleBegin failed with err: ' + err); console.error('onBundleBegin failed with err: ' + JSON.stringify(err));
} }
console.info('onBundleBegin success'); console.info('onBundleBegin success');
}, },
onBundleEnd: (err, bundleName) => { onBundleEnd: (err: BusinessError, bundleName: string) => {
if (err) { if (err) {
console.error('onBundleEnd failed with err: ' + err); console.error('onBundleEnd failed with err: ' + JSON.stringify(err));
} }
console.info('onBundleEnd success'); console.info('onBundleEnd success');
}, },
onAllBundlesEnd: (err) => { onAllBundlesEnd: (err: BusinessError) => {
if (err) { if (err) {
console.error('onAllBundlesEnd failed with err: ' + err); console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err));
} }
console.info('onAllBundlesEnd success'); console.info('onAllBundlesEnd success');
}, },
onBackupServiceDied: () => { onBackupServiceDied: () => {
console.info('service died'); console.info('service died');
} }
}); }
let sessionRestore = new backup.SessionRestore(generalCallbacks);
return sessionRestore; return sessionRestore;
} }
async function restore () async function restore01 () {
{
g_session = createSessionRestore(); g_session = createSessionRestore();
const backupApps = [ const restoreApps: string[] = [
"com.example.hiworld", "com.example.hiworld",
] ]
// You can obtain the capability file based on actual situation. The following is an example only. // You can obtain the capability file based on actual situation. The following is an example only.
// You can also construct capability files as required. // You can also construct capability files as required.
let fileData = await backup.getLocalCapabilities(); let fileData = await backup.getLocalCapabilities();
await g_session.appendBundles(fileData.fd, backupApps); await g_session.appendBundles(fileData.fd, restoreApps);
console.info('appendBundles success'); console.info('appendBundles success');
// After the applications to be restored are added, call getFileHandle() to obtain the handles of the application files to be restored based on the application name. // After the applications to be restored are added, call getFileHandle() to obtain the handles of the application files to be restored based on the application name.
// The number of application data files to be restored varies depending on the number of backup files. The following is only an example. // The number of application data files to be restored varies depending on the number of backup files. The following is only an example.
await g_session.getFileHandle({ let handle: backup.FileMeta = {
bundleName: restoreApps[0], bundleName: restoreApps[0],
uri: "manage.json" uri: "manage.json"
}); }
await g_session.getFileHandle({ await g_session.getFileHandle(handle);
bundleName: restoreApps[0], handle.uri = "1.tar";
uri: "1.tar" await g_session.getFileHandle(handle);
});
console.info('getFileHandle success'); console.info('getFileHandle success');
} }
``` ```
...@@ -249,23 +265,30 @@ If the application has not been installed, you can install the application and t ...@@ -249,23 +265,30 @@ If the application has not been installed, you can install the application and t
**Example** **Example**
```ts ```ts
import backup from '@ohos.file.backup';
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
// Obtain the sandbox path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// Create a SessionRestore instance for data restoration. // Create a SessionRestore instance for data restoration.
let g_session; let g_session: backup.SessionRestore;
async function publishFile(file) async function publishFile(file: backup.File) {
{ let fileMeta: backup.FileMeta = {
await g_session.publishFile({
bundleName: file.bundleName, bundleName: file.bundleName,
uri: file.uri uri: file.uri
}); }
await g_session.publishFile(fileMeta);
} }
function createSessionRestore() { function createSessionRestore() {
let sessionRestore = new backup.SessionRestore({ let generalCallbacks: backup.GeneralCallbacks = {
onFileReady: (err, file) => { onFileReady: (err: BusinessError, file: backup.File) => {
if (err) { if (err) {
console.info('onFileReady err: ' + err); console.info('onFileReady err: ' + JSON.stringify(err));
} }
let bundlePath; let bundlePath: string;
if( file.uri == "/data/storage/el2/restore/bundle.hap" ) if( file.uri == "/data/storage/el2/restore/bundle.hap" )
{ {
// Set the path of the application installation package based on actual situation. // Set the path of the application installation package based on actual situation.
...@@ -281,61 +304,57 @@ If the application has not been installed, you can install the application and t ...@@ -281,61 +304,57 @@ If the application has not been installed, you can install the application and t
publishFile(file); publishFile(file);
console.info('onFileReady success'); console.info('onFileReady success');
}, },
onBundleBegin: (err, bundleName) => { onBundleBegin: (err: BusinessError, bundleName: string) => {
if (err) { if (err) {
console.error('onBundleBegin failed with err: ' + err); console.error('onBundleBegin failed with err: ' + JSON.stringify(err));
} }
console.info('onBundleBegin success'); console.info('onBundleBegin success');
}, },
onBundleEnd: (err, bundleName) => { onBundleEnd: (err: BusinessError, bundleName: string) => {
if (err) { if (err) {
console.error('onBundleEnd failed with err: ' + err); console.error('onBundleEnd failed with err: ' + JSON.stringify(err));
} }
console.info('onBundleEnd success'); console.info('onBundleEnd success');
}, },
onAllBundlesEnd: (err) => { onAllBundlesEnd: (err: BusinessError) => {
if (err) { if (err) {
console.error('onAllBundlesEnd failed with err: ' + err); console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err));
} }
console.info('onAllBundlesEnd success'); console.info('onAllBundlesEnd success');
}, },
onBackupServiceDied: () => { onBackupServiceDied: () => {
console.info('service died'); console.info('service died');
} }
}); }
let sessionRestore = new backup.SessionRestore(generalCallbacks);
return sessionRestore; return sessionRestore;
} }
async function restore () async function restore02 () {
{
g_session = createSessionRestore(); g_session = createSessionRestore();
const backupApps = [ const restoreApps: string[] = [
"com.example.hiworld", "com.example.hiworld",
] ]
let fpath = await globalThis.context.filesDir + '/localCapabilities.json'; let fpath = filesDir + '/localCapabilities.json';
let file = fs.openSync(fpath, fileIO.OpenMode.CREATE | fileIO.OpenMode.READ_WRITE); let file = fs.openSync(fpath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
let content = "{\"bundleInfos\" :[{\"allToBackup\" : false,\"extensionName\" : \"\"," + let content = "{\"bundleInfos\" :[{\"allToBackup\" : false,\"extensionName\" : \"\"," +
"\"name\" : \"cn.openharmony.inputmethodchoosedialog\",\"needToInstall\" : true,\"spaceOccupied\" : 0," + "\"name\" : \"cn.openharmony.inputmethodchoosedialog\",\"needToInstall\" : true,\"spaceOccupied\" : 0," +
"\"versionCode\" : 1000000,\"versionName\" : \"1.0.0\"}],\"deviceType\" : \"default\",\"systemFullName\" : \"OpenHarmony-4.0.6.2(Canary1)\"}"; "\"versionCode\" : 1000000,\"versionName\" : \"1.0.0\"}],\"deviceType\" : \"default\",\"systemFullName\" : \"OpenHarmony-4.0.6.2(Canary1)\"}";
fs.writeSync(file.fd, content); fs.writeSync(file.fd, content);
fs.fsyncSync(file.fd); fs.fsyncSync(file.fd);
await g_session.appendBundles(file.fd, backupApps); await g_session.appendBundles(file.fd, restoreApps);
console.info('appendBundles success'); console.info('appendBundles success');
// Obtain the file handle of the application to be installed. // Obtain the file handle of the application to be installed.
await g_session.getFileHandle({ let handle: backup.FileMeta = {
bundleName: restoreApps[0], bundleName: restoreApps[0],
uri: "/data/storage/el2/restore/bundle.hap" uri: "/data/storage/el2/restore/bundle.hap"
}); }
await g_session.getFileHandle(handle);
await g_session.getFileHandle({ handle.uri = "manage.json";
bundleName: restoreApps[0], await g_session.getFileHandle(handle);
uri: "manage.json" handle.uri = "1.tar";
}); await g_session.getFileHandle(handle);
await g_session.getFileHandle({
bundleName: restoreApps[0],
uri: "1.tar"
});
console.info('getFileHandle success'); console.info('getFileHandle success');
} }
``` ```
......
...@@ -19,6 +19,7 @@ The following example demonstrates how to upload a file in the **cache** directo ...@@ -19,6 +19,7 @@ The following example demonstrates how to upload a file in the **cache** directo
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import request from '@ohos.request'; import request from '@ohos.request';
import { BusinessError } from '@ohos.base';
// Obtain the application file path. // Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext; let context = getContext(this) as common.UIAbilityContext;
...@@ -30,32 +31,36 @@ fs.writeSync(file.fd, 'upload file test'); ...@@ -30,32 +31,36 @@ fs.writeSync(file.fd, 'upload file test');
fs.closeSync(file); fs.closeSync(file);
// Configure the upload task. // Configure the upload task.
let uploadConfig = { let header = new Map<Object, string>();
header.set('key1', 'value1');
header.set('key2', 'value2');
let files: Array<request.File> = [
{ filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' }
]
let data: Array<request.RequestData> = [{ name: 'name', value: 'value' }];
let uploadConfig: request.UploadConfig = {
url: 'https://xxx', url: 'https://xxx',
header: { key1: 'value1', key2: 'value2' }, header: header,
method: 'POST', method: 'POST',
files: [ files: files,
{ filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' } data: data
],
data: [
{ name: 'name', value: 'value' }
]
} }
// Upload the created application file to the network server. // Upload the created application file to the network server.
try { try {
request.uploadFile(context, uploadConfig) request.uploadFile(context, uploadConfig)
.then((uploadTask) => { .then((uploadTask: request.UploadTask) => {
uploadTask.on('complete', (taskStates) => { uploadTask.on('complete', (taskStates: Array<request.TaskState>) => {
for (let i = 0; i < taskStates.length; i++) { for (let i = 0; i < taskStates.length; i++) {
console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`); console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`);
} }
}); });
}) })
.catch((err) => { .catch((err: BusinessError) => {
console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
}) })
} catch (err) { } catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
} }
``` ```
...@@ -78,6 +83,8 @@ The following example demonstrates how to download a network resource file to a ...@@ -78,6 +83,8 @@ The following example demonstrates how to download a network resource file to a
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import request from '@ohos.request'; import request from '@ohos.request';
import { BusinessError } from '@ohos.base';
import buffer from '@ohos.buffer';
// Obtain the application file path. // Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext; let context = getContext(this) as common.UIAbilityContext;
...@@ -87,19 +94,21 @@ try { ...@@ -87,19 +94,21 @@ try {
request.downloadFile(context, { request.downloadFile(context, {
url: 'https://xxxx/xxxx.txt', url: 'https://xxxx/xxxx.txt',
filePath: filesDir + '/xxxx.txt' filePath: filesDir + '/xxxx.txt'
}).then((downloadTask) => { }).then((downloadTask: request.DownloadTask) => {
downloadTask.on('complete', () => { downloadTask.on('complete', () => {
console.info('download complete'); console.info('download complete');
let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE); let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE);
let buf = new ArrayBuffer(1024); let arrayBuffer = new ArrayBuffer(1024);
let readLen = fs.readSync(file.fd, buf); let readLen = fs.readSync(file.fd, arrayBuffer);
console.info(`The content of file: ${String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))}`); let buf = buffer.from(arrayBuffer, 0, readLen);
console.info(`The content of file: ${buf.toString()}`);
fs.closeSync(file); fs.closeSync(file);
}) })
}).catch((err) => { }).catch((err: BusinessError) => {
console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
}); });
} catch (err) { } catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
} }
``` ```
...@@ -10,13 +10,13 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi ...@@ -10,13 +10,13 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi
| Module| API| Description| | Module| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| \@ohos.file.storageStatistics | getCurrentBundleStats | Obtains the storage space of the current application, in bytes.| | \@ohos.file.storageStatistics | getCurrentBundleStats | Obtains the storage space of the current application, in bytes.|
| \@ohos.file.statvfs | getFreeSize | Obtains the free space of a file system, in bytes.| | \@ohos.file.statvfs | getFreeSize | Obtains the free space of a file system, in bytes.|
| \@ohos.file.statvfs | getTotalSize | Obtains the total space of a file system, in bytes.| | \@ohos.file.statvfs | getTotalSize | Obtains the total space of a file system, in bytes.|
**Table 2** Attributes for application space statistics **Table 2** Attributes for application space statistics
| BundleStats Attribute| Description| Directory for Statistics| | BundleStats Attribute| Description| Directory for Statistics|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| appSize | Size of the application installation files, in bytes.| /data/storage/el1/bundle | | appSize | Size of the application installation files, in bytes.| /data/storage/el1/bundle |
| cacheSize | Size of the application cache files, in bytes.| /data/storage/el1/base/cache<br>/data/storage/el1/base/haps/entry/cache<br>/data/storage/el2/base/cache<br>/data/storage/el2/base/haps/entry/cache | | cacheSize | Size of the application cache files, in bytes.| /data/storage/el1/base/cache<br>/data/storage/el1/base/haps/entry/cache<br>/data/storage/el2/base/cache<br>/data/storage/el2/base/haps/entry/cache |
...@@ -25,12 +25,13 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi ...@@ -25,12 +25,13 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi
## Development Example ## Development Example
- Obtain the free space of **/data** of the file system. - Obtain the free space of **/data** of the file system.
```ts ```ts
import statvfs from '@ohos.file.statvfs'; import statvfs from '@ohos.file.statvfs';
import { BusinessError } from '@ohos.base';
let path = "/data"; let path = "/data";
statvfs.getFreeSize(path, (err, number) => { statvfs.getFreeSize(path, (err: BusinessError, number: number) => {
if (err) { if (err) {
console.error(`Invoke getFreeSize failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke getFreeSize failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -40,11 +41,12 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi ...@@ -40,11 +41,12 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi
``` ```
- Obtain the space occupied by the current application. - Obtain the space occupied by the current application.
```ts ```ts
import storageStatistics from "@ohos.file.storageStatistics"; import storageStatistics from "@ohos.file.storageStatistics";
import { BusinessError } from '@ohos.base';
storageStatistics.getCurrentBundleStats((err, bundleStats) => { storageStatistics.getCurrentBundleStats((err: BusinessError, bundleStats: storageStatistics.BundleStats) => {
if (err) { if (err) {
console.error(`Invoke getCurrentBundleStats failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke getCurrentBundleStats failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
......
...@@ -8,82 +8,89 @@ For details about the APIs used to develop a file manager application, see [User ...@@ -8,82 +8,89 @@ For details about the APIs used to develop a file manager application, see [User
## How to Develop ## How to Develop
1. Apply for permissions required.<br> 1. Apply for permissions required.
Apply for the **ohos.permission.FILE_ACCESS_MANAGER** and **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permissions. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md).
Apply for the **ohos.permission.FILE_ACCESS_MANAGER** and **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permissions. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md).
> **NOTE** > **NOTE**
> >
> **ohos.permission.FILE_ACCESS_MANAGER** allows your application to use the user file access framework APIs. > - **ohos.permission.FILE_ACCESS_MANAGER** allows your application to use the user file access framework APIs.
> >- **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** allows your application to obtain information about file management server applications supported by the system.
> **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** allows your application to obtain information about file management server applications supported by the system.
2. Import dependent modules. 2. Import dependent modules.
```ts ```ts
import fileAccess from '@ohos.file.fileAccess'; import fileAccess from '@ohos.file.fileAccess';
import fileExtensionInfo from '@ohos.file.fileExtensionInfo'; import fileExtensionInfo from '@ohos.file.fileExtensionInfo';
import { Filter } from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';
``` ```
The **fileAccess** module provides APIs for basic file operations, and the **fileExtensionInfo** module provides key structs for application development. The **fileAccess** module provides APIs for basic file operations, and the **fileExtensionInfo** module provides key structs for application development.
3. Query device information.<br> 3. Query device information.
You can obtain attributes of the devices managed by one or all file management servers in the system. You can also filter devices as required. You can obtain attributes of the devices managed by one or all file management servers in the system. You can also filter devices as required.
In the user file access framework, **RootInfo** indicates the attribute information of a device. For example, obtain **RootInfo** of all devices. In the user file access framework, **RootInfo** indicates the attribute information of a device. For example, obtain **RootInfo** of all devices.
```ts ```ts
// Obtain the application context.
let context = getContext(this) as common.UIAbilityContext;
// Create a helper object for connecting to all file management servers in the system. // Create a helper object for connecting to all file management servers in the system.
let fileAccessHelperAllServer = null; let fileAccessHelperAllServer: fileAccess.FileAccessHelper;
createFileAccessHelper() { function createFileAccessHelper() {
try { // this.context is the context passed from EntryAbility. try { // this.context is the context passed from EntryAbility.
fileAccessHelperAllServer = fileAccess.createFileAccessHelper(this.context); fileAccessHelperAllServer = fileAccess.createFileAccessHelper(context);
if (!fileAccessHelperAllServer) { if (!fileAccessHelperAllServer) {
console.error("createFileAccessHelper interface returns an undefined object"); console.error("createFileAccessHelper interface returns an undefined object");
} }
} catch (error) { } catch (err) {
let error: BusinessError = err as BusinessError;
console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message); console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message);
} }
} }
async getRoots() { let rootInfos: Array<fileAccess.RootInfo> = [];
let rootIterator = null; async function getRoots() {
let rootInfos = []; let rootIterator: fileAccess.RootIterator;
let isDone = false; let isDone: boolean = false;
try { try {
rootIterator = await fileAccessHelperAllServer.getRoots(); rootIterator = await fileAccessHelperAllServer.getRoots();
if (!rootIterator) { if (!rootIterator) {
console.error("getRoots interface returns an undefined object"); console.error("getRoots interface returns an undefined object");
return; return;
} }
while (!isDone) { while (!isDone) {
let result = rootIterator.next(); let result = rootIterator.next();
console.info("next result = " + JSON.stringify(result)); console.info("next result = " + JSON.stringify(result));
isDone = result.done; isDone = result.done;
if (!isDone) if (!isDone)
rootinfos.push(result.value); rootInfos.push(result.value);
} }
} catch (error) { } catch (err) {
let error: BusinessError = err as BusinessError;
console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message); console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message);
} }
} }
``` ```
4. View directories. 4. View directories.
In the user file access framework, **FileInfo** indicates basic information about a file (directory). You can use **listfile()** to obtain a **FileIterator** object that traverses all files (directories) of the next level or use **scanfile()** to obtain a **FileIterator** object that meets the specified conditions. In the user file access framework, **FileInfo** indicates basic information about a file (directory). You can use **listfile()** to obtain a **FileIterator** object that traverses all files (directories) of the next level or use **scanfile()** to obtain a **FileIterator** object that meets the specified conditions.
Currently, **listfile()** and **scanfile()** can be called by the **RootInfo** object to traverse the next-level files or filter the entire directory tree. In addition, **listfile()** and **scanfile()** can be called by the **FileInfo** object to traverse the next-level files or filter the specified directories. Currently, **listfile()** and **scanfile()** can be called by the **RootInfo** object to traverse the next-level files or filter the entire directory tree. In addition, **listfile()** and **scanfile()** can be called by the **FileInfo** object to traverse the next-level files or filter the specified directories.
```ts ```ts
// Start from the root directory. // Start from the root directory.
let rootInfo = rootinfos[0]; let rootInfo = rootInfos[0];
let fileInfos = []; let fileInfos: Array<fileAccess.FileInfo> = [];
let isDone = false; let isDone: boolean = false;
let filter = {suffix: [".txt", ".jpg", ".xlsx"]}; // Set filter criteria. let filter: Filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // Set the filter.
try { try {
let fileIterator = rootInfo.listFile(); // Traverse the root directory of rootinfos[0] and return an iterator object. let fileIterator = rootInfo.listFile(); // Traverse the root directory of rootinfos[0] and return an iterator object.
// let fileIterator = rootInfo.scanFile(filter); // Filter device rootinfos[0] files that meet the specified conditions and return an iteration object. // let fileIterator = rootInfo.scanFile(filter); // Filter device rootinfos[0] files that meet the specified conditions and return an iteration object.
if (!fileIterator) { if (!fileIterator) {
console.error("listFile interface returns an undefined object"); console.error("listFile interface returns an undefined object");
return;
} }
while (!isDone) { while (!isDone) {
let result = fileIterator.next(); let result = fileIterator.next();
...@@ -92,35 +99,37 @@ For details about the APIs used to develop a file manager application, see [User ...@@ -92,35 +99,37 @@ For details about the APIs used to develop a file manager application, see [User
if (!isDone) if (!isDone)
fileInfos.push(result.value); fileInfos.push(result.value);
} }
} catch (error) { } catch (err) {
let error: BusinessError = err as BusinessError;
console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message); console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
} }
// Start from the specified directory. // Start from the specified directory.
let fileInfoDir = fileInfos[0]; // fileInfoDir indicates information about a directory. let fileInfoDir = fileInfos[0]; // fileInfoDir indicates information about a directory.
let subFileInfos = []; let subFileInfos: Array<fileAccess.FileInfo> = [];
let isDone = false; let isDone02: boolean = false;
let filter = {suffix: [".txt", ".jpg", ".xlsx"]}; // Set filter criteria. let filter02: Filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // Set the filter.
try { try {
let fileIterator = fileInfoDir.listFile(); // Traverse files in the specified directory and return an iterator object. let fileIterator = fileInfoDir.listFile(); // Traverse files in the specified directory and return an iterator object.
// let fileIterator = rootInfo.scanFile(filter); // Filter the files in the specified directory and return an iterator object. // let fileIterator = rootInfo.scanFile(filter02); // Filter the files in the specified directory and return an iterator object.
if (!fileIterator) { if (!fileIterator) {
console.error("listFile interface returns an undefined object"); console.error("listFile interface returns an undefined object");
return;
} }
while (!isDone) { while (!isDone02) {
let result = fileIterator.next(); let result = fileIterator.next();
console.info("next result = " + JSON.stringify(result)); console.info("next result = " + JSON.stringify(result));
isDone = result.done; isDone02 = result.done;
if (!isDone) if (!isDone02)
subfileInfos.push(result.value); subFileInfos.push(result.value);
} }
} catch (error) { } catch (err) {
let error: BusinessError = err as BusinessError;
console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message); console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
} }
``` ```
5. Perform operations on files or directories. 5. Perform operations on files or directories.
You can integrate APIs of the user file access framework to implement user behaviors, such as deleting, renaming, creating, and moving a file (directory). The following example shows how to create a file. For details about other APIs, see [User File Access and Management](../reference/apis/js-apis-fileAccess.md). You can integrate APIs of the user file access framework to implement user behaviors, such as deleting, renaming, creating, and moving a file (directory). The following example shows how to create a file. For details about other APIs, see [User File Access and Management](../reference/apis/js-apis-fileAccess.md).
```ts ```ts
...@@ -128,18 +137,20 @@ For details about the APIs used to develop a file manager application, see [User ...@@ -128,18 +137,20 @@ For details about the APIs used to develop a file manager application, see [User
// Create a file. // Create a file.
// sourceUri is the URI in fileinfo of the Download directory. // sourceUri is the URI in fileinfo of the Download directory.
// You need to use the obtained URI for development. // You need to use the obtained URI for development.
let sourceUri = "file://media/file/6"; async function creatFile() {
let displayName = "file1"; let sourceUri: string = "file://docs/storage/Users/currentUser/Download";
let fileUri = null; let displayName: string = "file1";
try { let fileUri: string;
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. try {
fileUri = await fileAccessHelper.createFile(sourceUri, displayName); // Obtain fileAccessHelperAllServer by referring to the sample code of fileAccess.createFileAccessHelper.
if (!fileUri) { fileUri = await fileAccessHelperAllServer.createFile(sourceUri, displayName);
console.error("createFile return undefined object"); if (!fileUri) {
return; console.error("createFile return undefined object");
} }
console.info("createFile sucess, fileUri: " + JSON.stringify(fileUri)); console.info("createFile sucess, fileUri: " + JSON.stringify(fileUri));
} catch (error) { } catch (err) {
console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message); let error: BusinessError = err as BusinessError;
}; console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message);
};
}
``` ```
...@@ -8,8 +8,7 @@ For example, device A and device B are installed with the same application. Afte ...@@ -8,8 +8,7 @@ For example, device A and device B are installed with the same application. Afte
1. Connect the devices to form a Super Device. 1. Connect the devices to form a Super Device.
Connect the devices to a LAN, and complete authentication of the devices. The devices must have the same account number. Connect the devices to a LAN, and complete authentication of the devices. The devices must have the same account number.
2. Implement cross-device access to the files of the same application. 2. Implement cross-device access to the files of the same application.
Place the files in the **distributedfiles/** directory of the application sandbox to implement access from difference devices. Place the files in the **distributedfiles/** directory of the application sandbox to implement access from difference devices.
...@@ -18,11 +17,13 @@ Connect the devices to a LAN, and complete authentication of the devices. The de ...@@ -18,11 +17,13 @@ Connect the devices to a LAN, and complete authentication of the devices. The de
```ts ```ts
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
let context =...; // Obtain the UIAbilityContext information of device A. import { BusinessError } from '@ohos.base';
let pathDir = context.distributedFilesDir;
let context = getContext(this) as common.UIAbilityContext; // Obtain the UIAbilityContext of device A.
let pathDir: string = context.distributedFilesDir;
// Obtain the file path of the distributed directory. // Obtain the file path of the distributed directory.
let filePath = pathDir + '/test.txt'; let filePath: string = pathDir + '/test.txt';
try { try {
// Create a file in the distributed directory. // Create a file in the distributed directory.
...@@ -32,7 +33,8 @@ Connect the devices to a LAN, and complete authentication of the devices. The de ...@@ -32,7 +33,8 @@ Connect the devices to a LAN, and complete authentication of the devices. The de
fs.writeSync(file.fd, 'content'); fs.writeSync(file.fd, 'content');
// Close the file. // Close the file.
fs.closeSync(file.fd); fs.closeSync(file.fd);
} catch (err) { } catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`Failed to openSync / writeSync / closeSync. Code: ${err.code}, message: ${err.message}`); console.error(`Failed to openSync / writeSync / closeSync. Code: ${err.code}, message: ${err.message}`);
} }
``` ```
...@@ -41,24 +43,33 @@ Connect the devices to a LAN, and complete authentication of the devices. The de ...@@ -41,24 +43,33 @@ Connect the devices to a LAN, and complete authentication of the devices. The de
```ts ```ts
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import buffer from '@ohos.buffer';
import { BusinessError } from '@ohos.base';
let context =...; // Obtain the UIAbilityContext information of device B. let context = getContext(this) as common.UIAbilityContext; // Obtain the UIAbilityContext of device B.
let pathDir = context.distributedFilesDir; let pathDir: string = context.distributedFilesDir;
// Obtain the file path of the distributed directory. // Obtain the file path of the distributed directory.
let filePath = pathDir + '/test.txt'; let filePath: string = pathDir + '/test.txt';
try { try {
// Open the file in the distributed directory. // Open the file in the distributed directory.
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
// Set the buffer for receiving the read data. // Set the buffer for receiving the read data.
let buffer = new ArrayBuffer(4096); let arrayBuffer = new ArrayBuffer(4096);
// Read the file. The return value is the number of read bytes. // Read the file. The return value is the number of read bytes.
let num = fs.readSync(file.fd, buffer, { class Option {
offset: 0 public offset: number = 0;
}); public length: number;
}
let option = new Option();
option.length = arrayBuffer.byteLength;
let num = fs.readSync(file.fd, arrayBuffer, option);
// Print the read data. // Print the read data.
console.info('read result: ' + String.fromCharCode.apply(null, new Uint8Array(buffer.slice(0, num)))); let buf = buffer.from(arrayBuffer, 0, num);
} catch (err) { console.info('read result: ' + buf.toString());
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`Failed to openSync / readSync. Code: ${err.code}, message: ${err.message}`); console.error(`Failed to openSync / readSync. Code: ${err.code}, message: ${err.message}`);
} }
``` ```
...@@ -28,13 +28,13 @@ The following table describes the broadcast related parameters. ...@@ -28,13 +28,13 @@ The following table describes the broadcast related parameters.
**Table 1** Broadcast parameters **Table 1** Broadcast parameters
| Broadcast| Parameter| | Broadcast| Parameter|
| -------- | -------- | | -------- | -------- |
| usual.event.data.VOLUME_REMOVED | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.| | usual.event.data.VOLUME_REMOVED | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.|
| usual.event.data.VOLUME_UNMOUNTED | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.<br>**volumeState**: state of the volume.| | usual.event.data.VOLUME_UNMOUNTED | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.<br>**volumeState**: state of the volume.|
| usual.event.data.VOLUME_MOUNTED | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.<br>**volumeState**: state of the volume.<br>**fsUuid**: universally unique identifier (UUID) of the volume.<br>**path**: path where the volume is mounted.| | usual.event.data.VOLUME_MOUNTED | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.<br>**volumeState**: state of the volume.<br>**fsUuid**: universally unique identifier (UUID) of the volume.<br>**path**: path where the volume is mounted.|
| usual.event.data.VOLUME_BAD_REMOVAL | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.| | usual.event.data.VOLUME_BAD_REMOVAL | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.|
| usual.event.data.VOLUME_EJECT | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.<br>**volumeState**: state of the volume.| | usual.event.data.VOLUME_EJECT | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.<br>**volumeState**: state of the volume.|
## How to Develop ## How to Develop
...@@ -55,29 +55,33 @@ You can subscribe to broadcast events to observe the insertion and removal of ex ...@@ -55,29 +55,33 @@ You can subscribe to broadcast events to observe the insertion and removal of ex
```ts ```ts
import CommonEvent from '@ohos.commonEventManager'; import CommonEvent from '@ohos.commonEventManager';
import volumeManager from '@ohos.file.volumeManager'; import volumeManager from '@ohos.file.volumeManager';
import { BusinessError } from '@ohos.base';
const subscribeInfo = {
let subscriber: CommonEvent.CommonEventSubscriber;
async function example() {
const subscribeInfo: CommonEvent.CommonEventSubscribeInfo = {
events: [ events: [
"usual.event.data.VOLUME_REMOVED", "usual.event.data.VOLUME_REMOVED",
"usual.event.data.VOLUME_UNMOUNTED", "usual.event.data.VOLUME_UNMOUNTED",
"usual.event.data.VOLUME_MOUNTED", "usual.event.data.VOLUME_MOUNTED",
"usual.event.data.VOLUME_BAD_REMOVAL", "usual.event.data.VOLUME_BAD_REMOVAL",
"usual.event.data.VOLUME_EJECT" "usual.event.data.VOLUME_EJECT"
] ]
}; };
let subscriber = await CommonEvent.createSubscriber(subscribeInfo); subscriber = await CommonEvent.createSubscriber(subscribeInfo);
}
``` ```
3. Obtain volume information from the broadcast. 3. Obtain volume information from the broadcast.
```ts ```ts
CommonEvent.subscribe(subscriber, function (err, data) { CommonEvent.subscribe(subscriber, (err: BusinessError, data: CommonEvent.CommonEventData) => {
if (data.event === 'usual.event.data.VOLUME_MOUNTED') { if (data.event === 'usual.event.data.VOLUME_MOUNTED') {
// Manage the volume device based on the information obtained from the broadcast. // Manage the volume device based on the information obtained from the broadcast.
let volId = data.parameters.id; let volId: string = data.parameters.id;
volumeManager.getVolumeById(volId, function(error, vol) { volumeManager.getVolumeById(volId, (error: BusinessError, vol: volumeManager.Volume) => {
if (error) { if (error) {
console.error('volumeManager getVolumeById failed'); console.error('volumeManager getVolumeById failed for ' + JSON.stringify(error));
} else { } else {
console.info('volumeManager getVolumeById successfully, the volume state is ' + vol.state); console.info('volumeManager getVolumeById successfully, the volume state is ' + vol.state);
} }
......
...@@ -18,37 +18,41 @@ For example, select an image from **Gallery** and save it to the file manager. ...@@ -18,37 +18,41 @@ For example, select an image from **Gallery** and save it to the file manager.
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import photoAccessHelper from '@ohos.file.photoAccessHelper'; import photoAccessHelper from '@ohos.file.photoAccessHelper';
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
import common from '@ohos.app.ability.common';
import image from '@ohos.multimedia.image';
import { BusinessError } from '@ohos.base';
``` ```
2. Obtain the thumbnail of the first image on the device. Before performing this operation, ensure that at least one image exists on the device. 2. Obtain the thumbnail of the first image on the device. Before performing this operation, ensure that at least one image exists on the device.
```ts ```ts
const context = getContext(this); let context = getContext(this) as common.UIAbilityContext;
let photoAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
let pixelmapArrayBuffer; let pixelmapArrayBuffer: ArrayBuffer;
async getPixelmap() { async function getPixelmap() {
try { try {
let predicates = new dataSharePredicates.DataSharePredicates(); let predicates = new dataSharePredicates.DataSharePredicates();
let fetchOption = { let fetchOption: photoAccessHelper.FetchOptions = {
fetchColumns: [], fetchColumns: [],
predicates: predicates predicates: predicates
}; };
let fetchResult = await photoAccessHelper.getAssets(fetchOption); let fetchResult = await phAccessHelper.getAssets(fetchOption);
console.info('[picker] getThumbnail fetchResult: ' + fetchResult); console.info('[picker] getThumbnail fetchResult: ' + fetchResult);
const asset = await fetchResult.getFirstObject(); const asset = await fetchResult.getFirstObject();
console.info('[picker] getThumbnail asset displayName = ', asset.displayName); console.info('[picker] getThumbnail asset displayName = ', asset.displayName);
asset.getThumbnail().then((pixelMap) => { asset.getThumbnail().then((pixelMap: image.PixelMap) => {
let pixelBytesNumber = pixelMap.getPixelBytesNumber(); let pixelBytesNumber = pixelMap.getPixelBytesNumber();
const readBuffer = new ArrayBuffer(pixelBytesNumber); const readBuffer = new ArrayBuffer(pixelBytesNumber);
pixelMap.readPixelsToBuffer(readBuffer).then(() => { pixelMap.readPixelsToBuffer(readBuffer).then(() => {
pixelmapArrayBuffer = readBuffer; pixelmapArrayBuffer = readBuffer;
}) })
}).catch((err) => { }).catch((err: BusinessError) => {
console.error('[picker] getThumbnail failed with error: ' + err); console.error('[picker] getThumbnail failed with error: ' + JSON.stringify(err));
}); });
} catch (error) { } catch (error) {
console.error('[picker] getThumbnail error = ' + error); let err: BusinessError = error as BusinessError;
console.error('[picker] getThumbnail error = ' + JSON.stringify(err));
} }
} }
``` ```
...@@ -58,8 +62,8 @@ For example, select an image from **Gallery** and save it to the file manager. ...@@ -58,8 +62,8 @@ For example, select an image from **Gallery** and save it to the file manager.
The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts ```ts
let uri:string; let uris: Array<string>;
async photoViewPickerSave() { async function photoViewPickerSave() {
try { try {
const photoSaveOptions = new picker.PhotoSaveOptions(); // Create a photoSaveOptions instance. const photoSaveOptions = new picker.PhotoSaveOptions(); // Create a photoSaveOptions instance.
photoSaveOptions.newFileNames = ["PhotoViewPicker01.png"]; // (Optional) Name of the file to be saved. The file name in the square brackets can be customized and must be unique. If the file name already exists on the device, change the file name. Otherwise, an error will be returned. photoSaveOptions.newFileNames = ["PhotoViewPicker01.png"]; // (Optional) Name of the file to be saved. The file name in the square brackets can be customized and must be unique. If the file name already exists on the device, change the file name. Otherwise, an error will be returned.
...@@ -68,15 +72,16 @@ For example, select an image from **Gallery** and save it to the file manager. ...@@ -68,15 +72,16 @@ For example, select an image from **Gallery** and save it to the file manager.
try { try {
let photoSaveResult = await photoViewPicker.save(photoSaveOptions); let photoSaveResult = await photoViewPicker.save(photoSaveOptions);
if (photoSaveResult != undefined) { if (photoSaveResult != undefined) {
console.info("[picker] photoViewPickerSave photoSaveResult = " + JSON.stringify(photoSaveResult)); uris = photoSaveResult;
this.uri = photoSaveResult[0]; console.info('photoViewPicker.save to file succeed and uris are:' + uris);
console.info('photoViewPicker.save to file succeed and uri is:' + photoSaveResult[0]);
} }
} catch (err) { } catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`[picker] Invoke photoViewPicker.save failed, code is ${err.code}, message is ${err.message}`); console.error(`[picker] Invoke photoViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
} }
} catch (error) { } catch (error) {
console.info("[picker] photoViewPickerSave error = " + error); let err: BusinessError = error as BusinessError;
console.info("[picker] photoViewPickerSave error = " + JSON.stringify(err));
} }
} }
``` ```
...@@ -86,14 +91,15 @@ For example, select an image from **Gallery** and save it to the file manager. ...@@ -86,14 +91,15 @@ For example, select an image from **Gallery** and save it to the file manager.
Then, use [fs.write](../reference/apis/js-apis-file-fs.md#fswrite) to modify the file based on the FD, and close the FD after the modification is complete. Then, use [fs.write](../reference/apis/js-apis-file-fs.md#fswrite) to modify the file based on the FD, and close the FD after the modification is complete.
```ts ```ts
async writeOnly(uri) { async function writeOnly(uri: string) {
try { try {
let file = fs.openSync(uri, fs.OpenMode.WRITE_ONLY); let file = fs.openSync(uri, fs.OpenMode.WRITE_ONLY);
let writeLen = await fs.write(file.fd, pixelmapArrayBuffer); let writeLen = await fs.write(file.fd, pixelmapArrayBuffer);
fs.closeSync(file); fs.closeSync(file);
console.info("[picker] writeOnly writeLen = " + writeLen); console.info("[picker] writeOnly writeLen = " + writeLen);
} catch (error) { } catch (error) {
console.info("[picker] writeOnly error: " + error); let err: BusinessError = error as BusinessError;
console.info("[picker] writeOnly error: " + JSON.stringify(err));
} }
} }
``` ```
...@@ -105,6 +111,7 @@ For example, select an image from **Gallery** and save it to the file manager. ...@@ -105,6 +111,7 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts ```ts
import picker from '@ohos.file.picker'; import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
``` ```
2. Create a **documentSaveOptions** instance. 2. Create a **documentSaveOptions** instance.
...@@ -112,6 +119,7 @@ For example, select an image from **Gallery** and save it to the file manager. ...@@ -112,6 +119,7 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts ```ts
const documentSaveOptions = new picker.DocumentSaveOptions(); // Create a documentSaveOptions instance. const documentSaveOptions = new picker.DocumentSaveOptions(); // Create a documentSaveOptions instance.
documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; // (Optional) Set the name of the document to save. documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; // (Optional) Set the name of the document to save.
documentSaveOptions.fileSuffixChoices = ['.png', '.txt', '.mp4']; // (Optional) Types of the documents to save.
``` ```
3. Create a **documentViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-3) to open the **FilePicker** page to save the document. After the user selects the destination folder, the document is saved and the URI of the document saved is returned. 3. Create a **documentViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-3) to open the **FilePicker** page to save the document. After the user selects the destination folder, the document is saved and the URI of the document saved is returned.
...@@ -119,12 +127,12 @@ For example, select an image from **Gallery** and save it to the file manager. ...@@ -119,12 +127,12 @@ For example, select an image from **Gallery** and save it to the file manager.
The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts ```ts
let uri = null; let uris: Array<string>;
const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance. const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance.
documentViewPicker.save(documentSaveOptions).then((documentSaveResult) => { documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
uri = documentSaveResult[0]; uris = documentSaveResult;
console.info('documentViewPicker.save to file succeed and uri is:' + uri); console.info('documentViewPicker.save to file succeed and uris are:' + uris);
}).catch((err) => { }).catch((err: BusinessError) => {
console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
}) })
``` ```
...@@ -151,6 +159,7 @@ For example, select an image from **Gallery** and save it to the file manager. ...@@ -151,6 +159,7 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts ```ts
import picker from '@ohos.file.picker'; import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
``` ```
2. Create an **audioSaveOptions** instance. 2. Create an **audioSaveOptions** instance.
...@@ -160,17 +169,17 @@ For example, select an image from **Gallery** and save it to the file manager. ...@@ -160,17 +169,17 @@ For example, select an image from **Gallery** and save it to the file manager.
audioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; // (Optional) Set the name of the audio file to save. audioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; // (Optional) Set the name of the audio file to save.
``` ```
3. Create an **audioViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-6) to open the **FilePicker** page to save the file. After the user selects the destination folder, the audio file is saved and the URI of the file saved is returned. 3. Create an **audioViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-6) to open the **FilePicker** page to save the file. After the user selects the destination folder, the audio file is saved and the URI of the document saved is returned.
The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts ```ts
let uri = null; let uri: string;
const audioViewPicker = new picker.AudioViewPicker(); const audioViewPicker = new picker.AudioViewPicker();
audioViewPicker.save(audioSaveOptions).then((audioSelectResult) => { audioViewPicker.save(audioSaveOptions).then((audioSelectResult: Array<string>) => {
uri = audioSelectResult[0]; uri = audioSelectResult[0];
console.info('audioViewPicker.save to file succeed and uri is:' + uri); console.info('audioViewPicker.save to file succeed and uri is:' + uri);
}).catch((err) => { }).catch((err: BusinessError) => {
console.error(`Invoke audioViewPicker.save failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke audioViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
}) })
``` ```
...@@ -182,7 +191,7 @@ For example, select an image from **Gallery** and save it to the file manager. ...@@ -182,7 +191,7 @@ For example, select an image from **Gallery** and save it to the file manager.
console.info('file fd: ' + file.fd); console.info('file fd: ' + file.fd);
``` ```
5. Use [fs.writeSync()](../reference/apis/js-apis-file-fs.md#writesync) to edit the file based on the FD, and then close the FD. 5. Use [fs.writeSync()](../reference/apis/js-apis-file-fs.md#writesync) to edit the document based on the FD, and then close the FD.
```ts ```ts
let writeLen = fs.writeSync(file.fd, 'hello, world'); let writeLen = fs.writeSync(file.fd, 'hello, world');
......
...@@ -17,6 +17,7 @@ The **FilePicker** provides the following interfaces by file type: ...@@ -17,6 +17,7 @@ The **FilePicker** provides the following interfaces by file type:
```ts ```ts
import picker from '@ohos.file.picker'; import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
``` ```
2. Create a **photoSelectOptions** instance. 2. Create a **photoSelectOptions** instance.
...@@ -38,12 +39,12 @@ The **FilePicker** provides the following interfaces by file type: ...@@ -38,12 +39,12 @@ The **FilePicker** provides the following interfaces by file type:
The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the **PhotoSelectResult**. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the **PhotoSelectResult**. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts ```ts
let uri = null; let uris: Array<string>;
const photoViewPicker = new picker.PhotoViewPicker(); const photoViewPicker = new picker.PhotoViewPicker();
photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => { photoViewPicker.select(photoSelectOptions).then((photoSelectResult: picker.PhotoSelectResult) => {
uri = photoSelectResult.photoUris[0]; uris = photoSelectResult.photoUris;
console.info('photoViewPicker.select to file succeed and uri is:' + uri); console.info('photoViewPicker.select to file succeed and uris are:' + uris);
}).catch((err) => { }).catch((err: BusinessError) => {
console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
}) })
``` ```
...@@ -71,12 +72,17 @@ The **FilePicker** provides the following interfaces by file type: ...@@ -71,12 +72,17 @@ The **FilePicker** provides the following interfaces by file type:
```ts ```ts
import picker from '@ohos.file.picker'; import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
``` ```
2. Create a **documentSelectOptions** instance. 2. Create a **documentSelectOptions** instance.
```ts ```ts
const documentSelectOptions = new picker.DocumentSelectOptions(); const documentSelectOptions = new picker.DocumentSelectOptions();
documentSelectOptions.maxSelectNumber = 5; // (Optional) Maximum number of documents to select.
documentSelectOptions.defaultFilePathUri = "file://docs/storage/Users/currentUser/test"; // (Optional) Path of the file or directory to select.
documentSelectOptions.fileSuffixFilters = ['.png', '.txt', '.mp4']; // (Optional) File name extensions of the documents to select.
``` ```
3. Create a **documentViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-3) to open the **FilePicker** page for the user to select documents. After the documents are selected, a result set containing the file URIs is returned. 3. Create a **documentViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-3) to open the **FilePicker** page for the user to select documents. After the documents are selected, a result set containing the file URIs is returned.
...@@ -85,17 +91,13 @@ The **FilePicker** provides the following interfaces by file type: ...@@ -85,17 +91,13 @@ The **FilePicker** provides the following interfaces by file type:
For example, you can use [file management APIs](../reference/apis/js-apis-file-fs.md) to obtain file attributes, such as the file size, access time, and last modification time, based on the URI. If you need to obtain the file name, use [startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md). For example, you can use [file management APIs](../reference/apis/js-apis-file-fs.md) to obtain file attributes, such as the file size, access time, and last modification time, based on the URI. If you need to obtain the file name, use [startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md).
> **NOTE**
>
> Currently, **DocumentSelectOptions** is not configurable. By default, all types of user files are selected.
```ts ```ts
let uri = null; let uris: Array<string>;
const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance. const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance.
documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => { documentViewPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
uri = documentSelectResult[0]; uris = documentSelectResult;
console.info('documentViewPicker.select to file succeed and uri is:' + uri); console.info('documentViewPicker.select to file succeed and uris are:' + uris);
}).catch((err) => { }).catch((err: BusinessError) => {
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
}) })
``` ```
...@@ -105,24 +107,27 @@ The **FilePicker** provides the following interfaces by file type: ...@@ -105,24 +107,27 @@ The **FilePicker** provides the following interfaces by file type:
> Currently, **DocumentSelectOptions** cannot be used to obtain the file name. To obtain the file name, use **startAbilityForResult()**. > Currently, **DocumentSelectOptions** cannot be used to obtain the file name. To obtain the file name, use **startAbilityForResult()**.
```ts ```ts
let config = { async function example() {
action: 'ohos.want.action.OPEN_FILE', let config: Want = {
parameters: { action: 'ohos.want.action.OPEN_FILE',
startMode: 'choose', parameters: {
startMode: 'choose',
}
} }
} try {
try { let result = await context.startAbilityForResult(config, {windowMode: 1});
let result = await context.startAbilityForResult(config, {windowMode: 1}); if (result.resultCode !== 0) {
if (result.resultCode !== 0) { console.error(`documentViewPicker.select failed, code is ${result.resultCode}, message is ${result.want.parameters.message}`);
console.error(`documentViewPicker.select failed, code is ${result.resultCode}, message is ${result.want.parameters.message}`); return;
return; }
// Obtain the URI of the document.
let select_item_list = result.want.parameters.select_item_list;
// Obtain the name of the document.
let file_name_list = result.want.parameters.file_name_list;
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
} }
// Obtain the URI of the document.
let select_item_list = result.want.parameters.select_item_list;
// Obtain the name of the document.
let file_name_list = result.want.parameters.file_name_list;
} catch (err) {
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
} }
``` ```
...@@ -150,6 +155,7 @@ The **FilePicker** provides the following interfaces by file type: ...@@ -150,6 +155,7 @@ The **FilePicker** provides the following interfaces by file type:
```ts ```ts
import picker from '@ohos.file.picker'; import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
``` ```
2. Create an **audioSelectOptions** instance. 2. Create an **audioSelectOptions** instance.
...@@ -169,12 +175,12 @@ The **FilePicker** provides the following interfaces by file type: ...@@ -169,12 +175,12 @@ The **FilePicker** provides the following interfaces by file type:
> Currently, **AudioSelectOptions** is not configurable. By default, all types of user files are selected. > Currently, **AudioSelectOptions** is not configurable. By default, all types of user files are selected.
```ts ```ts
let uri = null; let uri: string;
const audioViewPicker = new picker.AudioViewPicker(); const audioViewPicker = new picker.AudioViewPicker();
audioViewPicker.select(audioSelectOptions).then(audioSelectResult => { audioViewPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
uri = audioSelectOptions[0]; uri = audioSelectResult[0];
console.info('audioViewPicker.select to file succeed and uri is:' + uri); console.info('audioViewPicker.select to file succeed and uri is:' + uri);
}).catch((err) => { }).catch((err: BusinessError) => {
console.error(`Invoke audioViewPicker.select failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke audioViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
}) })
``` ```
......
...@@ -13,7 +13,7 @@ For details about the APIs, see [ohos.file.securityLabel](../reference/apis/js-a ...@@ -13,7 +13,7 @@ For details about the APIs, see [ohos.file.securityLabel](../reference/apis/js-a
| setSecurityLabel | Sets a security label for a file.| Method| √ | √ | | setSecurityLabel | Sets a security label for a file.| Method| √ | √ |
| getSecurityLabel | Obtains the security label of a file.| Method| √ | √ | | getSecurityLabel | Obtains the security label of a file.| Method| √ | √ |
> **NOTE** > **NOTICE**
> >
> - In distributed networking, a device can view the files that do not match its security level but cannot access them. > - In distributed networking, a device can view the files that do not match its security level but cannot access them.
> >
...@@ -26,16 +26,18 @@ Obtain the sandbox path of a file and set the data security label. For details a ...@@ -26,16 +26,18 @@ Obtain the sandbox path of a file and set the data security label. For details a
```ts ```ts
import securityLabel from '@ohos.file.securityLabel'; import securityLabel from '@ohos.file.securityLabel';
import { BusinessError } from '@ohos.base';
import common from '@ohos.app.ability.common';
// Obtain the sandbox path of the file. // Obtain the sandbox path of the file.
let context =...; // Obtain UIAbilityContext information. let context = getContext(this) as common.UIAbilityContext; // Obtain UIAbilityContext.
let pathDir = context.filesDir; let pathDir = context.filesDir;
let filePath = pathDir + '/test.txt'; let filePath = pathDir + '/test.txt';
// Set the data level of the file to S0. // Set the data level of the file to S0.
securityLabel.setSecurityLabel(filePath, 's0').then(() => { securityLabel.setSecurityLabel(filePath, 's0').then(() => {
console.info('Succeeded in setSecurityLabeling.'); console.info('Succeeded in setSecurityLabeling.');
}).catch((err) => { }).catch((err: BusinessError) => {
console.error(`Failed to setSecurityLabel. Code: ${err.code}, message: ${err.message}`); console.error(`Failed to setSecurityLabel. Code: ${err.code}, message: ${err.message}`);
}); });
``` ```
...@@ -12,7 +12,7 @@ You can use the related APIs to [share a file with another application](#sharing ...@@ -12,7 +12,7 @@ You can use the related APIs to [share a file with another application](#sharing
The file URIs are in the following format: The file URIs are in the following format:
**file**://&lt;*bundleName*&gt;/&lt;*path*&gt; **file://**&lt;bundleName&gt;/&lt;path&gt;
- **file**: indicates a file URI. - **file**: indicates a file URI.
...@@ -30,7 +30,7 @@ Before sharing application files, you need to [obtain the application file path] ...@@ -30,7 +30,7 @@ Before sharing application files, you need to [obtain the application file path]
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import fileuri from '@ohos.file.fileuri'; import fileuri from '@ohos.file.fileuri';
import window from '@ohos.window'; import window from '@ohos.window';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
// Obtain the application sandbox path of the file. // Obtain the application sandbox path of the file.
...@@ -43,6 +43,7 @@ Before sharing application files, you need to [obtain the application file path] ...@@ -43,6 +43,7 @@ Before sharing application files, you need to [obtain the application file path]
``` ```
2. Set the target application, with which you want to share the file, and grant permissions on the file. 2. Set the target application, with which you want to share the file, and grant permissions on the file.
Use [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to share the file with the target application. You need to pass in the obtained URI in **uri** of the **want** parameter, set the type of the file to share, set **action** to **ohos.want.action.sendData**, and set the granted permission on the file in **flags**. For details, see [Want](../reference/apis/js-apis-app-ability-want.md#attributes). Use [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to share the file with the target application. You need to pass in the obtained URI in **uri** of the **want** parameter, set the type of the file to share, set **action** to **ohos.want.action.sendData**, and set the granted permission on the file in **flags**. For details, see [Want](../reference/apis/js-apis-app-ability-want.md#attributes).
> **NOTE** > **NOTE**
...@@ -51,37 +52,39 @@ Before sharing application files, you need to [obtain the application file path] ...@@ -51,37 +52,39 @@ Before sharing application files, you need to [obtain the application file path]
```ts ```ts
import fileuri from '@ohos.file.fileuri'; import fileuri from '@ohos.file.fileuri';
import window from '@ohos.window'; import window from '@ohos.window';
import wantConstant from '@ohos.app.ability.wantConstant'; import wantConstant from '@ohos.app.ability.wantConstant';
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import Want from '@ohos.app.ability.Want';
export default class EntryAbility extends UIAbility { import { BusinessError } from '@ohos.base';
onWindowStageCreate(windowStage: window.WindowStage) {
// Obtain the application sandbox path of the file. export default class EntryAbility extends UIAbility {
let filePath = this.context.filesDir + '/test.txt'; onWindowStageCreate(windowStage: window.WindowStage) {
// Convert the application sandbox path into a URI. // Obtain the application sandbox path of the file.
let uri = fileuri.getUriFromPath(filePath); let filePath = this.context.filesDir + '/test.txt';
let want = { // Convert the application sandbox path into a URI.
// Grant the read and write permissions on the shared file to the target application. let uri = fileuri.getUriFromPath(filePath);
flags: wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION | wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, let want: Want = {
// Set the implicit startup rule for the application that shares the file. // Grant the read and write permissions on the shared file to the target application.
action: 'ohos.want.action.sendData', flags: wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION | wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION,
uri: uri, // Set the implicit startup rule for the application that shares the file.
type: 'text/plain' action: 'ohos.want.action.sendData',
} uri: uri,
this.context.startAbility(want) type: 'text/plain'
.then(() => { }
console.info('Invoke getCurrentBundleStats succeeded.'); this.context.startAbility(want)
}) .then(() => {
.catch((err) => { console.info('Invoke getCurrentBundleStats succeeded.');
console.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`); })
}); .catch((err: BusinessError) => {
} console.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`);
});
... }
} // ...
}
``` ```
## Using Shared Files ## Using Shared Files
In the [**module.json5** file](../quick-start/module-configuration-file.md) of the application, which wants to use the shared file, set **actions** to **ohos.want.action.sendData** to allow the application to receive files shared by another application and set **uris** to the type of the URI to receive. In the following example, the application receives only .txt files with **scheme** of **file**. In the [**module.json5** file](../quick-start/module-configuration-file.md) of the application, which wants to use the shared file, set **actions** to **ohos.want.action.sendData** to allow the application to receive files shared by another application and set **uris** to the type of the URI to receive. In the following example, the application receives only .txt files with **scheme** of **file**.
...@@ -120,10 +123,12 @@ After obtaining the URI of the shared file from **want**, the application can ca ...@@ -120,10 +123,12 @@ After obtaining the URI of the shared file from **want**, the application can ca
```ts ```ts
// xxx.ets // xxx.ets
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
function getShareFile() { function getShareFile() {
try { try {
let want =...; // Obtain the want information sent from the application that shares the file. let want: Want = ...; // Obtain the want sent from the application that shares the file.
// Obtain the uri field from the want information. // Obtain the uri field from the want information.
let uri = want.uri; let uri = want.uri;
...@@ -135,11 +140,13 @@ function getShareFile() { ...@@ -135,11 +140,13 @@ function getShareFile() {
// Perform operations on the URI of the shared file as required. For example, open the URI to obtain the file object in read/write mode. // Perform operations on the URI of the shared file as required. For example, open the URI to obtain the file object in read/write mode.
let file = fs.openSync(uri, fs.OpenMode.READ_WRITE); let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
console.info('open file successfully!'); console.info('open file successfully!');
} catch (error) { } catch (err) {
let error: BusinessError = err as BusinessError;
console.error(`Invoke openSync failed, code is ${error.code}, message is ${error.message}`); console.error(`Invoke openSync failed, code is ${error.code}, message is ${error.message}`);
} }
} catch (error) { } catch (error) {
console.error(`Invoke openSync failed, code is ${error.code}, message is ${error.message}`); let err: BusinessError = error as BusinessError;
console.error(`Invoke openSync failed, code is ${err.code}, message is ${err.message}`);
} }
} }
``` ```
...@@ -8,9 +8,11 @@ OpenHarmony provides multiple classes for you to develop audio playback applicat ...@@ -8,9 +8,11 @@ OpenHarmony provides multiple classes for you to develop audio playback applicat
- [AudioRenderer](using-audiorenderer-for-playback.md): provides ArkTS and JS API to implement audio output. It supports only the PCM format and requires applications to continuously write audio data. The applications can perform data preprocessing, for example, setting the sampling rate and bit width of audio files, before audio input. This class can be used to develop more professional and diverse playback applications. To use this class, you must have basic audio processing knowledge. - [AudioRenderer](using-audiorenderer-for-playback.md): provides ArkTS and JS API to implement audio output. It supports only the PCM format and requires applications to continuously write audio data. The applications can perform data preprocessing, for example, setting the sampling rate and bit width of audio files, before audio input. This class can be used to develop more professional and diverse playback applications. To use this class, you must have basic audio processing knowledge.
- [OpenSL ES](using-opensl-es-for-playback.md): provides a set of standard, cross-platform, yet unique native audio APIs. It supports audio output in PCM format and is applicable to playback applications that are ported from other embedded platforms or that implements audio output at the native layer. - [OpenSL ES](using-opensl-es-for-playback.md): provides a set of standard, cross-platform native audio APIs. It supports audio output in PCM format and is suitable for playback applications that are ported from other embedded platforms or that implement audio output at the native layer.
- [TonePlayer](using-toneplayer-for-playback.md): provides ArkTS and JS API to implement the playback of dialing tones and ringback tones. It can be used to play the content selected from a fixed type range, without requiring the input of media assets or audio data. This class is application to specific scenarios where dialing tones and ringback tones are played. is available only to system applications. - [Using OHAudio for Audio Playback](using-ohaudio-for-playback.md): provides a set of native APIs for audio output. These APIs are normalized in design and support both common and low-latency audio channels. They are suitable for playback applications that implement audio output at the native layer.
- [TonePlayer](using-toneplayer-for-playback.md): provides ArkTS and JS APIs to implement the playback of dialing tones and ringback tones. It can be used to play the content selected from a fixed type range, without requiring the input of media assets or audio data. This class is applicable to specific scenarios where dialing tones and ringback tones are played. It is available only to system applications.
- Applications often need to use short sound effects, such as camera shutter sound effect, key press sound effect, and game shooting sound effect. Currently, only the **AVPlayer** class can implement audio file playback. More APIs will be provided to support this scenario in later versions. - Applications often need to use short sound effects, such as camera shutter sound effect, key press sound effect, and game shooting sound effect. Currently, only the **AVPlayer** class can implement audio file playback. More APIs will be provided to support this scenario in later versions.
......
...@@ -8,7 +8,9 @@ OpenHarmony provides multiple classes for you to develop audio recording applica ...@@ -8,7 +8,9 @@ OpenHarmony provides multiple classes for you to develop audio recording applica
- [AudioCapturer](using-audiocapturer-for-recording.md): provides ArkTS and JS API to implement audio input. It supports only the PCM format and requires applications to continuously read audio data. The application can perform data processing after audio output. This class can be used to develop more professional and diverse recording applications. To use this class, you must have basic audio processing knowledge. - [AudioCapturer](using-audiocapturer-for-recording.md): provides ArkTS and JS API to implement audio input. It supports only the PCM format and requires applications to continuously read audio data. The application can perform data processing after audio output. This class can be used to develop more professional and diverse recording applications. To use this class, you must have basic audio processing knowledge.
- [OpenSL ES](using-opensl-es-for-recording.md): provides a set of standard, cross-platform, yet unique native audio APIs. It supports audio input in PCM format and is applicable to recording applications that are ported from other embedded platforms or that implements audio input at the native layer. - [OpenSL ES](using-opensl-es-for-recording.md): provides a set of standard, cross-platform native audio APIs. It supports audio input in PCM format and is suitable for recording applications that are ported from other embedded platforms or that implement audio input at the native layer.
- [Using OHAudio for Audio Recording](using-ohaudio-for-recording.md): provides a set of native APIs for audio input. These APIs are normalized in design and support both common and low-latency audio channels. They are suitable for playback applications that implement audio input at the native layer.
## Precautions for Developing Audio Recording Applications ## Precautions for Developing Audio Recording Applications
......
...@@ -40,7 +40,7 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/ ...@@ -40,7 +40,7 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/
Scenario 1: Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object for starting a UIAbility component. Scenario 1: Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object for starting a UIAbility component.
```typescript ```typescript
let wantAgentObj:WantAgent = null; // Save the WantAgent object created. It will be used to complete the trigger operations. let wantAgentObj:WantAgent; // Save the WantAgent object created. It will be used to complete the trigger operations.
// Set the action type through operationType of WantAgentInfo. // Set the action type through operationType of WantAgentInfo.
let wantAgentInfo:wantAgent.WantAgentInfo = { let wantAgentInfo:wantAgent.WantAgentInfo = {
...@@ -64,7 +64,7 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/ ...@@ -64,7 +64,7 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/
Scenario 2: Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object for publishing a [common event](../application-models/common-event-overview.md). Scenario 2: Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object for publishing a [common event](../application-models/common-event-overview.md).
```typescript ```typescript
let wantAgentObj:WantAgent = null; // Save the WantAgent object created. It will be used to complete the trigger operations. let wantAgentObj:WantAgent; // Save the WantAgent object created. It will be used to complete the trigger operations.
// Set the action type through operationType of WantAgentInfo. // Set the action type through operationType of WantAgentInfo.
let wantAgentInfo:wantAgent.WantAgentInfo = { let wantAgentInfo:wantAgent.WantAgentInfo = {
......
...@@ -241,7 +241,7 @@ The **abilities** tag represents the UIAbility configuration of the module, whic ...@@ -241,7 +241,7 @@ The **abilities** tag represents the UIAbility configuration of the module, whic
| label | Name of the UIAbility component displayed to users. The value is a string resource index.| String| Yes (initial value: left empty)<br>If **UIAbility** is set to **MainElement**, this attribute is mandatory.| | label | Name of the UIAbility component displayed to users. The value is a string resource index.| String| Yes (initial value: left empty)<br>If **UIAbility** is set to **MainElement**, this attribute is mandatory.|
| permissions | Permissions required for another application to access the UIAbility component.<br>The value is generally in the reverse domain name notation and contains a maximum of 255 bytes. It is an array of predefined permission names.| String array| Yes (initial value: left empty)| | permissions | Permissions required for another application to access the UIAbility component.<br>The value is generally in the reverse domain name notation and contains a maximum of 255 bytes. It is an array of predefined permission names.| String array| Yes (initial value: left empty)|
| [metadata](#metadata)| Metadata information of the UIAbility component.| Object array| Yes (initial value: left empty)| | [metadata](#metadata)| Metadata information of the UIAbility component.| Object array| Yes (initial value: left empty)|
| exported | Whether the UIAbility component can be called by other applications.<br>- **true**: The UIAbility component can be called by other applications.<br>- **false**: The UIAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)| | exported | Whether the UIAbility component can be called by other applications.<br>- **true**: The UIAbility component can be called by other applications.<br>- **false**: The ExtensionAbility component cannot be called by other applications, not even by aa commands.| Boolean| Yes (initial value: **false**)|
| continuable | Whether the UIAbility component can be [migrated](../application-models/hop-cross-device-migration.md).<br>- **true**: The UIAbility component can be migrated.<br>- **false**: The UIAbility component cannot be migrated.| Boolean| Yes (initial value: **false**)| | continuable | Whether the UIAbility component can be [migrated](../application-models/hop-cross-device-migration.md).<br>- **true**: The UIAbility component can be migrated.<br>- **false**: The UIAbility component cannot be migrated.| Boolean| Yes (initial value: **false**)|
| [skills](#skills) | Feature set of [wants](../application-models/want-overview.md) that can be received by the current UIAbility or ExtensionAbility component.<br>Configuration rules:<br>- For HAPs of the entry type, you can configure multiple **skills** attributes with the entry capability for an OpenHarmony application. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.)<br>- For HAPs of the feature type, you can configure **skills** attributes with the entry capability for an OpenHarmony application, but not for an OpenHarmony service.| Object array| Yes (initial value: left empty)| | [skills](#skills) | Feature set of [wants](../application-models/want-overview.md) that can be received by the current UIAbility or ExtensionAbility component.<br>Configuration rules:<br>- For HAPs of the entry type, you can configure multiple **skills** attributes with the entry capability for an OpenHarmony application. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.)<br>- For HAPs of the feature type, you can configure **skills** attributes with the entry capability for an OpenHarmony application, but not for an OpenHarmony service.| Object array| Yes (initial value: left empty)|
| backgroundModes | Continuous tasks of the UIAbility component. <br>Continuous tasks are classified into the following types:<br>- **dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices.<br>- **audioPlayback**: audio playback service.<br>- **audioRecording**: audio recording service.<br>- **location**: location and navigation services.<br>- **bluetoothInteraction**: Bluetooth scanning, connection, and transmission services (wearables).<br>- **multiDeviceConnection**: multi-device interconnection service.<br>- **wifiInteraction**: Wi-Fi scanning, connection, and transmission services (as used in the Multi-screen Collaboration and clone features)<br>- **voip**: voice/video call and VoIP services.<br>- **taskKeeping**: computing service.| String array| Yes (initial value: left empty)| | backgroundModes | Continuous tasks of the UIAbility component. <br>Continuous tasks are classified into the following types:<br>- **dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices.<br>- **audioPlayback**: audio playback service.<br>- **audioRecording**: audio recording service.<br>- **location**: location and navigation services.<br>- **bluetoothInteraction**: Bluetooth scanning, connection, and transmission services (wearables).<br>- **multiDeviceConnection**: multi-device interconnection service.<br>- **wifiInteraction**: Wi-Fi scanning, connection, and transmission services (as used in the Multi-screen Collaboration and clone features)<br>- **voip**: voice/video call and VoIP services.<br>- **taskKeeping**: computing service.| String array| Yes (initial value: left empty)|
...@@ -382,7 +382,7 @@ The **extensionAbilities** tag represents the configuration of extensionAbilitie ...@@ -382,7 +382,7 @@ The **extensionAbilities** tag represents the configuration of extensionAbilitie
| uri | Data URI provided by the ExtensionAbility component. The value is a string with a maximum of 255 bytes, in the reverse domain name notation.<br>**NOTE**<br>This attribute is mandatory when the type of the ExtensionAbility component is set to **dataShare**.| String| Yes (initial value: left empty)| | uri | Data URI provided by the ExtensionAbility component. The value is a string with a maximum of 255 bytes, in the reverse domain name notation.<br>**NOTE**<br>This attribute is mandatory when the type of the ExtensionAbility component is set to **dataShare**.| String| Yes (initial value: left empty)|
|skills | Feature set of [wants](../application-models/want-overview.md) that can be received by the ExtensionAbility component.<br>Configuration rule: In an entry package, you can configure multiple **skills** attributes with the entry capability. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.) The **label** and **icon** in the first ExtensionAbility that has **skills** configured are used as the **label** and **icon** of the entire OpenHarmony service/application.<br>**NOTE**<br>The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application, but not for an OpenHarmony service.| Array| Yes (initial value: left empty)| |skills | Feature set of [wants](../application-models/want-overview.md) that can be received by the ExtensionAbility component.<br>Configuration rule: In an entry package, you can configure multiple **skills** attributes with the entry capability. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.) The **label** and **icon** in the first ExtensionAbility that has **skills** configured are used as the **label** and **icon** of the entire OpenHarmony service/application.<br>**NOTE**<br>The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application, but not for an OpenHarmony service.| Array| Yes (initial value: left empty)|
| [metadata](#metadata)| Metadata of the ExtensionAbility component.| Object| Yes (initial value: left empty)| | [metadata](#metadata)| Metadata of the ExtensionAbility component.| Object| Yes (initial value: left empty)|
| exported | Whether the ExtensionAbility component can be called by other applications. <br>- **true**: The ExtensionAbility component can be called by other applications.<br>- **false**: The ExtensionAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)| | exported | Whether the ExtensionAbility component can be called by other applications. <br>- **true**: The ExtensionAbility component can be called by other applications.<br>- **false**: The ExtensionAbility component cannot be called by other applications, not even by aa commands.| Boolean| Yes (initial value: **false**)|
Example of the **extensionAbilities** structure: Example of the **extensionAbilities** structure:
......
...@@ -97,7 +97,7 @@ Example of the **module** tag structure: ...@@ -97,7 +97,7 @@ Example of the **module** tag structure:
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| moduleName | Name of the HAP file. The maximum length is 31 bytes. During application upgrade, this name can be changed. If it is changed, migration of module-related directories is required for the application. You can use the [file operation API](../reference/apis/js-apis-file-fs.md#fscopydir10) for migration.| String| No| | moduleName | Name of the HAP file. The maximum length is 31 bytes. This name can be changed during application update. However, if it is changed, you need to adapt the application to the migration of module-related directories. You can use the [file operation API](../reference/apis/js-apis-file-fs.md#fscopydir10) for this purpose.| String| No|
| moduleType | Type of the HAP file, which can **entry**, **feature**, or **har**.| String| No| | moduleType | Type of the HAP file, which can **entry**, **feature**, or **har**.| String| No|
| installationFree | Whether the HAP file supports the installation-free feature. **true**: The HAP file supports the installation-free feature and meets installation-free constraints. **false**: The HAP file does not support the installation-free feature. If this tag is set to **true** for an entry-type HAP file (**entry.hap**), it must also be set to **true** for feature-type HAP files (**feature.hap**) of the same application. If this tag is set to **false** for an entry-type HAP file, it can be set to **true** or **false** for feature-type modules of the same application based on service requirements.| Boolean| No| | installationFree | Whether the HAP file supports the installation-free feature. **true**: The HAP file supports the installation-free feature and meets installation-free constraints. **false**: The HAP file does not support the installation-free feature. If this tag is set to **true** for an entry-type HAP file (**entry.hap**), it must also be set to **true** for feature-type HAP files (**feature.hap**) of the same application. If this tag is set to **false** for an entry-type HAP file, it can be set to **true** or **false** for feature-type modules of the same application based on service requirements.| Boolean| No|
| deliveryWithInstall | Whether the HAP file will be installed when the user installs the application. **true**: The HAP file will be installed when the user installs the application. **false**: The HAP file will not be installed when the user installs the application.| Boolean| No| | deliveryWithInstall | Whether the HAP file will be installed when the user installs the application. **true**: The HAP file will be installed when the user installs the application. **false**: The HAP file will not be installed when the user installs the application.| Boolean| No|
...@@ -203,7 +203,7 @@ Example of the metadata attribute: ...@@ -203,7 +203,7 @@ Example of the metadata attribute:
| label | Ability name displayed to users. The value can be a name string or a resource index to names in multiple languages, for example, **$string:ability_label**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.<br>**NOTE**<br>The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 bytes.| String| Yes (initial value: left empty)| | label | Ability name displayed to users. The value can be a name string or a resource index to names in multiple languages, for example, **$string:ability_label**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.<br>**NOTE**<br>The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 bytes.| String| Yes (initial value: left empty)|
| uri | Uniform Resource Identifier (URI) of the ability. The value can contain a maximum of 255 bytes.| String| Yes (No for abilities using the Data template)| | uri | Uniform Resource Identifier (URI) of the ability. The value can contain a maximum of 255 bytes.| String| Yes (No for abilities using the Data template)|
| launchType | Launch type of the ability. The value can be **standard** or **singleton**.<br>**standard**: Multiple **Ability** instances can be created during startup. Most abilities can use this type.<br>**singleton**: Only a single **Ability** instance can be created across all task stacks during startup. For example, a globally unique incoming call screen uses the singleton launch type. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String| Yes (initial value: **"singleton"**)| | launchType | Launch type of the ability. The value can be **standard** or **singleton**.<br>**standard**: Multiple **Ability** instances can be created during startup. Most abilities can use this type.<br>**singleton**: Only a single **Ability** instance can be created across all task stacks during startup. For example, a globally unique incoming call screen uses the singleton launch type. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String| Yes (initial value: **"singleton"**)|
| visible | Whether the ability can be called by other applications.<br>**true**: The ability can be called by other applications.<br>**false**: The ability cannot be called by other applications.| Boolean| Yes (initial value: **false**)| | visible | Whether the ability can be called by other applications.<br>**true**: The ability can be called by other applications.<br>**false**: The ability cannot be called by other applications, not even by aa commands.| Boolean| Yes (initial value: **false**)|
| permissions | Permissions required for abilities of another application to call the current ability. The value is an array of permission names predefined by the system, generally in the reverse domain name notation. It contains a maximum of 255 bytes.| String array| Yes (initial value: left empty)| | permissions | Permissions required for abilities of another application to call the current ability. The value is an array of permission names predefined by the system, generally in the reverse domain name notation. It contains a maximum of 255 bytes.| String array| Yes (initial value: left empty)|
|skills | Types of the **want** that can be accepted by the ability.| Object array| Yes (initial value: left empty)| |skills | Types of the **want** that can be accepted by the ability.| Object array| Yes (initial value: left empty)|
| deviceCapability | Device capabilities required to run the ability. The value is an array of up to 512 elements, each of which contains a maximum of 64 bytes.| String array| Yes (initial value: left empty)| | deviceCapability | Device capabilities required to run the ability. The value is an array of up to 512 elements, each of which contains a maximum of 64 bytes.| String array| Yes (initial value: left empty)|
......
...@@ -57,7 +57,7 @@ You can debug HAP files using the methods: ...@@ -57,7 +57,7 @@ You can debug HAP files using the methods:
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.
## Deployment ## Deployment
The application market on the cloud distributes the applications to application market clients. These applications can contain one or more HAP files. After the user selects an application to download, the application market downloads all the HAP files contained in this application. The application market on the cloud distributes the applications to application market clients. These applications can contain one or more HAP files. After the user selects an application to download, the application market downloads all the HAP files contained in this application whose **deliveryWithInstall** field is set to **true**.
## Installation on a Device ## Installation on a Device
After the download is complete, the application market client calls the installation API of the bundle manager service in the system to install the downloaded HAP files. The bundle manager service deploys HAP files by application in the specified directory to complete the application installation. After the download is complete, the application market client calls the installation API of the bundle manager service in the system to install the downloaded HAP files. The bundle manager service deploys HAP files by application in the specified directory to complete the application installation.
...@@ -35,7 +35,7 @@ Along its evolution, OpenHarmony has provided two application models: ...@@ -35,7 +35,7 @@ Along its evolution, OpenHarmony has provided two application models:
For details about the differences between the FA model and stage model, see [Interpretation of the Application Model](../application-models/application-model-description.md). For details about the differences between the FA model and stage model, see [Interpretation of the Application Model](../application-models/application-model-description.md).
To help you better understand the preceding basic concepts and application development process, **Getting Started** provides a development example that contains two pages in different programming languages and application models. To help you better understand the preceding basic concepts and application development process, **Getting Started** walks you through an example of building the first ArkTS application with two pages in the stage model.
## Tool Preparation ## Tool Preparation
......
...@@ -280,7 +280,8 @@ ...@@ -280,7 +280,8 @@
- [@ohos.data.distributedKVStore (Distributed KV Store)](js-apis-distributedKVStore.md) - [@ohos.data.distributedKVStore (Distributed KV Store)](js-apis-distributedKVStore.md)
- [@ohos.data.preferences (User Preferences)](js-apis-data-preferences.md) - [@ohos.data.preferences (User Preferences)](js-apis-data-preferences.md)
- [@ohos.data.relationalStore (RDB Store)](js-apis-data-relationalStore.md) - [@ohos.data.relationalStore (RDB Store)](js-apis-data-relationalStore.md)
- [@ohos.data.UDMF (Unfied Data Management Framework)](js-apis-data-udmf.md) - [@ohos.data.unifiedDataChannel (Unified Data Channel)](js-apis-data-unifiedDataChannel.md)
- [@ohos.data.uniformTypeDescriptor (Standard Data Definition)](js-apis-data-uniformTypeDescriptor.md)
- [@ohos.data.ValuesBucket (Value Bucket)](js-apis-data-valuesBucket.md) - [@ohos.data.ValuesBucket (Value Bucket)](js-apis-data-valuesBucket.md)
- File Management - File Management
......
# @ohos.WallpaperExtensionAbility (WallpaperExtensionAbility) # @ohos.WallpaperExtensionAbility (WallpaperExtensionAbility)
The **WallpaperExtensionAbility** module provides APIs for developing wallpaper extension abilities and managing the lifecycle of these extension abilities. The **WallpaperExtensionAbility** module provides lifecycle callbacks for wallpaper extension abilities and APIs for listening for wallpaper changes.
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> >
> The APIs of this module can be used only in the FA model. > The APIs of this module can be used only in the stage model.
> >
> The APIs provided by this module are system APIs. > The APIs provided by this module are system APIs.
......
...@@ -4,9 +4,9 @@ The **DataShareResultSet** module provides APIs for accessing the result set obt ...@@ -4,9 +4,9 @@ The **DataShareResultSet** module provides APIs for accessing the result set obt
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> >
> The APIs provided by this module are system APIs. > - The APIs provided by this module are system APIs.
## Modules to Import ## Modules to Import
...@@ -22,8 +22,9 @@ You can call [query()](js-apis-data-dataShare.md#query) to obtain the **DataShar ...@@ -22,8 +22,9 @@ You can call [query()](js-apis-data-dataShare.md#query) to obtain the **DataShar
```ts ```ts
import dataShare from '@ohos.data.dataShare'; import dataShare from '@ohos.data.dataShare';
import dataSharePredicates from '@ohos.data.dataSharePredicates' import dataSharePredicates from '@ohos.data.dataSharePredicates'
import { BusinessError } from '@ohos.base'
let dataShareHelper; let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare"); let uri = ("datashare:///com.samples.datasharetest.DataShare");
await dataShare.createDataShareHelper(this.context, uri, (err, data) => { await dataShare.createDataShareHelper(this.context, uri, (err, data) => {
if (err != undefined) { if (err != undefined) {
...@@ -36,12 +37,12 @@ await dataShare.createDataShareHelper(this.context, uri, (err, data) => { ...@@ -36,12 +37,12 @@ await dataShare.createDataShareHelper(this.context, uri, (err, data) => {
let columns = ["*"]; let columns = ["*"];
let da = new dataSharePredicates.DataSharePredicates(); let da = new dataSharePredicates.DataSharePredicates();
let resultSet; let resultSet: DataShareResultSet;
da.equalTo("name", "ZhangSan"); da.equalTo("name", "ZhangSan");
dataShareHelper.query(uri, da, columns).then((data) => { dataShareHelper.query(uri, da, columns).then((data: DataShareResultSet) => {
console.info("query end, data : " + data); console.info("query end, data : " + data);
resultSet = data; resultSet = data;
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("query fail, error message : " + err); console.error("query fail, error message : " + err);
}); });
``` ```
......
# @ohos.data.uniformTypeDescriptor (Standard Data Definition)
The **uniformTypeDescriptor** module provides abstract definitions of OpenHarmony standardized data types.
> **NOTE**
>
> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```js
import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
```
## UniformDataType
Enumerates the types of OpenHarmony standard data.
**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
| Name | Value | Description |
|----------------------------|------------------------------|-----------|
| TEXT | 'general.text' | Text. |
| PLAIN_TEXT | 'general.plain-text' | Plaintext. |
| HYPERLINK | 'general.hyperlink' | Hyperlink. |
| HTML | 'general.html' | HyperText Markup Language (HTML). |
| FILE | 'general.file' | File. |
| IMAGE | 'general.image' | Image. |
| VIDEO | 'general.video' | Video. |
| AUDIO | 'general.audio' | Audio. |
| FOLDER | 'general.folder' | Folder. |
| OPENHARMONY_FORM | 'openharmony.form' | Widget. |
| OPENHARMONY_APP_ITEM | 'openharmony.app-item' | Icon. |
| OPENHARMONY_PIXEL_MAP | 'openharmony.pixel-map' | Pixel map. |
...@@ -146,7 +146,7 @@ Disables listening for global mouse events. ...@@ -146,7 +146,7 @@ Disables listening for global mouse events.
```js ```js
// Disable listening for a single callback. // Disable listening for a single callback.
function callback(mouseEvent) { let callback = (mouseEvent: MouseEvent) => {
console.log(`Monitor on success ${JSON.stringify(mouseEvent)}`); console.log(`Monitor on success ${JSON.stringify(mouseEvent)}`);
return false; return false;
}; };
......
...@@ -525,7 +525,7 @@ import tag from '@ohos.nfc.tag'; ...@@ -525,7 +525,7 @@ import tag from '@ohos.nfc.tag';
let elementName = null; let elementName = null;
let discTech = [tag.NFC_A, tag.NFC_B]; // replace with the tech(s) that is needed by foreground ability let discTech = [tag.NFC_A, tag.NFC_B]; // replace with the tech(s) that is needed by foreground ability
function foregroundCb(err, taginfo) { function foregroundCb(err, tagInfo) {
if (!err) { if (!err) {
console.log("foreground callback: tag found tagInfo = ", JSON.stringify(tagInfo)); console.log("foreground callback: tag found tagInfo = ", JSON.stringify(tagInfo));
} else { } else {
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册