提交 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
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_天气应用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
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-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-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-bundle-AbilityInfo.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
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-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-process.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
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 @
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-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-screenshot.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers
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
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-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-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-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
......@@ -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-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-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-touchevent.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
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-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-bundleManager-abilityInfo.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
......@@ -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.
```ts
import deviceManager from '@ohos.distributedHardware.deviceManager';
import deviceManager from '@ohos.distributedDeviceManager';
let dmClass;
let dmClass: deviceManager.DeviceManager;
function initDmClass() {
// createDeviceManager is a system API.
deviceManager.createDeviceManager('ohos.samples.demo', (err, dm) => {
if (err) {
...
return
try{
dmClass = deviceManager.createDeviceManager('ohos.samples.demo');
} catch(err) {
console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
}
dmClass = dm
})
}
function getRemoteDeviceId() {
if (typeof dmClass === 'object' && dmClass !== null) {
let list = dmClass.getTrustedDeviceListSync()
let list = dmClass.getAvailableDeviceListSync();
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 list[0].deviceId
return list[0].networkId;
} 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
let want = {
deviceId: getRemoteDeviceId(),
bundleName: 'com.example.myapplication',
abilityName: 'FuncAbility',
moduleName: 'module1', // moduleName is optional.
abilityName: 'EntryAbility',
moduleName: 'entry', // moduleName is optional.
}
// context is the AbilityContext of the initiator UIAbility.
this.context.startAbility(want).then(() => {
......@@ -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).
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.
- 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
```ts
const MSG_SEND_METHOD: string = 'CallSendMsg';
originMsg: string = '';
backMsg: string = '';
let originMsg: string = '';
let backMsg: string = '';
async onButtonCallWithResult(originMsg, backMsg) {
try {
let msg = new MyParcelable(1, originMsg);
......
......@@ -20,12 +20,15 @@ In OpenHarmony, distributed operations across devices are called continuation (a
- **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
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
......@@ -39,9 +42,9 @@ The following figure shows the continuation architecture.
![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.
......
......@@ -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).|
| 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) |
| 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.|
| 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) |
| 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) |
| 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) |
| 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) |
......@@ -8,18 +8,19 @@ The PageAbility component in the FA model corresponds to the UIAbility component
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.
| 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.|
| 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.|
| 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.|
| 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.|
| NA | onWindowStageDestroy(): void | This method is available only in the stage model. The callback is invoked when a window is destroyed.|
| PageAbility| UIAbility| Mapping Description|
| -------- | -------- | -------- |
| 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.|
| 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.|
| 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.|
| 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.|
| onDestroy(): void | onDestroy(): void | The two methods have the same meaning, invoking time, and parameters.|
![pageability-switch](figures/pageability-switch.png)
......@@ -31,7 +32,6 @@ The PageAbility lifecycle is basically the same as the UIAbility lifecycle. The
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
"pages" : [
"pages/Index"
......@@ -40,7 +40,6 @@ The PageAbility lifecycle is basically the same as the UIAbility lifecycle. The
In the stage model, implement the following method in **MainAbility**:
```ts
import Window from '@ohos.window'
......
# 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
......@@ -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.
- Application icon: an application entry icon, 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).
- 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 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.
- Widget page: widget UI module, which contains display and interaction information such as components, layouts, and events.
- FormExtensionAbility: a widget service logic module, which provides lifecycle callbacks invoked when a widget is created, destroyed, or updated.
- 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)
......@@ -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.
## 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).
......@@ -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.
| Category| JS widget| ArkTS widget|
| Category| JS Widget| ArkTS Widget|
| -------- | -------- | -------- |
| Development paradigm| Web-like paradigm| Declarative paradigm|
| Component capability| Supported| Supported|
......
......@@ -350,8 +350,8 @@ The window mode is specified by the **windowMode** field in the [StartOptions](.
> **NOTE**
>
> 1. 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.
> - If the **windowMode** field is not specified, the UIAbility is started in the default window mode.
> - 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.
......@@ -521,7 +521,7 @@ The development procedure is as follows:
funcAbilityWant: Want;
uiContext: UIContext;
onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam) {
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) {
if (want?.parameters?.router && want.parameters.router === 'funcA') {
let funcAUrl = 'pages/Second';
let router: Router = this.uiContext.getRouter();
......@@ -624,6 +624,7 @@ For the CalleeAbility, implement the callback to receive data and the methods to
```
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.
......@@ -631,7 +632,6 @@ For the CalleeAbility, implement the callback to receive data and the methods to
export default class MyParcelable {
num: number = 0;
str: string = '';
constructor(num, string) {
this.num = num;
this.str = string;
......
......@@ -30,9 +30,9 @@ 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).
| API | Description |
|--------------------------------------------------------------------------------------------------|------------------------------------------------------------|
| getPreferences(context: Context, name: string, callback: AsyncCallback&lt;Preferences&gt;): void | Obtain a **Preferences** instance. |
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| 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. |
| 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. |
......@@ -40,7 +40,7 @@ The following table lists the APIs used for persisting user preference data. For
| 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. |
| 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
......@@ -58,11 +58,13 @@ The following table lists the APIs used for persisting user preference data. For
```js
import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base';
import window from '@ohos.window';
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
onWindowStageCreate(windowStage: window.WindowStage) {
try {
dataPreferences.getPreferences(this.context, 'mystore', (err, preferences) => {
dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: dataPreferences.Preferences) => {
if (err) {
console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
return;
......@@ -82,12 +84,13 @@ The following table lists the APIs used for persisting user preference data. For
```js
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base';
// Obtain the context.
let context = featureAbility.getContext();
try {
dataPreferences.getPreferences(context, 'mystore', (err, preferences) => {
dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: dataPreferences.Preferences) => {
if (err) {
console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
return;
......@@ -102,7 +105,7 @@ The following table lists the APIs used for persisting user preference data. For
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**
>
......@@ -157,7 +160,7 @@ The following table lists the APIs used for persisting user preference data. For
```js
try {
preferences.flush((err) => {
preferences.flush((err: BusinessError) => {
if (err) {
console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
return;
......@@ -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:
```js
let observer = function (key) {
console.info('The key' + key + 'changed.');
interface observer {
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'.
preferences.put('startup', 'manual', (err) => {
preferences.put('startup', 'manual', (err: BusinessError) => {
if (err) {
console.error(`Failed to put the value of 'startup'. Code:${err.code},message:${err.message}`);
return;
}
console.info("Succeeded in putting the value of 'startup'.");
preferences.flush((err) => {
preferences.flush((err: BusinessError) => {
if (err) {
console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
return;
......@@ -210,7 +215,7 @@ The following table lists the APIs used for persisting user preference data. For
```js
try {
dataPreferences.deletePreferences(this.context, 'mystore', (err, val) => {
dataPreferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => {
if (err) {
console.error(`Failed to delete preferences. Code:${err.code}, message:${err.message}`);
return;
......
......@@ -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:
- 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.
......@@ -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.
- The manual synchronization is available only for system applications.
## Available APIs
......@@ -247,24 +245,21 @@ The following uses a single KV store as an example to describe how to implement
> **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
import deviceManager from '@ohos.distributedHardware.deviceManager';
import deviceManager from '@ohos.distributedDeviceManager';
let devManager;
try {
// create deviceManager
deviceManager.createDeviceManager('bundleName', (err, value) => {
if (!err) {
devManager = value;
// deviceIds is obtained by devManager.getTrustedDeviceListSync.
devManager = deviceManager.createDeviceManager(context.applicationInfo.name);
// deviceIds is obtained by devManager.getAvailableDeviceListSync.
let deviceIds = [];
if (devManager !== null) {
// The ohos.permission.ACCESS_SERVICE_DM permission is required. This permission is available only for system applications.
let devices = devManager.getTrustedDeviceListSync();
if (devManager != null) {
let devices = devManager.getAvailableDeviceListSync();
for (let i = 0; i < devices.length; i++) {
deviceIds[i] = devices[i].deviceId;
deviceIds[i] = devices[i].networkId;
}
}
try {
......@@ -273,6 +268,8 @@ The following uses a single KV store as an example to describe how to implement
} 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
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
......@@ -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.
- Third-party applications cannot call the distributed APIs that must be specified with the device.
## 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|
| -------- | -------- |
......@@ -73,7 +78,7 @@ The following table lists the APIs for cross-device data synchronization of RDB
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).
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,20 +147,19 @@ The following table lists the APIs for cross-device data synchronization of RDB
> **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
// Obtain device IDs.
import deviceManager from '@ohos.distributedHardware.deviceManager';
import deviceManager from '@ohos.distributedDeviceManager';
let dmInstance = null;
let deviceId = null;
deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => {
if (err) {
console.info(`Failed to create device manager. Code:${err.code},message:${err.message}`);
return;
}
let devices = manager.getTrustedDeviceListSync();
let deviceId = devices[0].deviceId;
try {
dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify");
let devices = dmInstance.getAvailableDeviceListSync();
deviceId = devices[0].networkId;
// Construct a predicate object for querying the distributed table.
let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
......@@ -169,5 +173,7 @@ The following table lists the APIs for cross-device data synchronization of RDB
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,13 +57,14 @@ 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**.
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.
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.
```js
import Extension from '@ohos.application.DataShareExtensionAbility';
import rdb from '@ohos.data.relationalStore';
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.
......@@ -75,20 +76,20 @@ override the service implementation as required. For example, if the data provid
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)';
let rdbStore;
let result;
let rdbStore: relationalStore.RdbStore;
let result: string;
export default class DataShareExtAbility extends Extension {
private rdbStore_;
private rdbStore_: relationalStore.RdbStore;
// Override onCreate().
onCreate(want, callback) {
onCreate(want: Want, callback: Function) {
result = this.context.cacheDir + '/datashare.txt';
// Create an RDB store.
rdb.getRdbStore(this.context, {
name: DB_NAME,
securityLevel: rdb.SecurityLevel.S1
}, function (err, data) {
}, (err, data) => {
rdbStore = data;
rdbStore.executeSql(DDL_TBL_CREATE, [], (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
}
// Override query().
query(uri, predicates, columns, callback) {
query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: Function) {
if (predicates === null || predicates === undefined) {
console.info('invalid predicates');
}
......@@ -188,6 +189,8 @@ override the service implementation as required. For example, if the data provid
import UIAbility from '@ohos.app.ability.UIAbility';
import dataShare from '@ohos.data.dataShare';
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.
......@@ -200,11 +203,11 @@ override the service implementation as required. For example, if the data provid
3. Create a **DataShareHelper** instance.
```js
let dsHelper;
let abilityContext;
let dsHelper: dataShare.DataShareHelper;
let abilityContext: Context;
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
onWindowStageCreate(windowStage: window.WindowStage) {
abilityContext = this.context;
dataShare.createDataShareHelper(abilityContext, dseUri, (err, data) => {
dsHelper = data;
......@@ -217,8 +220,19 @@ override the service implementation as required. For example, if the data provid
```js
// Construct a piece of data.
let valuesBucket = { 'name': 'ZhangSan', 'age': 21, 'isStudent': false, 'Binary': new Uint8Array([1, 2, 3]) };
let updateBucket = { 'name': 'LiSi', 'age': 18, 'isStudent': true, 'Binary': new Uint8Array([1, 2, 3]) };
let key1 = 'name';
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 valArray = ['*'];
// Insert a piece of data.
......@@ -238,4 +252,3 @@ override the service implementation as required. For example, if the data provid
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
## 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 |
|-----------------------------------------------------------------------------------------|---------------------------------------------|
......@@ -45,75 +45,81 @@ The following example describes how to implement many-to-many data sharing. The
### Data Provider
1. Import the **@ohos.data.UDMF** module.
1. Import the **@ohos.data.unifiedDataChannel** and **@ohos.data.uniformTypeDescriptor** modules.
```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.
```ts
let plainText = new UDMF.PlainText();
import { BusinessError } from '@ohos.base';
let plainText = new unifiedDataChannel.PlainText();
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.
let options = {
intention: UDMF.Intention.DATA_HUB
let options: unifiedDataChannel.Options = {
intention: unifiedDataChannel.Intention.DATA_HUB
}
try {
UDMF.insertData(options, unifiedData, (err, data) => {
unifiedDataChannel.insertData(options, unifiedData, (err, data) => {
if (err === undefined) {
console.info(`Succeeded in inserting data. key = ${data}`);
} else {
console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `);
}
});
} catch(e) {
console.error(`Insert data throws an exception. code is ${e.code},message is ${e.message} `);
} catch (e) {
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.
```ts
let plainText = new UDMF.PlainText();
import { BusinessError } from '@ohos.base';
let plainText = new unifiedDataChannel.PlainText();
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.
let options = {
let options: unifiedDataChannel.Options = {
key: 'udmf://DataHub/com.ohos.test/0123456789'
};
try {
UDMF.updateData(options, unifiedData, (err) => {
unifiedDataChannel.updateData(options, unifiedData, (err) => {
if (err === undefined) {
console.info('Succeeded in updating data.');
} else {
console.error(`Failed to update data. code is ${err.code},message is ${err.message} `);
}
});
} catch(e) {
console.error(`Update data throws an exception. code is ${e.code},message is ${e.message} `);
} catch (e) {
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.
```ts
import { BusinessError } from '@ohos.base';
// Specify the type of the data channel whose data is to be deleted.
let options = {
intention: UDMF.Intention.DATA_HUB
let options: unifiedDataChannel.Options = {
intention: unifiedDataChannel.Intention.DATA_HUB
};
try {
UDMF.deleteData(options, (err, data) => {
unifiedDataChannel.deleteData(options, (err, data) => {
if (err === undefined) {
console.info(`Succeeded in deleting data. size = ${data.length}`);
for (let i = 0; i < data.length; i++) {
let records = data[i].getRecords();
for (let j = 0; j < records.length; j++) {
if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) {
let text = <UDMF.PlainText>(records[j]);
if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) {
let text = records[j] as unifiedDataChannel.PlainText;
console.info(`${i + 1}.${text.textContent}`);
}
}
......@@ -122,35 +128,38 @@ The following example describes how to implement many-to-many data sharing. The
console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `);
}
});
} catch(e) {
console.error(`Delete data throws an exception. code is ${e.code},message is ${e.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
1. Import the **@ohos.data.UDMF** module.
1. Import the **@ohos.data.unifiedDataChannel** and **@ohos.data.uniformTypeDescriptor** modules.
```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.
```ts
import { BusinessError } from '@ohos.base';
// Specify the type of the data channel whose data is to be queried.
let options = {
intention: UDMF.Intention.DATA_HUB
let options: unifiedDataChannel.Options = {
intention: unifiedDataChannel.Intention.DATA_HUB
};
try {
UDMF.queryData(options, (err, data) => {
unifiedDataChannel.queryData(options, (err, data) => {
if (err === undefined) {
console.info(`Succeeded in querying data. size = ${data.length}`);
for (let i = 0; i < data.length; i++) {
let records = data[i].getRecords();
for (let j = 0; j < records.length; j++) {
if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) {
let text = <UDMF.PlainText>(records[j]);
if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) {
let text = records[j] as unifiedDataChannel.PlainText;
console.info(`${i + 1}.${text.textContent}`);
}
}
......@@ -160,6 +169,7 @@ The following example describes how to implement many-to-many data sharing. The
}
});
} 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 @@
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
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
![UDMF_FILE](figures/udmf_type_File.png)
Figure 2 UDMF Text
**Figure 2** UDMF Text
![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
![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
......@@ -39,9 +46,9 @@ Figure 2 UDMF Text
## 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 |
|---------------|-------------------|-----------------------------------------------------------------------------------------------|
......@@ -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.
1. Import the **@ohos.data.UDMF** module.
1. Import the **@ohos.data.unifiedDataChannel** and **@ohos.data.uniformTypeDescriptor** modules.
```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.
(1) Create an image data record.
```ts
let image = new UDMF.Image();
let image = new unifiedDataChannel.Image();
```
(2) Modify object attributes.
......@@ -84,12 +93,13 @@ The following describes how to create a **UnifiedData** object containing two da
(4) Create a **UnifiedData** instance.
```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.
```ts
let plainText = new UDMF.PlainText();
let plainText = new unifiedDataChannel.PlainText();
plainText.textContent = 'this is textContent of plainText';
plainText.abstract = 'abstract of plainText';
plainText.details = {
......@@ -98,11 +108,13 @@ The following describes how to create a **UnifiedData** object containing two da
};
unifiedData.addRecord(plainText);
```
4. Obtain all data records in this **UnifiedData** instance.
```ts
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.
```ts
......@@ -110,13 +122,13 @@ The following describes how to create a **UnifiedData** object containing two da
// Read the type of the data record.
let type = records[i].getType();
switch (type) {
case UDMF.UnifiedDataType.IMAGE:
case uniformTypeDescriptor.UniformDataType.IMAGE:
// Convert the data to obtain the original image data record.
let image = <UDMF.Image>(records[i]);
let image = records[i] as unifiedDataChannel.Image;
break;
case UDMF.UnifiedDataType.PLAIN_TEXT:
case uniformTypeDescriptor.UniformDataType.PLAIN_TEXT:
// Convert the data to obtain the original text record.
let plainText = <UDMF.PlainText>(records[i]);
let plainText = records[i] as unifiedDataChannel.PlainText;
break;
default:
break;
......
......@@ -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).
Then, perform common file operations.
Then, perform file operations.
### Creating, Reading, and Writing a File
......@@ -46,21 +46,29 @@ The following example demonstrates how to create a file, read data from it, and
// pages/xxx.ets
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import buffer from '@ohos.buffer';
function createFile() {
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
function createFile() {
// Create a file and open it.
let file = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
// Write data to the file.
let writeLen = fs.writeSync(file.fd, "Try to write str.");
console.info("The length of str is: " + writeLen);
// Read data from the file.
let buf = new ArrayBuffer(1024);
let readLen = fs.readSync(file.fd, buf, { offset: 0 });
console.info("the content of file: " + String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen))));
let arrayBuffer = new ArrayBuffer(1024);
class Option {
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.
fs.closeSync(file);
}
......@@ -75,11 +83,11 @@ function createFile() {
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
function readWriteFile() {
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
function readWriteFile() {
// Open the source and destination files.
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);
......@@ -87,11 +95,18 @@ function readWriteFile() {
let bufSize = 4096;
let readSize = 0;
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) {
readSize += readLen;
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.
fs.closeSync(srcFile);
......@@ -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 common from '@ohos.app.ability.common';
async function readWriteFileWithStream() {
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
async function readWriteFileWithStream() {
// Open the file streams.
let inputStream = fs.createStreamSync(filesDir + '/test.txt', 'r+');
let outputStream = fs.createStreamSync(filesDir + '/destFile.txt', "w+");
......@@ -124,11 +139,18 @@ async function readWriteFileWithStream() {
let bufSize = 4096;
let readSize = 0;
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;
while (readLen > 0) {
await outputStream.write(buf);
readLen = await inputStream.read(buf, { offset: readSize });
option.offset = readSize;
readLen = await inputStream.read(buf, option);
readSize += readLen;
}
// Close the streams.
......@@ -148,8 +170,7 @@ async function readWriteFileWithStream() {
The following example demonstrates how to list files that meet the specified conditions.
```ts
// List files.
import fs from '@ohos.file.fs';
import fs, { Filter } from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
// Obtain the application file path.
......@@ -157,18 +178,20 @@ let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// List files that meet the specified conditions.
let options = {
recursion: false,
listNum: 0,
filter: {
suffix: ['.png', '.jpg', '.txt'], // The filename extension can be '.png', '.jpg', or '.txt'.
displayName: ['test%'], // The filename starts with 'test'.
fileSizeOver: 0, // The file size is greater than or equal to 0.
lastModifiedAfter: new Date(0).getTime(), // The latest modification time of the file is later than January 1, 1970.
},
}
let files = fs.listFileSync(filesDir, options);
for (let i = 0; i < files.length; i++) {
function getListFile() {
class ListFileOption {
public recursion: boolean = false;
public listNum: number = 0;
public filter: Filter
}
let option = new ListFileOption();
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.
option.filter.lastModifiedAfter = new Date(0).getTime(); // The latest modification time of the file is later than January 1, 1970.
let files = fs.listFileSync(filesDir, option);
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,
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';
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
async function getLocalCapabilities() {
try {
let fileData = await backup.getLocalCapabilities();
console.info('getLocalCapabilities success');
let fpath = await globalThis.context.filesDir + '/localCapabilities.json';
let fpath = filesDir + '/localCapabilities.json';
fs.copyFileSync(fileData.fd, fpath);
fs.closeSync(fileData.fd);
} catch (err) {
console.error('getLocalCapabilities failed with err: ' + err);
} catch (error) {
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.
**Example**
```ts
import backup from '@ohos.file.backup';
import common from '@ohos.app.ability.common';
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.
let g_session;
let g_session: backup.SessionBackup;
function createSessionBackup() {
let sessionBackup = new backup.SessionBackup({
onFileReady: async (err, file) => {
let generalCallbacks: backup.GeneralCallbacks = {
onFileReady: (err: BusinessError, file: backup.File) => {
if (err) {
console.info('onFileReady err: ' + err);
console.info('onFileReady err: ' + JSON.stringify(err));
}
try {
let bundlePath = await globalThis.context.filesDir + '/' + file.bundleName;
let bundlePath = filesDir + '/' + file.bundleName;
if (!fs.accessSync(bundlePath)) {
fs.mkdirSync(bundlePath);
}
......@@ -109,23 +124,23 @@ You can save the file to a local directory as required.
console.error('onFileReady failed with err: ' + e);
}
},
onBundleBegin: (err, bundleName) => {
onBundleBegin: (err: BusinessError, bundleName: string) => {
if (err) {
console.info('onBundleBegin err: ' + err);
console.info('onBundleBegin err: ' + JSON.stringify(err));
} else {
console.info('onBundleBegin bundleName: ' + bundleName);
}
},
onBundleEnd: (err, bundleName) => {
onBundleEnd: (err: BusinessError, bundleName: string) => {
if (err) {
console.info('onBundleEnd err: ' + err);
console.info('onBundleEnd err: ' + JSON.stringify(err));
} else {
console.info('onBundleEnd bundleName: ' + bundleName);
}
},
onAllBundlesEnd: (err) => {
onAllBundlesEnd: (err: BusinessError) => {
if (err) {
console.info('onAllBundlesEnd err: ' + err);
console.info('onAllBundlesEnd err: ' + JSON.stringify(err));
} else {
console.info('onAllBundlesEnd');
}
......@@ -133,16 +148,16 @@ You can save the file to a local directory as required.
onBackupServiceDied: () => {
console.info('onBackupServiceDied');
},
});
}
let sessionBackup = new backup.SessionBackup(generalCallbacks);
return sessionBackup;
}
async function sessionBackup ()
{
async function sessionBackup () {
g_session = createSessionBackup();
// 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.
const backupApps = [
const backupApps: string[] = [
"com.example.hiworld",
]
await g_session.appendBundles(backupApps);
......@@ -161,24 +176,26 @@ When all the data of the application is ready, the service starts to restore the
**Example**
```ts
import backup from '@ohos.file.backup';
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
// Create a SessionRestore instance for data restoration.
let g_session;
async function publishFile(file)
{
await g_session.publishFile({
let g_session: backup.SessionRestore;
async function publishFile(file: backup.File) {
let fileMeta: backup.FileMeta = {
bundleName: file.bundleName,
uri: file.uri
});
}
await g_session.publishFile(fileMeta);
}
function createSessionRestore() {
let sessionRestore = new backup.SessionRestore({
onFileReady: (err, file) => {
let generalCallbacks: backup.GeneralCallbacks = {
onFileReady: (err: BusinessError, file: backup.File) => {
if (err) {
console.info('onFileReady err: ' + err);
console.info('onFileReady err: ' + JSON.stringify(err));
}
// Set bundlePath based on the actual situation.
let bundlePath;
let bundlePath: string;
if (!fs.accessSync(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
publishFile(file);
console.info('onFileReady success');
},
onBundleBegin: (err, bundleName) => {
onBundleBegin: (err: BusinessError, bundleName: string) => {
if (err) {
console.error('onBundleBegin failed with err: ' + err);
console.error('onBundleBegin failed with err: ' + JSON.stringify(err));
}
console.info('onBundleBegin success');
},
onBundleEnd: (err, bundleName) => {
onBundleEnd: (err: BusinessError, bundleName: string) => {
if (err) {
console.error('onBundleEnd failed with err: ' + err);
console.error('onBundleEnd failed with err: ' + JSON.stringify(err));
}
console.info('onBundleEnd success');
},
onAllBundlesEnd: (err) => {
onAllBundlesEnd: (err: BusinessError) => {
if (err) {
console.error('onAllBundlesEnd failed with err: ' + err);
console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err));
}
console.info('onAllBundlesEnd success');
},
onBackupServiceDied: () => {
console.info('service died');
}
});
}
let sessionRestore = new backup.SessionRestore(generalCallbacks);
return sessionRestore;
}
async function restore ()
{
async function restore01 () {
g_session = createSessionRestore();
const backupApps = [
const restoreApps: string[] = [
"com.example.hiworld",
]
// You can obtain the capability file based on actual situation. The following is an example only.
// You can also construct capability files as required.
let fileData = await backup.getLocalCapabilities();
await g_session.appendBundles(fileData.fd, backupApps);
await g_session.appendBundles(fileData.fd, restoreApps);
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.
// 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],
uri: "manage.json"
});
await g_session.getFileHandle({
bundleName: restoreApps[0],
uri: "1.tar"
});
}
await g_session.getFileHandle(handle);
handle.uri = "1.tar";
await g_session.getFileHandle(handle);
console.info('getFileHandle success');
}
```
......@@ -249,23 +265,30 @@ If the application has not been installed, you can install the application and t
**Example**
```ts
import backup from '@ohos.file.backup';
import common from '@ohos.app.ability.common';
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.
let g_session;
async function publishFile(file)
{
await g_session.publishFile({
let g_session: backup.SessionRestore;
async function publishFile(file: backup.File) {
let fileMeta: backup.FileMeta = {
bundleName: file.bundleName,
uri: file.uri
});
}
await g_session.publishFile(fileMeta);
}
function createSessionRestore() {
let sessionRestore = new backup.SessionRestore({
onFileReady: (err, file) => {
let generalCallbacks: backup.GeneralCallbacks = {
onFileReady: (err: BusinessError, file: backup.File) => {
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" )
{
// 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
publishFile(file);
console.info('onFileReady success');
},
onBundleBegin: (err, bundleName) => {
onBundleBegin: (err: BusinessError, bundleName: string) => {
if (err) {
console.error('onBundleBegin failed with err: ' + err);
console.error('onBundleBegin failed with err: ' + JSON.stringify(err));
}
console.info('onBundleBegin success');
},
onBundleEnd: (err, bundleName) => {
onBundleEnd: (err: BusinessError, bundleName: string) => {
if (err) {
console.error('onBundleEnd failed with err: ' + err);
console.error('onBundleEnd failed with err: ' + JSON.stringify(err));
}
console.info('onBundleEnd success');
},
onAllBundlesEnd: (err) => {
onAllBundlesEnd: (err: BusinessError) => {
if (err) {
console.error('onAllBundlesEnd failed with err: ' + err);
console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err));
}
console.info('onAllBundlesEnd success');
},
onBackupServiceDied: () => {
console.info('service died');
}
});
}
let sessionRestore = new backup.SessionRestore(generalCallbacks);
return sessionRestore;
}
async function restore ()
{
async function restore02 () {
g_session = createSessionRestore();
const backupApps = [
const restoreApps: string[] = [
"com.example.hiworld",
]
let fpath = await globalThis.context.filesDir + '/localCapabilities.json';
let file = fs.openSync(fpath, fileIO.OpenMode.CREATE | fileIO.OpenMode.READ_WRITE);
let fpath = filesDir + '/localCapabilities.json';
let file = fs.openSync(fpath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
let content = "{\"bundleInfos\" :[{\"allToBackup\" : false,\"extensionName\" : \"\"," +
"\"name\" : \"cn.openharmony.inputmethodchoosedialog\",\"needToInstall\" : true,\"spaceOccupied\" : 0," +
"\"versionCode\" : 1000000,\"versionName\" : \"1.0.0\"}],\"deviceType\" : \"default\",\"systemFullName\" : \"OpenHarmony-4.0.6.2(Canary1)\"}";
fs.writeSync(file.fd, content);
fs.fsyncSync(file.fd);
await g_session.appendBundles(file.fd, backupApps);
await g_session.appendBundles(file.fd, restoreApps);
console.info('appendBundles success');
// Obtain the file handle of the application to be installed.
await g_session.getFileHandle({
let handle: backup.FileMeta = {
bundleName: restoreApps[0],
uri: "/data/storage/el2/restore/bundle.hap"
});
await g_session.getFileHandle({
bundleName: restoreApps[0],
uri: "manage.json"
});
await g_session.getFileHandle({
bundleName: restoreApps[0],
uri: "1.tar"
});
}
await g_session.getFileHandle(handle);
handle.uri = "manage.json";
await g_session.getFileHandle(handle);
handle.uri = "1.tar";
await g_session.getFileHandle(handle);
console.info('getFileHandle success');
}
```
......
......@@ -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 fs from '@ohos.file.fs';
import request from '@ohos.request';
import { BusinessError } from '@ohos.base';
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
......@@ -30,32 +31,36 @@ fs.writeSync(file.fd, 'upload file test');
fs.closeSync(file);
// 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',
header: { key1: 'value1', key2: 'value2' },
header: header,
method: 'POST',
files: [
{ filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' }
],
data: [
{ name: 'name', value: 'value' }
]
files: files,
data: data
}
// Upload the created application file to the network server.
try {
request.uploadFile(context, uploadConfig)
.then((uploadTask) => {
uploadTask.on('complete', (taskStates) => {
.then((uploadTask: request.UploadTask) => {
uploadTask.on('complete', (taskStates: Array<request.TaskState>) => {
for (let i = 0; i < taskStates.length; 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}`);
})
} catch (err) {
} catch (error) {
let err: BusinessError = error as BusinessError;
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
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
import request from '@ohos.request';
import { BusinessError } from '@ohos.base';
import buffer from '@ohos.buffer';
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
......@@ -87,19 +94,21 @@ try {
request.downloadFile(context, {
url: 'https://xxxx/xxxx.txt',
filePath: filesDir + '/xxxx.txt'
}).then((downloadTask) => {
}).then((downloadTask: request.DownloadTask) => {
downloadTask.on('complete', () => {
console.info('download complete');
let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE);
let buf = new ArrayBuffer(1024);
let readLen = fs.readSync(file.fd, buf);
console.info(`The content of file: ${String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))}`);
let arrayBuffer = new ArrayBuffer(1024);
let readLen = fs.readSync(file.fd, arrayBuffer);
let buf = buffer.from(arrayBuffer, 0, readLen);
console.info(`The content of file: ${buf.toString()}`);
fs.closeSync(file);
})
}).catch((err) => {
}).catch((err: BusinessError) => {
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}`);
}
```
......@@ -28,9 +28,10 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi
```ts
import statvfs from '@ohos.file.statvfs';
import { BusinessError } from '@ohos.base';
let path = "/data";
statvfs.getFreeSize(path, (err, number) => {
statvfs.getFreeSize(path, (err: BusinessError, number: number) => {
if (err) {
console.error(`Invoke getFreeSize failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -43,8 +44,9 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi
```ts
import storageStatistics from "@ohos.file.storageStatistics";
import { BusinessError } from '@ohos.base';
storageStatistics.getCurrentBundleStats((err, bundleStats) => {
storageStatistics.getCurrentBundleStats((err: BusinessError, bundleStats: storageStatistics.BundleStats) => {
if (err) {
console.error(`Invoke getCurrentBundleStats failed, code is ${err.code}, message is ${err.message}`);
} else {
......
......@@ -8,46 +8,52 @@ For details about the APIs used to develop a file manager application, see [User
## How to Develop
1. Apply for permissions required.<br>
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).
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).
> **NOTE**
>
> **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.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.
2. Import dependent modules.
```ts
import fileAccess from '@ohos.file.fileAccess';
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.
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.
In the user file access framework, **RootInfo** indicates the attribute information of a device. For example, obtain **RootInfo** of all devices.
```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.
let fileAccessHelperAllServer = null;
createFileAccessHelper() {
let fileAccessHelperAllServer: fileAccess.FileAccessHelper;
function createFileAccessHelper() {
try { // this.context is the context passed from EntryAbility.
fileAccessHelperAllServer = fileAccess.createFileAccessHelper(this.context);
fileAccessHelperAllServer = fileAccess.createFileAccessHelper(context);
if (!fileAccessHelperAllServer) {
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);
}
}
async getRoots() {
let rootIterator = null;
let rootInfos = [];
let isDone = false;
let rootInfos: Array<fileAccess.RootInfo> = [];
async function getRoots() {
let rootIterator: fileAccess.RootIterator;
let isDone: boolean = false;
try {
rootIterator = await fileAccessHelperAllServer.getRoots();
if (!rootIterator) {
......@@ -59,31 +65,32 @@ For details about the APIs used to develop a file manager application, see [User
console.info("next result = " + JSON.stringify(result));
isDone = result.done;
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);
}
}
```
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.
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
// Start from the root directory.
let rootInfo = rootinfos[0];
let fileInfos = [];
let isDone = false;
let filter = {suffix: [".txt", ".jpg", ".xlsx"]}; // Set filter criteria.
let rootInfo = rootInfos[0];
let fileInfos: Array<fileAccess.FileInfo> = [];
let isDone: boolean = false;
let filter: Filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // Set the filter.
try {
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.
if (!fileIterator) {
console.error("listFile interface returns an undefined object");
return;
}
while (!isDone) {
let result = fileIterator.next();
......@@ -92,35 +99,37 @@ For details about the APIs used to develop a file manager application, see [User
if (!isDone)
fileInfos.push(result.value);
}
} catch (error) {
} catch (err) {
let error: BusinessError = err as BusinessError;
console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
}
// Start from the specified directory.
let fileInfoDir = fileInfos[0]; // fileInfoDir indicates information about a directory.
let subFileInfos = [];
let isDone = false;
let filter = {suffix: [".txt", ".jpg", ".xlsx"]}; // Set filter criteria.
let subFileInfos: Array<fileAccess.FileInfo> = [];
let isDone02: boolean = false;
let filter02: Filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // Set the filter.
try {
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) {
console.error("listFile interface returns an undefined object");
return;
}
while (!isDone) {
while (!isDone02) {
let result = fileIterator.next();
console.info("next result = " + JSON.stringify(result));
isDone = result.done;
if (!isDone)
subfileInfos.push(result.value);
isDone02 = result.done;
if (!isDone02)
subFileInfos.push(result.value);
}
} catch (error) {
} catch (err) {
let error: BusinessError = err as BusinessError;
console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
}
```
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).
```ts
......@@ -128,18 +137,20 @@ For details about the APIs used to develop a file manager application, see [User
// Create a file.
// sourceUri is the URI in fileinfo of the Download directory.
// You need to use the obtained URI for development.
let sourceUri = "file://media/file/6";
let displayName = "file1";
let fileUri = null;
async function creatFile() {
let sourceUri: string = "file://docs/storage/Users/currentUser/Download";
let displayName: string = "file1";
let fileUri: string;
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
fileUri = await fileAccessHelper.createFile(sourceUri, displayName);
// Obtain fileAccessHelperAllServer by referring to the sample code of fileAccess.createFileAccessHelper.
fileUri = await fileAccessHelperAllServer.createFile(sourceUri, displayName);
if (!fileUri) {
console.error("createFile return undefined object");
return;
}
console.info("createFile sucess, fileUri: " + JSON.stringify(fileUri));
} catch (error) {
} catch (err) {
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
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.
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
```ts
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';
let context =...; // Obtain the UIAbilityContext information of device A.
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.
let filePath = pathDir + '/test.txt';
let filePath: string = pathDir + '/test.txt';
try {
// 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
fs.writeSync(file.fd, 'content');
// Close the file.
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}`);
}
```
......@@ -41,24 +43,33 @@ Connect the devices to a LAN, and complete authentication of the devices. The de
```ts
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 pathDir = context.distributedFilesDir;
let context = getContext(this) as common.UIAbilityContext; // Obtain the UIAbilityContext of device B.
let pathDir: string = context.distributedFilesDir;
// Obtain the file path of the distributed directory.
let filePath = pathDir + '/test.txt';
let filePath: string = pathDir + '/test.txt';
try {
// Open the file in the distributed directory.
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
// 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.
let num = fs.readSync(file.fd, buffer, {
offset: 0
});
class Option {
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.
console.info('read result: ' + String.fromCharCode.apply(null, new Uint8Array(buffer.slice(0, num))));
} catch (err) {
let buf = buffer.from(arrayBuffer, 0, num);
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}`);
}
```
......@@ -55,8 +55,11 @@ You can subscribe to broadcast events to observe the insertion and removal of ex
```ts
import CommonEvent from '@ohos.commonEventManager';
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: [
"usual.event.data.VOLUME_REMOVED",
"usual.event.data.VOLUME_UNMOUNTED",
......@@ -65,19 +68,20 @@ You can subscribe to broadcast events to observe the insertion and removal of ex
"usual.event.data.VOLUME_EJECT"
]
};
let subscriber = await CommonEvent.createSubscriber(subscribeInfo);
subscriber = await CommonEvent.createSubscriber(subscribeInfo);
}
```
3. Obtain volume information from the broadcast.
```ts
CommonEvent.subscribe(subscriber, function (err, data) {
CommonEvent.subscribe(subscriber, (err: BusinessError, data: CommonEvent.CommonEventData) => {
if (data.event === 'usual.event.data.VOLUME_MOUNTED') {
// Manage the volume device based on the information obtained from the broadcast.
let volId = data.parameters.id;
volumeManager.getVolumeById(volId, function(error, vol) {
let volId: string = data.parameters.id;
volumeManager.getVolumeById(volId, (error: BusinessError, vol: volumeManager.Volume) => {
if (error) {
console.error('volumeManager getVolumeById failed');
console.error('volumeManager getVolumeById failed for ' + JSON.stringify(error));
} else {
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.
import fs from '@ohos.file.fs';
import photoAccessHelper from '@ohos.file.photoAccessHelper';
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.
```ts
const context = getContext(this);
let photoAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
let context = getContext(this) as common.UIAbilityContext;
let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
let pixelmapArrayBuffer;
async getPixelmap() {
let pixelmapArrayBuffer: ArrayBuffer;
async function getPixelmap() {
try {
let predicates = new dataSharePredicates.DataSharePredicates();
let fetchOption = {
let fetchOption: photoAccessHelper.FetchOptions = {
fetchColumns: [],
predicates: predicates
};
let fetchResult = await photoAccessHelper.getAssets(fetchOption);
let fetchResult = await phAccessHelper.getAssets(fetchOption);
console.info('[picker] getThumbnail fetchResult: ' + fetchResult);
const asset = await fetchResult.getFirstObject();
console.info('[picker] getThumbnail asset displayName = ', asset.displayName);
asset.getThumbnail().then((pixelMap) => {
asset.getThumbnail().then((pixelMap: image.PixelMap) => {
let pixelBytesNumber = pixelMap.getPixelBytesNumber();
const readBuffer = new ArrayBuffer(pixelBytesNumber);
pixelMap.readPixelsToBuffer(readBuffer).then(() => {
pixelmapArrayBuffer = readBuffer;
})
}).catch((err) => {
console.error('[picker] getThumbnail failed with error: ' + err);
}).catch((err: BusinessError) => {
console.error('[picker] getThumbnail failed with error: ' + JSON.stringify(err));
});
} 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.
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
let uri:string;
async photoViewPickerSave() {
let uris: Array<string>;
async function photoViewPickerSave() {
try {
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.
......@@ -68,15 +72,16 @@ For example, select an image from **Gallery** and save it to the file manager.
try {
let photoSaveResult = await photoViewPicker.save(photoSaveOptions);
if (photoSaveResult != undefined) {
console.info("[picker] photoViewPickerSave photoSaveResult = " + JSON.stringify(photoSaveResult));
this.uri = photoSaveResult[0];
console.info('photoViewPicker.save to file succeed and uri is:' + photoSaveResult[0]);
uris = photoSaveResult;
console.info('photoViewPicker.save to file succeed and uris are:' + uris);
}
} 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}`);
}
} 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.
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
async writeOnly(uri) {
async function writeOnly(uri: string) {
try {
let file = fs.openSync(uri, fs.OpenMode.WRITE_ONLY);
let writeLen = await fs.write(file.fd, pixelmapArrayBuffer);
fs.closeSync(file);
console.info("[picker] writeOnly writeLen = " + writeLen);
} 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.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
```
2. Create a **documentSaveOptions** instance.
......@@ -112,6 +119,7 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts
const documentSaveOptions = new picker.DocumentSaveOptions(); // Create a documentSaveOptions instance.
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.
......@@ -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.
```ts
let uri = null;
let uris: Array<string>;
const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance.
documentViewPicker.save(documentSaveOptions).then((documentSaveResult) => {
uri = documentSaveResult[0];
console.info('documentViewPicker.save to file succeed and uri is:' + uri);
}).catch((err) => {
documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
uris = documentSaveResult;
console.info('documentViewPicker.save to file succeed and uris are:' + uris);
}).catch((err: BusinessError) => {
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.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
```
2. Create an **audioSaveOptions** instance.
......@@ -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.
```
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.
```ts
let uri = null;
let uri: string;
const audioViewPicker = new picker.AudioViewPicker();
audioViewPicker.save(audioSaveOptions).then((audioSelectResult) => {
audioViewPicker.save(audioSaveOptions).then((audioSelectResult: Array<string>) => {
uri = audioSelectResult[0];
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}`);
})
```
......@@ -182,7 +191,7 @@ For example, select an image from **Gallery** and save it to the file manager.
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
let writeLen = fs.writeSync(file.fd, 'hello, world');
......
......@@ -17,6 +17,7 @@ The **FilePicker** provides the following interfaces by file type:
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
```
2. Create a **photoSelectOptions** instance.
......@@ -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.
```ts
let uri = null;
let uris: Array<string>;
const photoViewPicker = new picker.PhotoViewPicker();
photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => {
uri = photoSelectResult.photoUris[0];
console.info('photoViewPicker.select to file succeed and uri is:' + uri);
}).catch((err) => {
photoViewPicker.select(photoSelectOptions).then((photoSelectResult: picker.PhotoSelectResult) => {
uris = photoSelectResult.photoUris;
console.info('photoViewPicker.select to file succeed and uris are:' + uris);
}).catch((err: BusinessError) => {
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:
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
```
2. Create a **documentSelectOptions** instance.
```ts
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.
......@@ -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).
> **NOTE**
>
> Currently, **DocumentSelectOptions** is not configurable. By default, all types of user files are selected.
```ts
let uri = null;
let uris: Array<string>;
const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance.
documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => {
uri = documentSelectResult[0];
console.info('documentViewPicker.select to file succeed and uri is:' + uri);
}).catch((err) => {
documentViewPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
uris = documentSelectResult;
console.info('documentViewPicker.select to file succeed and uris are:' + uris);
}).catch((err: BusinessError) => {
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
```
......@@ -105,7 +107,8 @@ 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()**.
```ts
let config = {
async function example() {
let config: Want = {
action: 'ohos.want.action.OPEN_FILE',
parameters: {
startMode: 'choose',
......@@ -121,9 +124,11 @@ The **FilePicker** provides the following interfaces by file type:
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) {
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
}
}
```
4. After the UI is returned from the **FilePicker** page, use a button to trigger API calling. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**.
......@@ -150,6 +155,7 @@ The **FilePicker** provides the following interfaces by file type:
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
```
2. Create an **audioSelectOptions** instance.
......@@ -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.
```ts
let uri = null;
let uri: string;
const audioViewPicker = new picker.AudioViewPicker();
audioViewPicker.select(audioSelectOptions).then(audioSelectResult => {
uri = audioSelectOptions[0];
audioViewPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
uri = audioSelectResult[0];
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}`);
})
```
......
......@@ -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| √ | √ |
| 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.
>
......@@ -26,16 +26,18 @@ Obtain the sandbox path of a file and set the data security label. For details a
```ts
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.
let context =...; // Obtain UIAbilityContext information.
let context = getContext(this) as common.UIAbilityContext; // Obtain UIAbilityContext.
let pathDir = context.filesDir;
let filePath = pathDir + '/test.txt';
// Set the data level of the file to S0.
securityLabel.setSecurityLabel(filePath, 's0').then(() => {
console.info('Succeeded in setSecurityLabeling.');
}).catch((err) => {
}).catch((err: BusinessError) => {
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
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.
......@@ -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.
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**
......@@ -54,6 +55,8 @@ Before sharing application files, you need to [obtain the application file path]
import window from '@ohos.window';
import wantConstant from '@ohos.app.ability.wantConstant';
import UIAbility from '@ohos.app.ability.UIAbility';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
......@@ -61,7 +64,7 @@ Before sharing application files, you need to [obtain the application file path]
let filePath = this.context.filesDir + '/test.txt';
// Convert the application sandbox path into a URI.
let uri = fileuri.getUriFromPath(filePath);
let want = {
let want: Want = {
// Grant the read and write permissions on the shared file to the target application.
flags: wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION | wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION,
// Set the implicit startup rule for the application that shares the file.
......@@ -73,15 +76,15 @@ Before sharing application files, you need to [obtain the application file path]
.then(() => {
console.info('Invoke getCurrentBundleStats succeeded.');
})
.catch((err) => {
.catch((err: BusinessError) => {
console.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`);
});
}
...
// ...
}
```
## 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**.
......@@ -120,10 +123,12 @@ After obtaining the URI of the shared file from **want**, the application can ca
```ts
// xxx.ets
import fs from '@ohos.file.fs';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
function getShareFile() {
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.
let uri = want.uri;
......@@ -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.
let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
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}`);
}
} 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
- [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.
......
......@@ -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.
- [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
......
......@@ -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.
```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.
let wantAgentInfo:wantAgent.WantAgentInfo = {
......@@ -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).
```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.
let wantAgentInfo:wantAgent.WantAgentInfo = {
......
......@@ -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.|
| 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)|
| 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**)|
| [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)|
......@@ -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)|
|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)|
| 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:
......
......@@ -97,7 +97,7 @@ Example of the **module** tag structure:
| 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|
| 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|
......@@ -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)|
| 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"**)|
| 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)|
|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)|
......
......@@ -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.
## 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
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:
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
......
......@@ -280,7 +280,8 @@
- [@ohos.data.distributedKVStore (Distributed KV Store)](js-apis-distributedKVStore.md)
- [@ohos.data.preferences (User Preferences)](js-apis-data-preferences.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)
- File Management
......
# @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**
>
> 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.
......
......@@ -29,7 +29,7 @@ import UIAbility from '@ohos.app.ability.UIAbility';
## UIAbility.onCreate
onCreate(want: Want, param: AbilityConstant.LaunchParam): void;
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void;
Called to initialize the service logic when a UIAbility is created.
......@@ -46,7 +46,7 @@ Called to initialize the service logic when a UIAbility is created.
```ts
class MyUIAbility extends UIAbility {
onCreate(want, param) {
onCreate(want, launchParam) {
console.log('onCreate, want: ${want.abilityName}');
}
}
......@@ -226,7 +226,7 @@ Called to save data during the ability migration preparation process.
## UIAbility.onNewWant
onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void;
Called when a new Want is passed in and this UIAbility is started again.
......@@ -237,15 +237,15 @@ Called when a new Want is passed in and this UIAbility is started again.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-app-ability-want.md) | Yes| Want information, such as the ability name and bundle name.|
| launchParams | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Reason for the UIAbility startup and the last abnormal exit.|
| launchParam | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Reason for the UIAbility startup and the last abnormal exit.|
**Example**
```ts
class MyUIAbility extends UIAbility {
onNewWant(want, launchParams) {
onNewWant(want, launchParam) {
console.log('onNewWant, want: ${want.abilityName}');
console.log('onNewWant, launchParams: ${JSON.stringify(launchParams)}');
console.log('onNewWant, launchParam: ${JSON.stringify(launchParam)}');
}
}
```
......@@ -315,7 +315,7 @@ class MyUIAbility extends UIAbility {
onShare(wantParam:{ [key: string]: Object }): void;
Called by this UIAbility to set data to share. **ohos.extra.param.key.shareUrl** indicates the online address of the service.
Called by this UIAbility to set data to share in the cross-device sharing scenario.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
......@@ -323,7 +323,7 @@ Called by this UIAbility to set data to share. **ohos.extra.param.key.shareUrl**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wantParam | {[key:&nbsp;string]:&nbsp;Object} | Yes| **want** parameter.|
| wantParam | {[key:&nbsp;string]:&nbsp;Object} | Yes| Data to share.|
**Example**
......
......@@ -4,11 +4,10 @@ The **DataShareExtensionAbility** module provides data share services based on t
>**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 and can be used only in the stage model.
>
> The APIs of this module can be used only in the stage model.
## Modules to Import
......@@ -50,17 +49,17 @@ let TBL_NAME = 'TBL00';
let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)';
let rdbStore;
let rdbStore: relationalStore.RdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
onCreate(want, callback) {
onCreate(want: Want, callback: Function) {
rdb.getRdbStore(this.context, {
name: DB_NAME,
securityLevel: rdb.SecurityLevel.S1
}, function (err, data) {
}, (err, data) => {
console.info(`getRdbStore done, data : ${data}`);
rdbStore = data;
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
rdbStore.executeSql(DDL_TBL_CREATE, [], (err) => {
console.error(`executeSql done, error message : ${err}`);
});
if (callback) {
......@@ -91,21 +90,22 @@ Inserts data into the database. This API can be overridden as required.
```ts
import rdb from '@ohos.data.relationalStore';
import { ValuesBucket } from '@ohos.data.ValuesBucket'
let DB_NAME = 'DB00.db';
let TBL_NAME = 'TBL00';
let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)';
let rdbStore;
let rdbStore: relationalStore.RdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
insert(uri, valueBucket, callback) {
insert(uri: string, valueBucket: ValuesBucket, callback: Function) {
if (valueBucket === null) {
console.error('invalid valueBuckets');
return;
}
rdbStore.insert(TBL_NAME, valueBucket, function (err, ret) {
rdbStore.insert(TBL_NAME, valueBucket, (err, ret) => {
console.info(`callback ret: ${ret}`);
if (callback !== undefined) {
callback(err, ret);
......@@ -136,20 +136,22 @@ Updates data in the database. This API can be overridden as required.
```ts
import rdb from '@ohos.data.relationalStore';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { ValuesBucket } from '@ohos.data.ValuesBucket'
let DB_NAME = 'DB00.db';
let TBL_NAME = 'TBL00';
let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)';
let rdbStore;
let rdbStore: relationalStore.RdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
update(uri, predicates, valueBucket, callback) {
update(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueBucket: ValuesBucket, callback: Function) {
if (predicates === null || predicates === undefined) {
return;
}
rdbStore.update(TBL_NAME, valueBucket, predicates, function (err, ret) {
rdbStore.update(TBL_NAME, valueBucket, predicates, (err, ret) => {
if (callback !== undefined) {
callback(err, ret);
}
......@@ -178,20 +180,21 @@ Deletes data from the database. This API can be overridden as required.
```ts
import rdb from '@ohos.data.relationalStore';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
let DB_NAME = 'DB00.db';
let TBL_NAME = 'TBL00';
let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)';
let rdbStore;
let rdbStore: relationalStore.RdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
delete(uri, predicates, callback) {
delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: Function) {
if (predicates === null || predicates === undefined) {
return;
}
rdbStore.delete(TBL_NAME, predicates, function (err, ret) {
rdbStore.delete(TBL_NAME, predicates, (err, ret) => {
if (callback !== undefined) {
callback(err, ret);
}
......@@ -221,20 +224,21 @@ Queries data from the database. This API can be overridden as required.
```ts
import rdb from '@ohos.data.relationalStore';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
let DB_NAME = 'DB00.db';
let TBL_NAME = 'TBL00';
let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)';
let rdbStore;
let rdbStore: relationalStore.RdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
query(uri, predicates, columns, callback) {
query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: Function) {
if (predicates === null || predicates === undefined) {
return;
}
rdbStore.query(TBL_NAME, predicates, columns, function (err, resultSet) {
rdbStore.query(TBL_NAME, predicates, columns, (err, resultSet) => {
if (resultSet !== undefined) {
console.info(`resultSet.rowCount: ${resultSet.rowCount}`);
}
......@@ -266,21 +270,22 @@ Batch inserts data into the database. This API is called by the server and can b
```ts
import rdb from '@ohos.data.relationalStore';
import { ValuesBucket } from '@ohos.data.ValuesBucket'
let DB_NAME = 'DB00.db';
let TBL_NAME = 'TBL00';
let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)';
let rdbStore;
let rdbStore: relationalStore.RdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
batchInsert(uri, valueBuckets, callback) {
batchInsert(uri: string, valueBuckets: Array<ValuesBucket>, callback: Function) {
if (valueBuckets === null || valueBuckets.length === undefined) {
console.error('invalid valueBuckets');
return;
}
rdbStore.batchInsert(TBL_NAME, valueBuckets, function (err, ret) {
rdbStore.batchInsert(TBL_NAME, valueBuckets, (err, ret) => {
if (callback !== undefined) {
callback(err, ret);
}
......@@ -308,9 +313,15 @@ Normalizes a URI. This API can be overridden as required.
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
normalizeUri(uri, callback) {
let err = {'code':0};
let ret = `normalize: ${uri}`;
normalizeUri(uri: string, callback: Function) {
let key = 'code';
let value = 0;
let err: BusinessError = {
code: value,
name: key,
message: key
};
let ret: string = `normalize: ${uri}`;
callback(err, ret);
}
};
......@@ -335,8 +346,14 @@ Denormalizes a URI. This API can be overridden as required.
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
denormalizeUri(uri, callback) {
let err = {'code':0};
denormalizeUri(uri: string, callback: Function) {
let key = 'code';
let value = 0;
let err: BusinessError = {
code: value,
name: key,
message: key
};
let ret = `denormalize ${uri}`;
callback(err, ret);
}
......
......@@ -672,7 +672,7 @@ Describes audio renderer information.
| ------------- | --------------------------- | ---- | ---------------- |
| content | [ContentType](#contenttype) | No | Audio content type.<br>This parameter is mandatory in API versions 8 and 9 and optional since API version 10.|
| usage | [StreamUsage](#streamusage) | Yes | Audio stream usage.|
| rendererFlags | number | Yes | Audio renderer flags.|
| rendererFlags | number | Yes | Audio renderer flags.<br>The value **0** means a common audio renderer, and **1** means a low-latency audio renderer. Currently, the JS APIs do not support the low-latency audio renderer.|
## InterruptResult<sup>9+</sup>
......@@ -4341,9 +4341,9 @@ async function selectOutputDeviceByFilter(){
}
```
### getPreferOutputDeviceForRendererInfo<sup>10+</sup>
### getPreferredOutputDeviceForRendererInfo<sup>10+</sup>
getPreferOutputDeviceForRendererInfo(rendererInfo: AudioRendererInfo, callback: AsyncCallback&lt;AudioDeviceDescriptors&gt;): void
getPreferredOutputDeviceForRendererInfo(rendererInfo: AudioRendererInfo, callback: AsyncCallback&lt;AudioDeviceDescriptors&gt;): void
Obtains the output device with the highest priority based on the audio renderer information. This API uses an asynchronous callback to return the result.
......@@ -4356,6 +4356,15 @@ Obtains the output device with the highest priority based on the audio renderer
| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information. |
| callback | AsyncCallback&lt;[AudioDeviceDescriptors](#audiodevicedescriptors)&gt; | Yes | Callback used to return the information about the output device with the highest priority.|
**Error codes**
For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 6800101 | if input parameter value error. Return by callback. |
| 6800301 | System error. Return by callback. |
**Example**
```js
let rendererInfo = {
......@@ -4363,8 +4372,8 @@ let rendererInfo = {
usage : audio.StreamUsage.STREAM_USAGE_MEDIA,
rendererFlags : 0 }
async function getPreferOutputDevice() {
audioRoutingManager.getPreferOutputDeviceForRendererInfo(rendererInfo, (err, desc) => {
async function getPreferredOutputDevice() {
audioRoutingManager.getPreferredOutputDeviceForRendererInfo(rendererInfo, (err, desc) => {
if (err) {
console.error(`Result ERROR: ${err}`);
} else {
......@@ -4374,8 +4383,8 @@ async function getPreferOutputDevice() {
}
```
### getPreferOutputDeviceForRendererInfo<sup>10+</sup>
getPreferOutputDeviceForRendererInfo(rendererInfo: AudioRendererInfo): Promise&lt;AudioDeviceDescriptors&gt;
### getPreferredOutputDeviceForRendererInfo<sup>10+</sup>
getPreferredOutputDeviceForRendererInfo(rendererInfo: AudioRendererInfo): Promise&lt;AudioDeviceDescriptors&gt;
Obtains the output device with the highest priority based on the audio renderer information. This API uses a promise to return the result.
......@@ -4399,7 +4408,8 @@ For details about the error codes, see [Audio Error Codes](../errorcodes/errorco
| ID| Error Message|
| ------- | --------------------------------------------|
| 6800101 | if input parameter value error |
| 6800101 | if input parameter value error. Return by promise. |
| 6800301 | System error. Return by promise. |
**Example**
......@@ -4409,8 +4419,8 @@ let rendererInfo = {
usage : audio.StreamUsage.STREAM_USAGE_MEDIA,
rendererFlags : 0 }
async function getPreferOutputDevice() {
audioRoutingManager.getPreferOutputDeviceForRendererInfo(rendererInfo).then((desc) => {
async function getPreferredOutputDevice() {
audioRoutingManager.getPreferredOutputDeviceForRendererInfo(rendererInfo).then((desc) => {
console.info(`device descriptor: ${desc}`);
}).catch((err) => {
console.error(`Result ERROR: ${err}`);
......@@ -4418,9 +4428,9 @@ async function getPreferOutputDevice() {
}
```
### on('preferOutputDeviceChangeForRendererInfo')<sup>10+</sup>
### on('preferredOutputDeviceChangeForRendererInfo')<sup>10+</sup>
on(type: 'preferOutputDeviceChangeForRendererInfo', rendererInfo: AudioRendererInfo, callback: Callback<AudioDeviceDescriptors\>): void
on(type: 'preferredOutputDeviceChangeForRendererInfo', rendererInfo: AudioRendererInfo, callback: Callback<AudioDeviceDescriptors\>): void
Subscribes to the change of the output device with the highest priority. This API uses an asynchronous callback to return the result.
......@@ -4430,7 +4440,7 @@ Subscribes to the change of the output device with the highest priority. This AP
| Name | Type | Mandatory| Description |
| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- |
| type | string | Yes | Event type. The value **'preferOutputDeviceChangeForRendererInfo'** means the event triggered when the output device with the highest priority changes.|
| type | string | Yes | Event type. The value **'preferredOutputDeviceChangeForRendererInfo'** means the output device change event, which is triggered when the output device with the highest priority is changed.|
| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information. |
| callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)\> | Yes | Callback used to return the information about the output device with the highest priority. |
......@@ -4450,14 +4460,14 @@ let rendererInfo = {
usage : audio.StreamUsage.STREAM_USAGE_MEDIA,
rendererFlags : 0 }
audioRoutingManager.on('preferOutputDeviceChangeForRendererInfo', rendererInfo, (desc) => {
audioRoutingManager.on('preferredOutputDeviceChangeForRendererInfo', rendererInfo, (desc) => {
console.info(`device descriptor: ${desc}`);
});
```
### off('preferOutputDeviceChangeForRendererInfo')<sup>10+</sup>
### off('preferredOutputDeviceChangeForRendererInfo')<sup>10+</sup>
off(type: 'preferOutputDeviceChangeForRendererInfo', callback?: Callback<AudioDeviceDescriptors\>): void
off(type: 'preferredOutputDeviceChangeForRendererInfo', callback?: Callback<AudioDeviceDescriptors\>): void
Unsubscribes from the change of the output device with the highest priority.
......@@ -4467,7 +4477,157 @@ Unsubscribes from the change of the output device with the highest priority.
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------------------- | ---- | ------------------------------------------ |
| type | string | Yes | Event type. The value **'preferOutputDeviceChangeForRendererInfo'** means the event triggered when the output device with the highest priority changes.|
| type | string | Yes | Event type. The value **'preferredOutputDeviceChangeForRendererInfo'** means the output device change event, which is triggered when the output device with the highest priority is changed.|
| callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | No | Callback used for unsubscription. |
**Error codes**
For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 6800101 | if input parameter value error |
**Example**
```js
audioRoutingManager.off('preferredOutputDeviceChangeForRendererInfo');
```
### getPreferredInputDeviceForCapturerInfo<sup>10+</sup>
getPreferredInputDeviceForCapturerInfo(capturerInfo: AudioCapturerInfo, callback: AsyncCallback&lt;AudioDeviceDescriptors&gt;): void
Obtains the input device with the highest priority based on the audio renderer information. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
| Name | Type | Mandatory| Description |
| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- |
| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | Audio capturer information. |
| callback | AsyncCallback&lt;[AudioDeviceDescriptors](#audiodevicedescriptors)&gt; | Yes | Callback used to return the information about the input device with the highest priority.|
**Error codes**
For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 6800101 | if input parameter value error |
| 6800301 | System error |
**Example**
```js
let capturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags: 0
}
audioRoutingManager.getPreferredInputDeviceForCapturerInfo(capturerInfo, (err, desc) => {
if (err) {
console.error(`Result ERROR: ${err}`);
} else {
console.info(`device descriptor: ${desc}`);
}
});
```
### getPreferredInputDeviceForCapturerInfo<sup>10+</sup>
getPreferredInputDeviceForCapturerInfo(capturerInfo: AudioCapturerInfo): Promise&lt;AudioDeviceDescriptors&gt;
Obtains the input device with the highest priority based on the audio renderer information. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
| Name | Type | Mandatory| Description |
| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- |
| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | Audio capturer information. |
**Return value**
| Type | Description |
| --------------------- | --------------------------- |
| Promise&lt;[AudioDeviceDescriptors](#audiodevicedescriptors)&gt; | Promise used to return the information about the input device with the highest priority.|
**Error codes**
For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 6800101 | if input parameter value error |
| 6800301 | System error |
**Example**
```js
let capturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags: 0
}
audioRoutingManager.getPreferredInputDeviceForCapturerInfo(capturerInfo).then((desc) => {
console.info(`device descriptor: ${desc}`);
}).catch((err) => {
console.error(`Result ERROR: ${err}`);
})
```
### on('preferredInputDeviceChangeForCapturerInfo')<sup>10+</sup>
on(type: 'preferredInputDeviceChangeForCapturerInfo', capturerInfo: AudioCapturerInfo, callback: Callback<AudioDeviceDescriptors\>): void
Subscribes to the change of the input device with the highest priority. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
| Name | Type | Mandatory| Description |
| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- |
| type | string | Yes | Event type. The value **'preferredInputDeviceChangeForCapturerInfo'** means the input device change event, which is triggered when the input device with the highest priority is changed.|
| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | Audio capturer information. |
| callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)\> | Yes | Callback used to return the information about the input device with the highest priority. |
**Error codes**
For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 6800101 | if input parameter value error |
**Example**
```js
let capturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags: 0
}
audioRoutingManager.on('preferredInputDeviceChangeForCapturerInfo', capturerInfo, (desc) => {
console.info(`device descriptor: ${desc}`);
});
```
### off('preferredInputDeviceChangeForCapturerInfo')<sup>10+</sup>
off(type: 'preferredInputDeviceChangeForCapturerInfo', callback?: Callback<AudioDeviceDescriptors\>): void
Unsubscribes from the change of the input device with the highest priority.
**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------------------- | ---- | ------------------------------------------ |
| type | string | Yes | Event type. The value **'preferredInputDeviceChangeForCapturerInfo'** means the input device change event, which is triggered when the input device with the highest priority is changed.|
| callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | No | Callback used for unsubscription. |
**Error codes**
......@@ -4481,7 +4641,7 @@ For details about the error codes, see [Audio Error Codes](../errorcodes/errorco
**Example**
```js
audioRoutingManager.off('preferOutputDeviceChangeForRendererInfo');
audioRoutingManager.off('preferredInputDeviceChangeForCapturerInfo');
```
## AudioRendererChangeInfoArray<sup>9+</sup>
......@@ -4861,6 +5021,14 @@ Sets an audio effect mode. This API uses an asynchronous callback to return the
| mode | [AudioEffectMode](#audioeffectmode10) | Yes | Audio effect mode to set. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Error codes**
For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
| ID| Error Message|
| ------- | ----------------------------------------------|
| 6800101 | Invalid parameter error. Return by callback. |
**Example**
```js
......@@ -4893,6 +5061,14 @@ Sets an audio effect mode. This API uses a promise to return the result.
| -------------- | ------------------------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
| ID| Error Message|
| ------- | ---------------------------------------------|
| 6800101 | Invalid parameter error. Return by promise. |
**Example**
```js
......
......@@ -744,7 +744,7 @@ Subscribes to characteristic write request events.
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | -------------------------------------- |
| type | string | Yes | Event type. The value **characteristicWrite** indicates a characteristic write request event.|
| type | string | Yes | Event type. The value is **characteristicWrite**, which indicates a characteristic write request event.|
| callback | Callback&lt;[CharacteristicWriteRequest](#characteristicwriterequest)&gt; | Yes | Callback invoked to return a characteristic write request from the GATT client. |
**Example**
......@@ -983,6 +983,66 @@ gattServer.off('connectionStateChange');
```
### on('BLEMtuChange')
on(type: 'BLEMtuChange', callback: Callback&lt;number&gt;): void
Subscribes to MTU status changes for the server.
**Required permissions**: ohos.permission.ACCESS_BLUETOOTH
**System capability**: SystemCapability.Communication.Bluetooth.Core
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| type | string | Yes | Type of event to subscribe to. The value is **BLEMtuChange**, which indicates the MTU status changes. If this parameter is not set correctly, the callback cannot be registered.|
| callback | Callback&lt;number&gt; | Yes | Callback invoked to return the number of MTU bytes.|
**Example**
```js
try {
let gattServer = ble.createGattServer();
gattServer.on('BLEMtuChange', (mtu) => {
console.info('BLEMtuChange, mtu: ' + mtu);
});
} catch (err) {
console.error('errCode: ' + err.code + ', errMessage: ' + err.message);
}
```
### off('BLEMtuChange')
off(type: 'BLEMtuChange', callback?: Callback&lt;number&gt;): void
Unsubscribes from MTU status changes for the server.
**Required permissions**: ohos.permission.ACCESS_BLUETOOTH
**System capability**: SystemCapability.Communication.Bluetooth.Core
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| type | string | Yes | Type of event to unsubscribe from. The value is **BLEMtuChange**, which indicates the MTU status changes. If this parameter is not set correctly, the callback cannot be unregistered.|
| callback | Callback&lt;number&gt; | No | Callback for the MTU status changes. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.|
**Example**
```js
try {
let gattServer = ble.createGattServer();
gattServer.off('BLEMtuChange');
} catch (err) {
console.error('errCode: ' + err.code + ', errMessage: ' + err.message);
}
```
## GattClientDevice
Implements the GATT client. Before using an API of this class, you must create a **GattClientDevice** instance using **createGattClientDevice(deviceId: string)**.
......@@ -2179,7 +2239,7 @@ try {
on(type: 'BLEMtuChange', callback: Callback&lt;number&gt;): void
Subscribes to MTU status changes.
Subscribes to MTU status changes for the client.
**Required permissions**: ohos.permission.ACCESS_BLUETOOTH
......@@ -2189,8 +2249,8 @@ Subscribes to MTU status changes.
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| type | string | Yes | Event type. The value is **BLEMtuChange**, which indicates a MTU status change event.|
| callback | Callback&lt;number&gt; | Yes | Callback invoked to return the MTU status, which can be connected or disconnected.|
| type | string | Yes | Type of event to subscribe to. The value is **BLEMtuChange**, which indicates the MTU status changes. If this parameter is not set correctly, the callback cannot be registered.|
| callback | Callback&lt;number&gt; | Yes | Callback invoked to return the number of MTU bytes.|
**Example**
......@@ -2210,7 +2270,7 @@ try {
off(type: 'BLEMtuChange', callback?: Callback&lt;number&gt;): void
Unsubscribes from MTU status changes.
Unsubscribes from MTU status changes for the client.
**Required permissions**: ohos.permission.ACCESS_BLUETOOTH
......@@ -2220,8 +2280,8 @@ Unsubscribes from MTU status changes.
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| type | string | Yes | Event type. The value is **BLEMtuChange**, which indicates a MTU status change event.|
| callback | Callback&lt;number&gt; | No | Callback for MTU status changes. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.|
| type | string | Yes | Type of event to unsubscribe from. The value is **BLEMtuChange**, which indicates the MTU status changes. If this parameter is not set correctly, the callback cannot be unregistered.|
| callback | Callback&lt;number&gt; | No | Callback for the MTU status changes. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.|
**Example**
......
......@@ -60,7 +60,8 @@ function publishCB(err:Base.BusinessError) {
// Publish a common event.
try {
CommonEventManager.publish("event", publishCB);
} catch(err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -114,7 +115,8 @@ function publishCB(err:Base.BusinessError) {
// Publish a common event.
try {
CommonEventManager.publish("event", options, publishCB);
} catch (err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -166,7 +168,8 @@ let userId = 100;
// Publish a common event.
try {
CommonEventManager.publishAsUser("event", userId, publishCB);
} catch (err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -226,7 +229,8 @@ let userId = 100;
// Publish a common event.
try {
CommonEventManager.publishAsUser("event", userId, options, publishCB);
} catch (err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -269,7 +273,8 @@ function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManag
// Create a subscriber.
try {
CommonEventManager.createSubscriber(subscribeInfo, createCB);
} catch (err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -366,7 +371,8 @@ function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManag
// Subscribe to a common event.
try {
CommonEventManager.subscribe(subscriber, SubscribeCB);
} catch (err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
}
} else {
......@@ -377,7 +383,8 @@ function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManag
// Create a subscriber.
try {
CommonEventManager.createSubscriber(subscribeInfo, createCB);
} catch (err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -433,7 +440,8 @@ function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManag
// Subscribe to a common event.
try {
CommonEventManager.subscribe(subscriber, subscribeCB);
} catch(err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
}
}
......@@ -449,14 +457,16 @@ function unsubscribeCB(err:Base.BusinessError) {
// Create a subscriber.
try {
CommonEventManager.createSubscriber(subscribeInfo, createCB);
} catch (err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
}
// Unsubscribe from the common event.
try {
CommonEventManager.unsubscribe(subscriber, unsubscribeCB);
} catch (err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -583,7 +593,7 @@ CommonEventManager.setStaticSubscriberState(true, (err:Base.BusinessError) => {
console.info(`Set static subscriber state callback failed, err is null.`);
return;
}
if (err.code) {
if (err.code !== undefined && err.code != null) {
console.info(`Set static subscriber state callback failed, errCode: ${err.code}, errMes: ${err.message}`);
return;
}
......
# @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. |
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册