提交 b1ce5513 编写于 作者: 关明月 提交者: Gitee

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

Signed-off-by: N关明月 <guanmingyue@huawei.com>

要显示的变更太多。

To preserve performance only 1000 of 1000+ files are displayed.
...@@ -8,14 +8,14 @@ ...@@ -8,14 +8,14 @@
- Quick Start - Quick Start
- Getting Started - Getting Started
- [Preparations](quick-start/start-overview.md) - [Preparations](quick-start/start-overview.md)
- [Getting Started with eTS in the Traditional Coding Approach](quick-start/start-with-ets.md) - [Getting Started with eTS in Stage Model](quick-start/start-with-ets-stage.md)
- [Getting Started with eTS in the Low-Code Approach](quick-start/start-with-ets-low-code.md) - [Getting Started with eTS in FA Model](quick-start/start-with-ets-fa.md)
- [Getting Started with JavaScript in the Traditional Coding Approach](quick-start/start-with-js.md) - [Getting Started with JavaScript in FA Model](quick-start/start-with-js-fa.md)
- [Getting Started with JavaScript in the Low-Code Approach](quick-start/start-with-js-low-code.md)
- Development Fundamentals - Development Fundamentals
- [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md) - [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md)
- [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md) - [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md)
- [SysCap](quick-start/syscap.md) - [SysCap](quick-start/syscap.md)
- [HarmonyAppProvision Configuration File](quick-start/app-provision-structure.md)
- Development - Development
- [Ability Development](ability/Readme-EN.md) - [Ability Development](ability/Readme-EN.md)
- [UI Development](ui/Readme-EN.md) - [UI Development](ui/Readme-EN.md)
...@@ -44,5 +44,8 @@ ...@@ -44,5 +44,8 @@
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
- APIs - APIs
- [JS and TS APIs](reference/apis/Readme-EN.md) - [JS and TS APIs](reference/apis/Readme-EN.md)
- Native APIs
- [Standard Libraries](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md)
- Contribution - Contribution
- [How to Contribute](../contribute/documentation-contribution.md) - [How to Contribute](../contribute/documentation-contribution.md)
...@@ -17,5 +17,7 @@ ...@@ -17,5 +17,7 @@
- Other - Other
- [WantAgent Development](wantagent.md) - [WantAgent Development](wantagent.md)
- [Ability Assistant Usage](ability-assistant-guidelines.md) - [Ability Assistant Usage](ability-assistant-guidelines.md)
- [ContinuationManager Development](continuationmanager.md)
- [Test Framework Usage](ability-delegator.md) - [Test Framework Usage](ability-delegator.md)
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
An ability is the abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances. An ability is the abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances.
The ability framework model has two forms. The ability framework model has two forms:
- FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there is Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities. - FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there is Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities.
- Stage model, which is introduced since API version 9. In the stage model, there is `Ability` and `ExtensionAbility`. `ExtensionAbility` is further extended to `ServiceExtensionAbility`, `FormExtensionAbility`, `DataShareExtensionAbility`, and more. - Stage model, which is introduced since API version 9. In the stage model, there is `Ability` and `ExtensionAbility`. `ExtensionAbility` is further extended to `ServiceExtensionAbility`, `FormExtensionAbility`, `DataShareExtensionAbility`, and more.
...@@ -11,10 +11,10 @@ The stage model is designed to make it easier to develop complex applications in ...@@ -11,10 +11,10 @@ The stage model is designed to make it easier to develop complex applications in
| Item | FA Model | Stage Model | | Item | FA Model | Stage Model |
| -------------- | ------------------------------------------------------------ | -------------------------------------------------------- | | -------------- | ------------------------------------------------------------ | -------------------------------------------------------- |
| Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. | | Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. |
| Engine instance | Each ability in a process exclusively uses a JS VM engine instance. | Multiple abilities in a process share one JS VM engine instance. | | Engine instance | Each ability in a process exclusively uses a JS VM engine instance. | Multiple abilities in a process share one JS VM engine instance. |
| Intra-process object sharing| Not supported. | Supported. | | Intra-process object sharing| Not supported. | Supported. |
| Bundle description file | The `config.json` file is used to describe the HAP and component information. Each component must use a fixed file name.| The `module.json` file is used to describe the HAP and component information. The entry file name can be specified.| | Bundle description file | The `config.json` file is used to describe the HAP and component information. Each component must use a fixed file name.| The `module.json5` file is used to describe the HAP and component information. The entry file name can be specified.|
| Component | Four types of components are provided: Page ability (used for UI page display), Service ability (used to provide services), Data ability (used for data sharing), and Form ability (used to provide widgets).| Two types of components are provided: Ability (used for UI page display) and Extension (scenario-based service extension). | | Component | Four types of components are provided: Page ability (used for UI page display), Service ability (used to provide services), Data ability (used for data sharing), and Form ability (used to provide widgets).| Two types of components are provided: Ability (used for UI page display) and Extension (scenario-based service extension). |
In addition, the following differences exist in the development process: In addition, the following differences exist in the development process:
...@@ -27,5 +27,4 @@ In addition, the following differences exist in the development process: ...@@ -27,5 +27,4 @@ In addition, the following differences exist in the development process:
![lifecycle](figures/lifecycle.png) ![lifecycle](figures/lifecycle.png)
For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md). For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md).
# ContinuationManager Development
> **NOTE**
>
> Currently, the **ContinuationManager** module is not available for application development. Its APIs are mainly used to start the device selection module.
## When to Use
Users are using two or more devices to experience an all-scenario, multi-device lifestyle. Each type of device has its unique advantages and disadvantages specific to scenarios. The ability continuation capability breaks boundaries of devices and enables multi-device collaboration, achieving precise control, universal coordination, and seamless hops of user applications.
As the entry of the ability continuation capability, **continuationManager** is used to start the device selection module for the user to select the target device. After a device is selected, information about the selected device is returned to the user. The user can then initiate cross-device continuation or collaboration based on the device information.
![continuationManager](figures/continuationManager.png)
## Available APIs
| API | Description|
| ---------------------------------------------------------------------------------------------- | ----------- |
| register(callback: AsyncCallback\<number>): void | Registers the continuation management service and obtains a token. This API does not involve any filter parameters and uses an asynchronous callback to return the result.|
| register(options: ContinuationExtraParams, callback: AsyncCallback\<number>): void | Registers the continuation management service and obtains a token. This API uses an asynchronous callback to return the result.|
| register(options?: ContinuationExtraParams): Promise\<number> | Registers the continuation management service and obtains a token. This API uses a promise to return the result.|
| on(type: "deviceConnect", token: number, callback: Callback\<Array\<ContinuationResult>>): void | Subscribes to device connection events. This API uses an asynchronous callback to return the result.|
| on(type: "deviceDisconnect", token: number, callback: Callback\<Array\<string>>): void | Subscribes to device disconnection events. This API uses an asynchronous callback to return the result.|
| off(type: "deviceConnect", token: number): void | Unsubscribes from device connection events.|
| off(type: "deviceDisconnect", token: number): void | Unsubscribes from device disconnection events.|
| startDeviceManager(token: number, callback: AsyncCallback\<void>): void | Starts the device selection module to show the list of available devices. This API does not involve any filter parameters and uses an asynchronous callback to return the result.|
| startDeviceManager(token: number, options: ContinuationExtraParams, callback: AsyncCallback\<void>): void | Starts the device selection module to show the list of available devices. This API uses an asynchronous callback to return the result.|
| startDeviceManager(token: number, options?: ContinuationExtraParams): Promise\<void> | Starts the device selection module to show the list of available devices. This API uses a promise to return the result.|
| updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState, callback: AsyncCallback\<void>): void | Instructs the device selection module to update the device connection state. This API uses an asynchronous callback to return the result.|
| updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState): Promise\<void> | Instructs the device selection module to update the device connection state. This API uses a promise to return the result.|
| unregister(token: number, callback: AsyncCallback\<void>): void | Deregisters the continuation management service. This API uses an asynchronous callback to return the result.|
| unregister(token: number): Promise\<void> | Deregisters the continuation management service. This API uses a promise to return the result.|
## How to Develop
1. Import the **continuationManager** module.
```ts
import continuationManager from '@ohos.continuation.continuationManager';
```
2. Apply for permissions required for cross-device continuation or collaboration operations.
The permission application operation varies according to the ability model in use. In the FA mode, add the required permission in the `config.json` file, as follows:
```json
{
"module": {
"reqPermissions": [
{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
}
]
}
}
```
This permission must also be granted by the user through a dialog box when the application is started for the first time. The sample code is as follows:
```ts
import abilityAccessCtrl from "@ohos.abilityAccessCtrl";
import bundle from '@ohos.bundle';
async function requestPermission() {
let permissions: Array<string> = [
"ohos.permission.DISTRIBUTED_DATASYNC"
];
let needGrantPermission: boolean = false;
let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
let applicationInfo = await bundle.getApplicationInfo('ohos.samples.etsDemo', 0, 100);
for (let i = 0; i < permissions.length; i++) {
let result = await atManager.verifyAccessToken(applicationInfo.accessTokenId, permissions[i]);
// Check whether the permission is granted.
if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
needGrantPermission = true;
break;
}
}
// If the permission is not granted, call requestPermissionsFromUser to apply for the permission.
if (needGrantPermission) {
await featureAbility.getContext().requestPermissionsFromUser(permissions, 1);
} else {
console.info('app permission already granted');
}
}
```
In the stage model, add the required permission in the `module.json5` file. The sample code is as follows:
```json
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
}
]
}
}
```
```ts
import abilityAccessCtrl from "@ohos.abilityAccessCtrl";
import bundle from '@ohos.bundle';
async function requestPermission() {
let permissions: Array<string> = [
"ohos.permission.DISTRIBUTED_DATASYNC"
];
let needGrantPermission: boolean = false;
let atManger: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
let applicationInfo = await bundle.getApplicationInfo('ohos.samples.continuationmanager', 0, 100);
for (const permission of permissions) {
try {
let grantStatus = await atManger.verifyAccessToken(applicationInfo.accessTokenId, permission);
// Check whether the permission is granted.
if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_DENIED) {
needGrantPermission = true;
break;
}
} catch (err) {
console.error('app permission query grant status error' + JSON.stringify(err));
needGrantPermission = true;
break;
}
}
// If the permission is not granted, call requestPermissionsFromUser to apply for the permission.
if (needGrantPermission) {
try {
await globalThis.abilityContext.requestPermissionsFromUser(permissions);
} catch (err) {
console.error('app permission request permissions error' + JSON.stringify(err));
}
} else {
console.info('app permission already granted');
}
}
```
3. Register the continuation management service and obtain a token.
The sample code is as follows:
```ts
let token: number = -1; // Used to save the token returned after the registration. The token will be used when listening for device connection/disconnection events, starting the device selection module, and updating the device connection state.
continuationManager.register().then((data) => {
console.info('register finished, ' + JSON.stringify(data));
token = data; // Obtain a token and assign a value to the token variable.
}).catch((err) => {
console.error('register failed, cause: ' + JSON.stringify(err));
});
```
4. Listen for the device connection/disconnection state.
The sample code is as follows:
```ts
let remoteDeviceId: string = ""; // Used to save the information about the remote device selected by the user, which will be used for cross-device continuation or collaboration.
// The token parameter is the token obtained during the registration.
continuationManager.on("deviceConnect", token, (continuationResults) => {
console.info('registerDeviceConnectCallback len: ' + continuationResults.length);
if (continuationResults.length <= 0) {
console.info('no selected device');
return;
}
remoteDeviceId = continuationResults[0].id; // Assign the deviceId of the first selected remote device to the remoteDeviceId variable.
// Pass the remoteDeviceId parameter to want.
let want = {
deviceId: remoteDeviceId,
bundleName: 'ohos.samples.continuationmanager',
abilityName: 'MainAbility'
};
// To initiate multi-device collaboration, you must obtain the ohos.permission.DISTRIBUTED_DATASYNC permission.
globalThis.abilityContext.startAbility(want).then((data) => {
console.info('StartRemoteAbility finished, ' + JSON.stringify(data));
}).catch((err) => {
console.error('StartRemoteAbility failed, cause: ' + JSON.stringify(err));
});
});
```
The preceding multi-device collaboration operation is performed across devices in the stage model. For details about this operation in the FA model, see [Page Ability Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/ability/fa-pageability.md).
You can also instruct the device selection module to update the device connection state. The sample code is as follows:
```ts
// Set the device connection state.
let deviceConnectStatus: continuationManager.DeviceConnectState = continuationManager.DeviceConnectState.CONNECTED;
// The token parameter is the token obtained during the registration, and the remoteDeviceId parameter is the remoteDeviceId obtained.
continuationManager.updateConnectStatus(token, remoteDeviceId, deviceConnectStatus).then((data) => {
console.info('updateConnectStatus finished, ' + JSON.stringify(data));
}).catch((err) => {
console.error('updateConnectStatus failed, cause: ' + JSON.stringify(err));
});
```
Listen for the device disconnection state so that the user can stop cross-device continuation or collaboration in time. The sample code is as follows:
```ts
// The token parameter is the token obtained during the registration.
continuationManager.on("deviceDisconnect", token, (deviceIds) => {
console.info('onDeviceDisconnect len: ' + deviceIds.length);
if (deviceIds.length <= 0) {
console.info('no unselected device');
return;
}
// Update the device connection state.
let unselectedDeviceId: string = deviceIds[0]; // Assign the deviceId of the first deselected remote device to the unselectedDeviceId variable.
let deviceConnectStatus: continuationManager.DeviceConnectState = continuationManager.DeviceConnectState.DISCONNECTING; // Device disconnected.
// The token parameter is the token obtained during the registration, and the unselectedDeviceId parameter is the unselectedDeviceId obtained.
continuationManager.updateConnectStatus(token, unselectedDeviceId, deviceConnectStatus).then((data) => {
console.info('updateConnectStatus finished, ' + JSON.stringify(data));
}).catch((err) => {
console.error('updateConnectStatus failed, cause: ' + JSON.stringify(err));
});
});
```
5. Start the device selection module to show the list of available devices on the network.
The sample code is as follows:
```ts
// Filter parameters.
let continuationExtraParams = {
deviceType: ["00E"], // Device type.
continuationMode: continuationManager.ContinuationMode.COLLABORATION_SINGLE // Single-choice mode of the device selection module.
};
// The token parameter is the token obtained during the registration.
continuationManager.startDeviceManager(token, continuationExtraParams).then((data) => {
console.info('startDeviceManager finished, ' + JSON.stringify(data));
}).catch((err) => {
console.error('startDeviceManager failed, cause: ' + JSON.stringify(err));
});
```
6. If you do not need to perform cross-device migration or collaboration operations, you can deregister the continuation management service, by passing the token obtained during the registration.
The sample code is as follows:
```ts
// The token parameter is the token obtained during the registration.
continuationManager.unregister(token).then((data) => {
console.info('unregister finished, ' + JSON.stringify(data));
}).catch((err) => {
console.error('unregister failed, cause: ' + JSON.stringify(err));
});
```
...@@ -23,12 +23,10 @@ Example URIs: ...@@ -23,12 +23,10 @@ Example URIs:
- Cross-device communication: **dataability://***device_id***/***com.domainname.dataability.persondata***/***person***/***10* - Cross-device communication: **dataability://***device_id***/***com.domainname.dataability.persondata***/***person***/***10*
- Local-device communication: **dataability:///***com.domainname.dataability.persondata***/***person***/***10* - Local-device communication: **dataability:///***com.domainname.dataability.persondata***/***person***/***10*
> **NOTE** > **NOTE**
> >
> In the case of local-device communication, **device_id** is empty, and therefore, there are three slashes (/) after **dataability:**. > In the case of local-device communication, **device_id** is empty, and therefore, there are three slashes (/) after **dataability:**.
## Available APIs ## Available APIs
**Table 1** Data ability lifecycle APIs **Table 1** Data ability lifecycle APIs
...@@ -140,7 +138,7 @@ Import the basic dependency packages and obtain the URI string for communicating ...@@ -140,7 +138,7 @@ Import the basic dependency packages and obtain the URI string for communicating
The basic dependency packages include: The basic dependency packages include:
- @ohos.ability.featureAbility - @ohos.ability.featureAbility
- @ohos.data.dataability - @ohos.data.dataAbility
- @ohos.data.rdb - @ohos.data.rdb
#### Data Ability API Development #### Data Ability API Development
...@@ -154,7 +152,7 @@ The basic dependency packages include: ...@@ -154,7 +152,7 @@ The basic dependency packages include:
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
import ohos_data_ability from '@ohos.data.dataAbility' import ohos_data_ability from '@ohos.data.dataAbility'
import ohos_data_rdb from '@ohos.data.rdb' import ohos_data_rdb from '@ohos.data.rdb'
var urivar = "dataability:///com.ix.DataAbility" var urivar = "dataability:///com.ix.DataAbility"
var DAHelper = featureAbility.acquireDataAbilityHelper( var DAHelper = featureAbility.acquireDataAbilityHelper(
urivar urivar
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
## Widget Overview ## Widget Overview
A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application. A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application.
A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message. A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message.
Basic concepts: Basic concepts:
- Widget provider: an atomic service that controls what and how content is displayed in a widget and interacts with users. - Widget provider: an atomic service that controls what and how content is displayed in a widget and interacts with users.
...@@ -157,8 +157,8 @@ Configure the **config.json** file for the widget. ...@@ -157,8 +157,8 @@ Configure the **config.json** file for the widget.
| supportDimensions | Grid styles supported by the widget. Available values are as follows:<br>**1 * 2**: indicates a grid with one row and two columns.<br>**2 * 2**: indicates a grid with two rows and two columns.<br>**2 * 4**: indicates a grid with two rows and four columns.<br>**4 * 4**: indicates a grid with four rows and four columns.| String array| No | | supportDimensions | Grid styles supported by the widget. Available values are as follows:<br>**1 * 2**: indicates a grid with one row and two columns.<br>**2 * 2**: indicates a grid with two rows and two columns.<br>**2 * 4**: indicates a grid with two rows and four columns.<br>**4 * 4**: indicates a grid with four rows and four columns.| String array| No |
| defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No |
| updateEnabled | Whether the widget can be updated periodically. Available values are as follows:<br>**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.<br>**false**: The widget cannot be updated periodically.| Boolean | No | | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:<br>**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.<br>**false**: The widget cannot be updated periodically.| Boolean | No |
| scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.<br>This parameter has a lower priority than **updateDuration**. If both are specified, the value specified by **updateDuration** is used.| String | Yes (initial value: **0:0**) |
| updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.<br>If the value is **0**, this field does not take effect.<br>If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.<br>If the value is **0**, this field does not take effect.<br>If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.<br>This parameter has a higher priority than **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number | Yes (initial value: **0**) |
| formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | | formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) |
| formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) |
| jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. | String | No | | jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. | String | No |
...@@ -189,7 +189,6 @@ Configure the **config.json** file for the widget. ...@@ -189,7 +189,6 @@ Configure the **config.json** file for the widget.
"scheduledUpdateTime": "10:30", "scheduledUpdateTime": "10:30",
"supportDimensions": ["2*2"], "supportDimensions": ["2*2"],
"type": "JS", "type": "JS",
"updateDuration": 1,
"updateEnabled": true "updateEnabled": true
}] }]
}] }]
...@@ -208,7 +207,7 @@ Mostly, the widget provider is started only when it needs to obtain information ...@@ -208,7 +207,7 @@ Mostly, the widget provider is started only when it needs to obtain information
let formName = want.parameters["ohos.extra.param.key.form_name"]; let formName = want.parameters["ohos.extra.param.key.form_name"];
let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"];
// Persistently store widget information for subsequent use, such as widget instance retrieval or update. // Persistently store widget information for subsequent use, such as widget instance retrieval or update.
// The storeFormInfo API is not implemented here. For details about the implementation, see "FA Model Widget" provided in "Samples". // The storeFormInfo API is not implemented here.
storeFormInfo(formId, formName, tempFlag, want); storeFormInfo(formId, formName, tempFlag, want);
let obj = { let obj = {
...@@ -227,7 +226,7 @@ You should override **onDestroy** to delete widget data. ...@@ -227,7 +226,7 @@ You should override **onDestroy** to delete widget data.
console.log('FormAbility onDestroy'); console.log('FormAbility onDestroy');
// You need to implement the code for deleting the persistent widget instance. // You need to implement the code for deleting the persistent widget instance.
// The deleteFormInfo API is not implemented here. For details, see "Widget Host" provided in "Samples". // The deleteFormInfo API is not implemented here.
deleteFormInfo(formId); deleteFormInfo(formId);
} }
``` ```
...@@ -336,7 +335,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme ...@@ -336,7 +335,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
"actions": { "actions": {
"routerEvent": { "routerEvent": {
"action": "router", "action": "router",
"abilityName": "com.example.MyApplication.hmservice.FormAbility", "abilityName": "com.example.entry.MainAbility",
"params": { "params": {
"message": "add detail" "message": "add detail"
} }
...@@ -349,3 +348,57 @@ Now you've got a widget shown below. ...@@ -349,3 +348,57 @@ Now you've got a widget shown below.
![fa-form-example](figures/fa-form-example.png) ![fa-form-example](figures/fa-form-example.png)
### Developing Widget Events
You can set router and message events for components on a widget. The router event applies to ability redirection, and the message event applies to custom click events. The key steps are as follows:
1. Set **onclick** in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file.
2. For the router event, set the following attributes:
- **action**: **"router"**.
- **abilityName**: target ability name, for example, **com.example.entry.MainAbility**, which is the default main ability name in DevEco Studio for the FA model.
- **params**: custom parameters of the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the main ability in the FA model, **featureAbility.getWant()** can be used to obtain **want** and its **parameters** field.
3. For the message event, set the following attributes:
- **action**: **"message"**.
- **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onEvent**.
The code snippet is as follows:
- In the HML file:
```html
<div class="container">
<stack>
<div class="container-img">
<image src="/common/widget.png" class="bg-img"></image>
</div>
<div class="container-inner">
<text class="title" onclick="routerEvent">{{title}}</text>
<text class="detail_text" onclick="messageEvent">{{detail}}</text>
</div>
</stack>
</div>
```
- In the JSON file:
```json
{
"data": {
"title": "TitleDefault",
"detail": "TextDefault"
},
"actions": {
"routerEvent": {
"action": "router",
"abilityName": "com.example.entry.MainAbility",
"params": {
"message": "add detail"
}
},
"messageEvent": {
"action": "message",
"params": {
"message": "add detail"
}
}
}
}
```
\ No newline at end of file
...@@ -12,8 +12,9 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -12,8 +12,9 @@ The following table lists the APIs used for ability continuation. For details ab
|API| Description| |API| Description|
|:------ | :------| |:------ | :------|
| onContinue(wantParam : {[key: string]: any}): OnContinueResult | Called by the initiator to store the data required for continuation and request continuation. The value **AGREE** means that the continuation is accepted, and **REJECT** means the continuation is rejected, and **MISMATCH** means a version mismatch.| | onContinue(wantParam : {[key: string]: any}): OnContinueResult | Called by the initiator to store the data required for continuation. The return value indicates whether the continuation request is accepted. The value **AGREE** means that the continuation request is accepted, **REJECT** means that the continuation request is rejected, and **MISMATCH** means a version mismatch.|
| onCreate(want: Want, param : LaunchParam): void | Called by the target to restore the data and UI page.| | onCreate(want: Want, param: AbilityConstant.LaunchParam): void; | Called by the target to restore the data and UI page in the multi-instance ability scenario.|
| onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; | Called by the target to restore the data and UI page in the singleton ability scenario.|
...@@ -21,20 +22,30 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -21,20 +22,30 @@ The following table lists the APIs used for ability continuation. For details ab
![continuation_dev](figures/continuation-info.png) ![continuation_dev](figures/continuation-info.png)
In effect, ability continuation is a cross-device ability startup that carries data. When the continuation is triggered, device A calls back **onContinue()** of the application. You must save the current data in this API. Then, device A initiates a cross-device ability startup on device B and transmits the data to device B. Device B calls back **onCreate()**. You must restore the transmitted data in this API. In effect, ability continuation is a cross-device ability startup that carries data. When a continuation action is initiated, the system on device A calls back **onContinue()** of the application. You must implement storage of the current data in this API. Then, the system initiates a cross-device ability startup on device B and transmits the data to device B. The system on device B calls back **onCreate()** or **onNewWant()**. You must implement restoration of the transmitted data in this API.
## How to Develop ## How to Develop
The code snippets provided below are all from [Sample](https://gitee.com/openharmony/ability_dmsfwk/tree/master/services/dtbschedmgr/test/samples/continuationManualTestSuite).
### Application Continuation ### Application Continuation
1. Configuration 1. Modify the configuration file.
- Configure the application to support ability continuation. - Configure the application to support ability continuation.
Set the **continuable** field in the **module.json5** file to **true**. The default value is **false**. If this parameter is set to **false**, the application cannot be continued on another device. Set the **continuable** field in the **module.json5** file to **true**. The default value is **false**. If this parameter is set to **false**, the application cannot be continued on another device.
```javascript ```javascript
"continuable": true {
"module": {
"abilities": [
{
"continuable": true,
}
]
}
}
``` ```
...@@ -42,30 +53,53 @@ In effect, ability continuation is a cross-device ability startup that carries d ...@@ -42,30 +53,53 @@ In effect, ability continuation is a cross-device ability startup that carries d
- Configure the application startup type. - Configure the application startup type.
Set **launchType** in the **module.json5** file to **standard** to add multi-instance support to the application. If **launchType** is set to **standard** in the **module.json5** file, the application is of the multi-instance launch type. During ability continuation, regardless of whether the application is already open, the target starts the application and restores the UI page. If **launchType** is set to **singleton**, the application is of the singleton launch type. If the application is already open, the target clears the existing page stack and restores the UI page. For more information, see "Launch Type" in [Ability Development](./stage-ability.md).
Configure a multi-instance application as follows:
```javascript ```javascript
"launchType": "standard" {
"module": {
"abilities": [
{
"launchType": "standard",
}
]
}
}
``` ```
Configure a singleton application as follows or retain the default settings of **launchType**:
```javascript
{
"module": {
"abilities": [
{
"launchType": "singleton",
}
]
}
}
```
- Apply for the distributed permissions. - Apply for the distributed permissions.
Declare the **DISTRIBUTED_DATASYNC** permission in the **module.json5** file for the application. Declare the **DISTRIBUTED_DATASYNC** permission in the **module.json5** file for the application.
```javascript ```javascript
"requestPermissions": [ "requestPermissions": [
{ {
"name": "ohos.permission.DISTRIBUTED_DATASYNC" "name": "ohos.permission.DISTRIBUTED_DATASYNC"
}, },
``` ```
This permission must be granted by the user in a dialog box when the application is started for the first time. To enable the application to display a dialog box to ask for the permission, add the following code to **onWindowStageCreate** of the **Ability** class: This permission must be granted by the user in a dialog box when the application is started for the first time. To enable the application to display a dialog box to ask for the permission, add the following code to **onWindowStageCreate** of the **Ability** class:
```javascript ```javascript
requestPermissions = async () => { requestPermissions = async () => {
let permissions: Array<string> = [ let permissions: Array<string> = [
...@@ -102,14 +136,13 @@ In effect, ability continuation is a cross-device ability startup that carries d ...@@ -102,14 +136,13 @@ In effect, ability continuation is a cross-device ability startup that carries d
} }
} }
``` ```
2. Implement the **onContinue()** API. 2. Implement the **onContinue()** API.
The **onContinue()** API is called by the initiator to save the UI component state variables and memory data and prepare for continuation. After the application completes the continuation preparation, the system must return **OnContinueResult.AGREE(0)** to accept the continuation request. If an error code is returned, the request is rejected. If this API is not implemented, the system rejects the continuation request by default. The **onContinue()** API is called by the initiator to save the UI component state variables and memory data and prepare for continuation. After the application completes the continuation preparation, the system must return either **OnContinueResult.AGREE(0)** to accept the continuation request or an error code to reject the request. If this API is not implemented, the system rejects the continuation request by default.
Modules to import: Modules to import:
...@@ -119,22 +152,25 @@ In effect, ability continuation is a cross-device ability startup that carries d ...@@ -119,22 +152,25 @@ In effect, ability continuation is a cross-device ability startup that carries d
``` ```
To implement ability continuation, you must implement this API and have the value **AGREE** returned. To implement ability continuation, you must implement this API and have the value **AGREE** returned.
You can obtain the target device ID (identified by the key **targetDevice**) and the version number (identified by the key **version**) of the application installed on the target device from the **wantParam** parameter of this API. The version number can be used for compatibility check. If the current application version is incompatible with that on the target device, **OnContinueResult.MISMATCH** can be returned to reject the continuation request.
Example Example
```javascript ```javascript
onContinue(wantParam : {[key: string]: any}) { onContinue(wantParam : {[key: string]: any}) {
Logger.info("onContinue using distributedObject") Logger.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`)
// Set the user input data into want params. let workInput = AppStorage.Get<string>('ContinueWork');
wantParam["input"] = AppStorage.Get<string>('ContinueInput'); // Set the user input data into wantParam.
Logger.info(`onContinue input = ${wantParam["input"]}`); wantParam["work"] = workInput // set user input data into want params
return AbilityConstant.OnContinueResult.AGREE Logger.info(`onContinue input = ${wantParam["input"]}`);
} return AbilityConstant.OnContinueResult.AGREE
}
``` ```
3. Implement the continuation logic in the **onCreate()** API. 3. Implement the continuation logic in the **onCreate()** or **onNewWant()** API.
The **onCreate()** API is called by the target. When the ability is started on the target device, this API is called to instruct the application to synchronize the memory data and UI component state, and triggers page restoration after the synchronization is complete. If the continuation logic is not implemented, the ability will be started in common startup mode and the page cannot be restored. The **onCreate()** API is called by the target. When the ability is started on the target device, this API is called to instruct the application to synchronize the memory data and UI component state, and triggers page restoration after the synchronization is complete. If the continuation logic is not implemented, the ability will be started in common startup mode and the page cannot be restored.
...@@ -142,22 +178,34 @@ In effect, ability continuation is a cross-device ability startup that carries d ...@@ -142,22 +178,34 @@ In effect, ability continuation is a cross-device ability startup that carries d
After data restore is complete, call **restoreWindowStage** to trigger page restoration. After data restore is complete, call **restoreWindowStage** to trigger page restoration.
Example
You can also use **want.parameters.version** in the **want** parameter to obtain the application version number of the initiator.
Example
```javascript ```javascript
onCreate(want, launchParam) { import Ability from '@ohos.application.Ability';
Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) import distributedObject from '@ohos.data.distributedDataObject';
globalThis.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { export default class MainAbility extends Ability {
let input = want.parameters.input // Obtain user data from want params. storage : LocalStorag;
AppStorage.SetOrCreate<string>('ContinueInput', input)
Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`) onCreate(want, launchParam) {
Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
this.contentStorage = new ContentStorage(); if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
this.context.restoreWindowStage(this.contentStorage); // Obtain the user data from the want parameter.
} let workInput = want.parameters.work
} Logger.info(`work input ${workInput}`)
AppStorage.SetOrCreate<string>('ContinueWork', workInput)
this.storage = new LocalStorage();
this.context.restoreWindowStage(this.storage);
}
}
}
``` ```
For a singleton ability, use **onNewWant()** to achieve the same implementation.
...@@ -169,28 +217,38 @@ Distributed objects allow cross-device data synchronization like local variables ...@@ -169,28 +217,38 @@ Distributed objects allow cross-device data synchronization like local variables
In the ability continuation scenario, the distributed data object is used to synchronize the memory data from the local device to the target device. In the ability continuation scenario, the distributed data object is used to synchronize the memory data from the local device to the target device.
- In **onContinue()**, the initiator saves the data to be continued to the distributed object, sets the session ID, and sends the session ID to the target device through **wantParam**. - In **onContinue()**, the initiator saves the data to be migrated to the distributed object, calls the **save()** API to save the data and synchronize the data to the target device, sets the session ID, and sends the session ID to the target device through **wantParam**.
```javascript ```javascript
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:undefined}); var g_object = distributedObject.createDistributedObject({data:undefined});
export default class MainAbility extends Ability { export default class MainAbility extends Ability {
contentStorage : ContentStorage
sessionId : string; sessionId : string;
onContinue(wantParam : {[key: string]: any}) { onContinue(wantParam : {[key: string]: any}) {
Logger.info("onContinue using distributedObject") Logger.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`)
this.sessionId = distributedObject.genSessionId();
// Set the session ID for the distributed data object. if (g_object.__sessionId === undefined) {
g_object.setSessionId(this.sessionId); this.sessionId = distributedObject.genSessionId()
g_object.name = "Amy"; Logger.info(`onContinue generate new sessionId`)
// Set the session ID into the want parameter. }
wantParam["session"] = this.sessionId; else {
return AbilityConstant.OnContinueResult.AGREE this.sessionId = g_object.__sessionId;
} }
wantParam["session"] = this.sessionId
g_object.data = AppStorage.Get<string>('ContinueStudy');
Logger.info(`onContinue sessionId = ${this.sessionId}, name = ${g_object.data}`)
g_object.setSessionId(this.sessionId);
g_object.save(wantParam.targetDevice, (result, data)=>{
Logger.info("save callback");
Logger.info("save sessionId " + data.sessionId);
Logger.info("save version " + data.version);
Logger.info("save deviceId " + data.deviceId);
});
``` ```
...@@ -201,15 +259,11 @@ In the ability continuation scenario, the distributed data object is used to syn ...@@ -201,15 +259,11 @@ In the ability continuation scenario, the distributed data object is used to syn
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:undefined}); var g_object = distributedObject.createDistributedObject({data:undefined});
export default class MainAbility extends Ability { export default class MainAbility extends Ability {
contentStorage : ContentStorage storage : LocalStorag;
sessionId : string;
statusCallback(sessionId, networkid, status) {
Logger.info(`continuation object status change, sessionId: ${sessionId}, status: ${status}, g_object.name: ${g_object.name}`)
}
onCreate(want, launchParam) { onCreate(want, launchParam) {
Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
...@@ -218,13 +272,40 @@ In the ability continuation scenario, the distributed data object is used to syn ...@@ -218,13 +272,40 @@ In the ability continuation scenario, the distributed data object is used to syn
this.sessionId = want.parameters.session this.sessionId = want.parameters.session
Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`) Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`)
g_object.on("status", this.statusCallback); // Before fetching data from the remote device, reset g_object.data to undefined.
// Set the session ID for data synchronization. g_object.data = undefined;
g_object.setSessionId(this.sessionId); // Set the session ID, so the target will fetch data from the remote device.
g_object.setSessionId(this.sessionId);
this.contentStorage = new ContentStorage(); AppStorage.SetOrCreate<string>('ContinueStudy', g_object.data)
this.context.restoreWindowStage(this.contentStorage); this.storage = new LocalStorage();
this.context.restoreWindowStage(this.storage);
} }
} }
} }
``` ```
### More Information
1. Timeout
- If the application to be continued is not installed on the target device, the system checks whether the application can be installed on it and waits for a response for 4 seconds. If no response is received within 4 seconds, the caller receives a timeout error code, which means that the application cannot be installed on the target device. If the application can be installed, the system prompts the consumer to install the application on the target device. The consumer can initiate the continuation again after the installation.
- If the application to be continued has been installed on the target device, the system waits for a response to the continuation request for 20 seconds. If no response is received within 20 seconds, the caller receives a timeout error code, which means that the continuation fails.
2. By default, the system supports page stack information migration, which means that the page stack of the initiator will be automatically migrated to the target device. No adaptation is required.
### Restrictions
1. The continuation must be performed between the same ability, which means the same bundle name, module name, and ability name. For details, see [Application Package Structure Configuration File](../quick-start/stage-structure.md).
2. Currently, the application can only implement the continuation capability. The continuation action must be initiated by the system.
### Best Practice
For better user experience, you are advised to use the **wantParam** parameter to transmit data smaller than 100 KB and use distributed objects to transmit data larger than 100 KB.
# Ability Development # Ability Development
## When to Use ## When to Use
Ability development in the [stage model](stage-brief.md) is significantly different from that in the FA model. The stage model requires you to declare the application package structure in the `module.json` and `app.json` files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). To develop an ability based on the stage model, implement the following logic: Ability development in the [stage model](stage-brief.md) is significantly different from that in the FA model. The stage model requires you to declare the application package structure in the `module.json5` and `app.json5` files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). To develop an ability based on the stage model, implement the following logic:
- Create an ability that supports screen viewing and human-machine interaction. You must implement the following scenarios: ability lifecycle callbacks, obtaining ability configuration, requesting permissions, and notifying environment changes. - Create an ability that supports screen viewing and human-machine interaction. You must implement the following scenarios: ability lifecycle callbacks, obtaining ability configuration, requesting permissions, and notifying environment changes.
- Start an ability. You need to implement ability startup on the same device, on a remote device, or with a specified UI page. - Start an ability. You need to implement ability startup on the same device, on a remote device, or with a specified UI page.
- Call abilities. For details, see [Call Development](stage-call.md). - Call abilities. For details, see [Call Development](stage-call.md).
...@@ -8,7 +8,7 @@ Ability development in the [stage model](stage-brief.md) is significantly differ ...@@ -8,7 +8,7 @@ Ability development in the [stage model](stage-brief.md) is significantly differ
- Continue the ability on another device. For details, see [Ability Continuation Development](stage-ability-continuation.md). - Continue the ability on another device. For details, see [Ability Continuation Development](stage-ability-continuation.md).
### Launch Type ### Launch Type
An ability can be launched in the **standard**, **singleton**, or **specified** mode, as configured by `launchType` in the `module.json` file. Depending on the launch type, the action performed when the ability is started differs, as described below. An ability can be launched in the **standard**, **singleton**, or **specified** mode, as configured by `launchType` in the `module.json5` file. Depending on the launch type, the action performed when the ability is started differs, as described below.
| Launch Type | Description |Action | | Launch Type | Description |Action |
| ----------- | ------- |---------------- | | ----------- | ------- |---------------- |
...@@ -16,7 +16,7 @@ An ability can be launched in the **standard**, **singleton**, or **specified** ...@@ -16,7 +16,7 @@ An ability can be launched in the **standard**, **singleton**, or **specified**
| singleton | Singleton | The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.| | singleton | Singleton | The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.|
| specified | Instance-specific| The internal service of an ability determines whether to create multiple instances during running.| | specified | Instance-specific| The internal service of an ability determines whether to create multiple instances during running.|
By default, the singleton mode is used. The following is an example of the `module.json` file: By default, the singleton mode is used. The following is an example of the `module.json5` file:
```json ```json
{ {
"module": { "module": {
...@@ -42,6 +42,7 @@ The table below describes the APIs provided by the `AbilityStage` class, which h ...@@ -42,6 +42,7 @@ The table below describes the APIs provided by the `AbilityStage` class, which h
The table below describes the APIs provided by the `Ability` class. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md). The table below describes the APIs provided by the `Ability` class. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md).
**Table 2** Ability APIs **Table 2** Ability APIs
|API|Description| |API|Description|
|:------|:------| |:------|:------|
|onCreate(want: Want, param: AbilityConstant.LaunchParam): void|Called when an ability is created.| |onCreate(want: Want, param: AbilityConstant.LaunchParam): void|Called when an ability is created.|
...@@ -58,7 +59,7 @@ To create Page abilities for an application in the stage model, you must impleme ...@@ -58,7 +59,7 @@ To create Page abilities for an application in the stage model, you must impleme
``` ```
import AbilityStage from "@ohos.application.AbilityStage" import AbilityStage from "@ohos.application.AbilityStage"
``` ```
2. Implement the `AbilityStage` class. 2. Implement the `AbilityStage` class. The default relative path generated by the APIs is **entry\src\main\ets\Application\AbilityStage.ts**.
```ts ```ts
export default class MyAbilityStage extends AbilityStage { export default class MyAbilityStage extends AbilityStage {
onCreate() { onCreate() {
...@@ -70,9 +71,9 @@ To create Page abilities for an application in the stage model, you must impleme ...@@ -70,9 +71,9 @@ To create Page abilities for an application in the stage model, you must impleme
```js ```js
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
``` ```
4. Implement the lifecycle callbacks of the `Ability` class. 4. Implement the lifecycle callbacks of the `Ability` class. The default relative path generated by the APIs is **entry\src\main\ets\MainAbility\MainAbility.ts**.
In the `onWindowStageCreate(windowStage)` API, use `loadContent` to set the application page to be loaded. For details about how to use the `Window` APIs, see [Window Development](../windowmanager/window-guidelines.md). In the `onWindowStageCreate(windowStage)` API, use `loadContent` to set the application page to be loaded. For details about how to use the `Window` APIs, see [Window Development](../windowmanager/application-window-stage.md).
```ts ```ts
export default class MainAbility extends Ability { export default class MainAbility extends Ability {
onCreate(want, launchParam) { onCreate(want, launchParam) {
...@@ -86,8 +87,8 @@ To create Page abilities for an application in the stage model, you must impleme ...@@ -86,8 +87,8 @@ To create Page abilities for an application in the stage model, you must impleme
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
console.log("MainAbility onWindowStageCreate") console.log("MainAbility onWindowStageCreate")
windowStage.loadContent("pages/index").then((data) => { windowStage.loadContent("pages/index").then(() => {
console.log("MainAbility load content succeed with data: " + JSON.stringify(data)) console.log("MainAbility load content succeed")
}).catch((error) => { }).catch((error) => {
console.error("MainAbility load content failed with error: " + JSON.stringify(error)) console.error("MainAbility load content failed with error: " + JSON.stringify(error))
}) })
...@@ -107,7 +108,10 @@ To create Page abilities for an application in the stage model, you must impleme ...@@ -107,7 +108,10 @@ To create Page abilities for an application in the stage model, you must impleme
} }
``` ```
### Obtaining AbilityStage and Ability Configurations ### Obtaining AbilityStage and Ability Configurations
Both the `AbilityStage` and `Ability` classes have the `context` attribute. An application can obtain the context of an `Ability` instance through `this.context` to obtain the configuration details. The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the `context` attribute in the `AbilityStage` class. The sample code is as follows: Both the `AbilityStage` and `Ability` classes have the `context` attribute. An application can obtain the context of an `Ability` instance through `this.context` to obtain the configuration details.
The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the `context` attribute in the `AbilityStage` class. The sample code is as follows:
```ts ```ts
import AbilityStage from "@ohos.application.AbilityStage" import AbilityStage from "@ohos.application.AbilityStage"
export default class MyAbilityStage extends AbilityStage { export default class MyAbilityStage extends AbilityStage {
...@@ -140,14 +144,14 @@ export default class MainAbility extends Ability { ...@@ -140,14 +144,14 @@ export default class MainAbility extends Ability {
console.log("MainAbility ability name" + abilityInfo.name) console.log("MainAbility ability name" + abilityInfo.name)
let config = this.context.config let config = this.context.config
console.log("MyAbilityStage config language" + config.language) console.log("MainAbility config language" + config.language)
} }
} }
``` ```
### Requesting Permissions ### Requesting Permissions
If an application needs to obtain user privacy information or use system capabilities, for example, obtaining location information or using the camera to take photos or record videos, it must request the respective permission from consumers. During application development, you need to specify the involved sensitive permissions, declare the required permissions in `module.json`, and use the `requestPermissionsFromUser` API to request the permission from consumers in the form of a dialog box. The following uses the permission for calendar access as an example. If an application needs to obtain user privacy information or use system capabilities, for example, obtaining location information or using the camera to take photos or record videos, it must request the respective permission from consumers. During application development, you need to specify the involved sensitive permissions, declare the required permissions in `module.json5`, and use the `requestPermissionsFromUser` API to request the permission from consumers in the form of a dialog box. The following uses the permission for calendar access as an example.
Declare the required permission in the `module.json` file. Declare the required permission in the `module.json5` file.
```json ```json
"requestPermissions": [ "requestPermissions": [
{ {
...@@ -227,8 +231,8 @@ var want = { ...@@ -227,8 +231,8 @@ var want = {
"bundleName": "com.example.MyApplication", "bundleName": "com.example.MyApplication",
"abilityName": "MainAbility" "abilityName": "MainAbility"
}; };
context.startAbility(want).then((data) => { context.startAbility(want).then(() => {
console.log("Succeed to start ability with data: " + JSON.stringify(data)) console.log("Succeed to start ability")
}).catch((error) => { }).catch((error) => {
console.error("Failed to start ability with error: "+ JSON.stringify(error)) console.error("Failed to start ability with error: "+ JSON.stringify(error))
}) })
...@@ -244,8 +248,8 @@ var want = { ...@@ -244,8 +248,8 @@ var want = {
"bundleName": "com.example.MyApplication", "bundleName": "com.example.MyApplication",
"abilityName": "MainAbility" "abilityName": "MainAbility"
}; };
context.startAbility(want).then((data) => { context.startAbility(want).then(() => {
console.log("Succeed to start remote ability with data: " + JSON.stringify(data)) console.log("Succeed to start remote ability")
}).catch((error) => { }).catch((error) => {
console.error("Failed to start remote ability with error: " + JSON.stringify(error)) console.error("Failed to start remote ability with error: " + JSON.stringify(error))
}) })
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application. A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application.
A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message. A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message.
Basic concepts: Basic concepts:
...@@ -49,10 +49,10 @@ The **FormExtension** class also has a member context, that is, the **FormExtens ...@@ -49,10 +49,10 @@ The **FormExtension** class also has a member context, that is, the **FormExtens
**Table 2** FormExtensionContext APIs **Table 2** FormExtensionContext APIs
| API | Description | | API | Description |
| :----------------------------------------------------------- | :------------------------ | | :----------------------------------------------------------- | :----------------------------------------------------------- |
| updateForm(formId: string, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\<void>): void | Updates a widget. This API uses an asynchronous callback to return the result. | | startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void | Starts an ability. This API uses an asynchronous callback to return the result. (This is a system API and cannot be called by third-party applications.)|
| updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise\<void> | Updates a widget. This API uses a promise to return the result.| | startAbility(want: Want): Promise&lt;void&gt; | Starts an ability. This API uses a promise to return the result. (This is a system API and cannot be called by third-party applications.)|
For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md). For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md).
...@@ -86,7 +86,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo ...@@ -86,7 +86,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo
export default class FormAbility extends FormExtension { export default class FormAbility extends FormExtension {
onCreate(want) { onCreate(want) {
console.log('FormAbility onCreate'); console.log('FormAbility onCreate');
// Persistently store widget information for subsequent use, such as during widget instance retrieval or update. // Persistently store widget information for subsequent use, such as widget instance retrieval or update.
let obj = { let obj = {
"title": "titleOnCreate", "title": "titleOnCreate",
"detail": "detailOnCreate" "detail": "detailOnCreate"
...@@ -176,8 +176,8 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo ...@@ -176,8 +176,8 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo
| supportDimensions | Grid styles supported by the widget. Available values are as follows:<br>**1 * 2**: indicates a grid with one row and two columns.<br>**2 * 2**: indicates a grid with two rows and two columns.<br>**2 * 4**: indicates a grid with two rows and four columns.<br>**4 * 4**: indicates a grid with four rows and four columns.| String array| No | | supportDimensions | Grid styles supported by the widget. Available values are as follows:<br>**1 * 2**: indicates a grid with one row and two columns.<br>**2 * 2**: indicates a grid with two rows and two columns.<br>**2 * 4**: indicates a grid with two rows and four columns.<br>**4 * 4**: indicates a grid with four rows and four columns.| String array| No |
| defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No |
| updateEnabled | Whether the widget can be updated periodically. Available values are as follows:<br>**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is recommended.<br>**false**: The widget cannot be updated periodically.| Boolean | No | | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:<br>**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is recommended.<br>**false**: The widget cannot be updated periodically.| Boolean | No |
| scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.<br>This parameter has a lower priority than **updateDuration**. If both are specified, the value specified by **updateDuration** is used.| String | Yes (initial value: **0:0**) |
| updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.<br>If the value is **0**, this field does not take effect.<br>If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.<br>If the value is **0**, this field does not take effect.<br>If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.<br>This parameter has a higher priority than **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number | Yes (initial value: **0**) |
| formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | | formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) |
| formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) |
| metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) | | metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) |
...@@ -200,7 +200,6 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo ...@@ -200,7 +200,6 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo
"defaultDimension": "2*2", "defaultDimension": "2*2",
"updateEnabled": true, "updateEnabled": true,
"scheduledUpdateTime": "10:30", "scheduledUpdateTime": "10:30",
"updateDuration": 1,
"formConfigAbility": "ability://ohos.samples.FormApplication.MainAbility" "formConfigAbility": "ability://ohos.samples.FormApplication.MainAbility"
}] }]
} }
...@@ -218,8 +217,8 @@ Mostly, the widget provider is started only when it needs to obtain information ...@@ -218,8 +217,8 @@ Mostly, the widget provider is started only when it needs to obtain information
let formId = want.parameters["ohos.extra.param.key.form_identity"]; let formId = want.parameters["ohos.extra.param.key.form_identity"];
let formName = want.parameters["ohos.extra.param.key.form_name"]; let formName = want.parameters["ohos.extra.param.key.form_name"];
let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"];
// Persistently store widget data for subsequent use, such as widget instance retrieval and update. // Persistently store widget data for subsequent use, such as widget instance retrieval or update.
// The storeFormInfo API is not implemented here. For details about the implementation, see "Samples" below. // The storeFormInfo API is not implemented here.
storeFormInfo(formId, formName, tempFlag, want); storeFormInfo(formId, formName, tempFlag, want);
let obj = { let obj = {
...@@ -238,7 +237,7 @@ You should override **onDestroy** to delete widget data. ...@@ -238,7 +237,7 @@ You should override **onDestroy** to delete widget data.
console.log('FormAbility onDestroy'); console.log('FormAbility onDestroy');
// You need to implement the code for deleting the persistent widget data. // You need to implement the code for deleting the persistent widget data.
// The deleteFormInfo API is not implemented here. For details about the implementation, see "Samples" below. // The deleteFormInfo API is not implemented here.
deleteFormInfo(formId); deleteFormInfo(formId);
} }
``` ```
...@@ -277,10 +276,11 @@ onUpdate(formId) { ...@@ -277,10 +276,11 @@ onUpdate(formId) {
You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
>
> Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI. > Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI.
- hml: - In the HML file:
```html ```html
<div class="container"> <div class="container">
<stack> <stack>
...@@ -295,7 +295,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme ...@@ -295,7 +295,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
</div> </div>
``` ```
- css: - In the CSS file:
```css ```css
.container { .container {
...@@ -336,7 +336,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme ...@@ -336,7 +336,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
} }
``` ```
- json: - In the JSON file:
```json ```json
{ {
"data": { "data": {
...@@ -346,7 +346,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme ...@@ -346,7 +346,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
"actions": { "actions": {
"routerEvent": { "routerEvent": {
"action": "router", "action": "router",
"abilityName": "com.example.MyApplication.hmservice.FormAbility", "abilityName": "MainAbility",
"params": { "params": {
"message": "add detail" "message": "add detail"
} }
...@@ -358,3 +358,58 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme ...@@ -358,3 +358,58 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
Now you've got a widget shown below. Now you've got a widget shown below.
![fa-form-example](figures/fa-form-example.png) ![fa-form-example](figures/fa-form-example.png)
### Developing Widget Events
You can set router and message events for components on a widget. The router event applies to ability redirection, and the message event applies to custom click events. The key steps are as follows:
1. Set **onclick** in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file.
2. For the router event, set the following attributes:
- **action**: **"router"**.
- **abilityName**: target ability name, for example, **MainAbility**, which is the default main ability name in DevEco Studio for the stage model.
- **params**: custom parameters of the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the main ability in the stage model, you can obtain **want** and its **parameters** field.
3. For the message event, set the following attributes:
- **action**: **"message"**.
- **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onEvent**.
The following is an example:
- In the HML file:
```html
<div class="container">
<stack>
<div class="container-img">
<image src="/common/widget.png" class="bg-img"></image>
</div>
<div class="container-inner">
<text class="title" onclick="routerEvent">{{title}}</text>
<text class="detail_text" onclick="messageEvent">{{detail}}</text>
</div>
</stack>
</div>
```
- In the JSON file:
```json
{
"data": {
"title": "TitleDefault",
"detail": "TextDefault"
},
"actions": {
"routerEvent": {
"action": "router",
"abilityName": "MainAbility",
"params": {
"message": "add detail"
}
},
"messageEvent": {
"action": "message",
"params": {
"message": "add detail"
}
}
}
}
```
\ No newline at end of file
# Service Extension Ability Development # Service Extension Ability Development
## When to Use ## When to Use
**ExtensionAbility** is the base class of the new Extension component in the stage model. It is used to process missions without UIs. The lifecycle of an Extension ability is simple and does not involve foreground or background states. **ServiceExtensionAbility** is extended from **ExtensionAbility**. `ExtensionAbility` is the base class of the new Extension component in the stage model. It is used to process missions without UIs. The lifecycle of an Extension ability is simple and does not involve foreground or background states. `ServiceExtensionAbility` is extended from `ExtensionAbility`.
You can customize a class that inherits from **ServiceExtensionAbility** and override the lifecycle callbacks in the base class to perform service logic operations during the initialization, connection, and disconnection processes. You can customize a class that inherits from `ServiceExtensionAbility` and override the lifecycle callbacks in the base class to perform service logic operations during the initialization, connection, and disconnection processes.
## Available APIs ## Available APIs
**Table 1** ServiceExtensionAbility lifecycle APIs **Table 1** ServiceExtensionAbility lifecycle APIs
|API|Description| |API|Description|
|:------|:------| |:------|:------|
|onCreate(want: Want): void|Called for the initialization when **startAbility** or **connectAbility** is invoked for a given ability for the first time.| |onCreate(want: Want): void|Called for the initialization when `startAbility` or `connectAbility` is invoked for a given ability for the first time.|
|onRequest(want: Want, startId: number): void|Called each time **startAbility** is invoked for a given ability. The initial value of **startId** is **1**, and the value is incremented by one each time **startAbility** is invoked for that ability.| |onRequest(want: Want, startId: number): void|Called each time `startAbility` is invoked for a given ability. The initial value of `startId` is `1`, and the value is incremented by one each time `startAbility` is invoked for that ability.|
|onConnect(want: Want): rpc.RemoteObject|Called when **connectAbility** is invoked for a given ability. This callback is not invoked for repeated calling of **connectAbility** for a specific ability. However, it will be invoked unless **connectAbility** is called after the ability has been disconnected using **disconnectAbility**. The returned result is a **RemoteObject**.| |onConnect(want: Want): rpc.RemoteObject|Called when `connectAbility` is invoked for a given ability. This callback is not invoked for repeated calling of `connectAbility` for a specific ability. However, it will be invoked unless `connectAbility` is called after the ability has been disconnected using `disconnectAbility`. The returned result is a `RemoteObject`.|
|onDisconnect(want: Want): void|Called when **disconnectAbility** is called for a given ability. If the Extension ability is started by **connectAbility** and is not bound to other applications, the **onDestroy** callback will also be triggered to destroy the Extension ability.| |onDisconnect(want: Want): void|Called when `disconnectAbility` is called for a given ability. If the Extension ability is started by `connectAbility` and is not bound to other applications, the `onDestroy` callback will also be triggered to destroy the Extension ability.|
|onDestroy(): void|Called when **terminateSelf** is invoked to terminate the ability.| |onDestroy(): void|Called when `terminateSelf` is invoked to terminate the ability.|
## Constraints ## Constraints
...@@ -24,7 +24,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p ...@@ -24,7 +24,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p
## How to Develop ## How to Develop
1. Declare the Service Extension ability in the **module.json** file by setting its **type** attribute to **service**. The following is a configuration example of the **module.json** file: 1. Declare the Service Extension ability in the `module.json5` file by setting its `type` attribute to `service`. The following is a configuration example of the `module.json5` file:
```json ```json
...@@ -39,7 +39,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p ...@@ -39,7 +39,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p
``` ```
2. Customize a class that inherits from **ServiceExtensionAbility** in the .ts file in the directory where the Service Extension ability is defined (**entry\src\main\ets\ServiceExtAbility\ServiceExtAbility.ts** by default) and override the lifecycle callbacks of the base class. The code sample is as follows: 2. Customize a class that inherits from `ServiceExtensionAbility` in the .ts file in the directory where the Service Extension ability is defined (`entry\src\main\ets\ServiceExtAbility\ServiceExtAbility.ts` by default) and override the lifecycle callbacks of the base class. The code sample is as follows:
```js ```js
import ServiceExtensionAbility from '@ohos.application.ServiceExtensionAbility' import ServiceExtensionAbility from '@ohos.application.ServiceExtensionAbility'
......
...@@ -10,6 +10,8 @@ The HTTP request function is mainly implemented by the HTTP module. ...@@ -10,6 +10,8 @@ The HTTP request function is mainly implemented by the HTTP module.
To use related APIs, you must declare the **ohos.permission.INTERNET** permission. To use related APIs, you must declare the **ohos.permission.INTERNET** permission.
For details about how to apply for permissions, see [Access Control Development](../security/accesstoken-guidelines.md).
The following table describes the related APIs. The following table describes the related APIs.
| API | Description | | API | Description |
...@@ -65,7 +67,7 @@ httpRequest.request( ...@@ -65,7 +67,7 @@ httpRequest.request(
console.info('cookies:' + data.cookies); // 8+ console.info('cookies:' + data.cookies); // 8+
} else { } else {
console.info('error:' + JSON.stringify(err)); console.info('error:' + JSON.stringify(err));
// Call the destroy() method to release resources after the call is complete. // Call the destroy() method to destroy the request if it is no longer needed.
httpRequest.destroy(); httpRequest.destroy();
} }
} }
......
...@@ -74,7 +74,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -74,7 +74,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
console.log("on close") console.log("on close")
}); });
// Bind the IP address and port number. // Bind the local IP address and port number.
let bindAddress = { let bindAddress = {
address: '192.168.xx.xx', address: '192.168.xx.xx',
port: 1234, // Bound port, for example, 1234. port: 1234, // Bound port, for example, 1234.
......
# DataShare Development # DataShare Development
The **DataShare** module allows an application to manage its own data and share data with other applications. Currently, data can be shared only between the applications on the same device. The **DataShare** module allows an application to manage its own data and share data with other applications. Currently, data can be shared only between applications on the same device.
## Available APIs ## Available APIs
...@@ -29,10 +29,10 @@ For more details, see [DataShareHelper](../reference/apis/js-apis-data-dataShare ...@@ -29,10 +29,10 @@ For more details, see [DataShareHelper](../reference/apis/js-apis-data-dataShare
## When to Use ## When to Use
**DataShare** can be divided into the following: There are two roles in **DataShare**.
- Data provider: Implement functions of adding, deleting, modifying, and querying data, and opening files, and share data. - Data provider: adds, deletes, modifies, and queries data, opens files, and shares data.
- Data consumer: Access the data provided by the provider using **DataShareHelper**. - Data consumer: accesses the data provided by the provider using **DataShareHelper**.
Examples are given below. Examples are given below.
...@@ -47,7 +47,7 @@ Examples are given below. ...@@ -47,7 +47,7 @@ Examples are given below.
import dataSharePredicates from '@ohos.data.dataSharePredicates' import dataSharePredicates from '@ohos.data.dataSharePredicates'
``` ```
2. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only the query() API. 2. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only the **query()** API.
3. 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. 3. 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.
...@@ -107,9 +107,9 @@ Examples are given below. ...@@ -107,9 +107,9 @@ Examples are given below.
| Field| Description | | Field| Description |
| ------------ | ------------------------------------------------------------ | | ------------ | ------------------------------------------------------------ |
| "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | | "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. |
| "type" | Ability type. The value is **dataShare**, indicating the development is based on the **Datashare** template.| | "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template.|
| "uri" | URI used for communication. It is the unique identifier for the client to connect to the server. | | "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. |
| "visible" | Whether it is visible to other applications. Communication with other applications is allowed only when the value is **true**.| | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**.|
**module.json5 example** **module.json5 example**
...@@ -129,7 +129,7 @@ Examples are given below. ...@@ -129,7 +129,7 @@ Examples are given below.
### Data Consumer Application Development ### Data Consumer Application Development
1. Import basic dependencies. 1. Import the dependencies.
```ts ```ts
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
...@@ -175,7 +175,7 @@ Examples are given below. ...@@ -175,7 +175,7 @@ Examples are given below.
dsHelper.insert(dseUri, valuesBucket, (err,data) => { dsHelper.insert(dseUri, valuesBucket, (err,data) => {
console.log("dsHelper insert result: " + data); console.log("dsHelper insert result: " + data);
}); });
// Delete the specified data. // Delete data.
dsHelper.delete(dseUri, da, (err,data) => { dsHelper.delete(dseUri, da, (err,data) => {
console.log("dsHelper delete result: " + data); console.log("dsHelper delete result: " + data);
}); });
......
...@@ -2,9 +2,9 @@ ...@@ -2,9 +2,9 @@
## Introduction ## Introduction
The **DataShare** module allows an application to manage its own data and share data with other applications. Currently, data can be shared only between the applications on the same device. The **DataShare** module allows an application to manage its own data and share data with other applications. Currently, data can be shared only between applications on the same device.
**DataShare** is used in application scenarios, such as contacts, short message service (SMS), and media gallery. However, not all data, such as accounts and passwords, can be accessed by other applications. Some data, such as SMS messages, can only be queried by other applications. **DataShare** provides a secure data sharing mechanism for applications. Data needs to be shared in a wealth of scenarios. For example, contacts, short message service (SMS), and media gallery always needs to be shared. However, certain data, such as accounts and passwords, cannot be shared. Some data, such as SMS messages, can be queried but not modified by other applications. **DataShare** provides a secure data sharing mechanism for applications in a variety of scenarios.
The data provider can directly use the **DataShare** framework to share data with other applications without complex encapsulation. The data consumer only needs to learn and use a set of interfaces because the data access mode does not vary with the data provisioning mode. This greatly reduces the learning time and development difficulty. The data provider can directly use the **DataShare** framework to share data with other applications without complex encapsulation. The data consumer only needs to learn and use a set of interfaces because the data access mode does not vary with the data provisioning mode. This greatly reduces the learning time and development difficulty.
...@@ -45,7 +45,7 @@ Before you get started, familiarize yourself with the following concepts: ...@@ -45,7 +45,7 @@ Before you get started, familiarize yourself with the following concepts:
- The **DataShareHelper** module, as the data consumer, provides interfaces for accessing data, including adding, deleting, modifying, and querying data. - The **DataShareHelper** module, as the data consumer, provides interfaces for accessing data, including adding, deleting, modifying, and querying data.
- The data consumer communicates with the data provider using inter-process communication (IPC). The data provider can be implemented through a database or other data storage. - The data consumer communicates with the data provider using inter-process communication (IPC). The data provider can be implemented through a database or other data storage.
- The **ResultSet** module is implemented through shared memory. Share memory stores the result sets, and interfaces are provided to traverse result sets. - The **ResultSet** module is implemented through shared memory. Shared memory stores the result sets, and interfaces are provided to traverse result sets.
## Constraints ## Constraints
......
# Distributed Data Service Overview<a name="EN-US_TOPIC_0000001183067628"></a> # Distributed Data Service Overview
The distributed data service \(DDS\) implements distributed database collaboration across devices for applications. Applications save data to distributed databases by calling the DDS APIs. The DDS isolates data of different applications based on a triplet of account, application, and database to ensure secure data access. The DDS synchronizes application data between trusted devices to provide users with consistent data access experience on different devices. The distributed data service (DDS) implements distributed database collaboration across devices for applications.
## Basic Concepts<a name="section17506141102520"></a> Applications save data to distributed databases by calling the DDS APIs. The DDS isolates data of different applications based on a triplet of account, application, and database to ensure secure data access. The DDS synchronizes application data between trusted devices to provide users with consistent data access experience on different devices.
You do not need to care about the implementation of the database locking mechanism.
## Basic Concepts
- **KV data model** - **KV data model**
...@@ -54,7 +58,7 @@ The distributed data service \(DDS\) implements distributed database collaborati ...@@ -54,7 +58,7 @@ The distributed data service \(DDS\) implements distributed database collaborati
The DDS provides the database backup capability. You can set **backup** to **true** to enable daily backup. If a distributed database is damaged, the DDS deletes the database and restores the most recent data from the backup database. If no backup database is available, the DDS creates one. The DDS can also back up encrypted databases. The DDS provides the database backup capability. You can set **backup** to **true** to enable daily backup. If a distributed database is damaged, the DDS deletes the database and restores the most recent data from the backup database. If no backup database is available, the DDS creates one. The DDS can also back up encrypted databases.
## Working Principles<a name="section315111581616"></a> ## Working Principles
The DDS supports distributed management of application database data in the OpenHarmony system. Data can be synchronized between multiple devices with the same account, delivering a consistent user experience across devices. The DDS consists of the following: The DDS supports distributed management of application database data in the OpenHarmony system. Data can be synchronized between multiple devices with the same account, delivering a consistent user experience across devices. The DDS consists of the following:
...@@ -86,7 +90,7 @@ Applications call the DDS APIs to create, access, and subscribe to distributed d ...@@ -86,7 +90,7 @@ Applications call the DDS APIs to create, access, and subscribe to distributed d
![](figures/en-us_image_0000001183386164.png) ![](figures/en-us_image_0000001183386164.png)
## Constraints<a name="section95382010203311"></a> ## Constraints
- The DDS supports the KV data model only. It does not support foreign keys or triggers of the relational database. - The DDS supports the KV data model only. It does not support foreign keys or triggers of the relational database.
- The KV data model specifications supported by the DDS are as follows: - The KV data model specifications supported by the DDS are as follows:
......
...@@ -2,45 +2,48 @@ ...@@ -2,45 +2,48 @@
> **NOTE** > **NOTE**
> >
> This feature is supported since API Version 9. For the versions earlier than API Version 9, use [Lightweight Storage](../reference/apis/js-apis-data-storage.md) APIs. > This feature is supported since API Version 9. For the versions earlier than API version 9, use [Lightweight Storage](../reference/apis/js-apis-data-storage.md) APIs.
## When to Use ## When to Use
Preferences are ideal for storing data frequently used by applications, but not for storing a large amount of data or data with frequent changes. The application data is persistently stored on a device in the form of files. Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can perform data operations using the **Preferences** APIs. Preferences are used for storing the data that is frequently used by applications, but not for storing a large amount of data or data frequently changed. The application data is persistently stored on a device in the form of files.
## Available APIs Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can call the **Preferences** APIs to manage data.
Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type. For more APIs related to preferences, see [Preferences](../reference/apis/js-apis-data-preferences.md). ## Available APIs
### Creating a Preferences Instance The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs and supports persistence of the KV pairs when required.
Create a **Preferences** instance for data operations. A **Preferences** instance is created after data is read from a specified file and loaded to the instance. The key is of the string type, and the value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.
**Table 1** API for creating a **Preferences** instance For details about **Preferences** APIs, see [Preferences](../reference/apis/js-apis-data-preferences.md).
| Package | API | Description | ### Obtaining a **Preferences** Instance
| ----------------- | ------------------------------------------- | ------------------------------------------- |
| ohos.data.preferences | getPreferences(context: Context, name: string): Promise\<Preferences> | Obtains a **Preferences** instance for data operations.|
### Writing Data Obtain a **Preferences** instance for data operations. A **Preferences** instance is obtained after data is read from a specified file and loaded to the instance.
Call the **put()** method to add or modify data in a **Preferences** instance. **Table 1** API for obtaining a **Preferences** instance
**Table 2** API for writing data | Package | API | Description |
| --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ohos.data.preferences | getPreferences(context: Context, name: string): Promise\<Preferences> | Obtains a **Preferences** instance.|
| Class | API | Description | ### Accessing Data
| ------- | -------------------------------------------------- | ----------------------------------------------- |
| Preferences | put(key: string, value: ValueType): Promise\<void> | Writes data with the value type of number, string, boolean, Array\<number>, Array\<string>, or Array\<boolean>.|
### Reading Data Call the **put()** method to add or modify data in a **Preferences** instance.
Call the **get()** method to read data from a **Preferences** instance. Call the **get()** method to read data from a **Preferences** instance.
**Table 3** API for reading data Call **getAll()** to obtain an **Object** instance that contains all KV pairs in a **Preferences** instance.
**Table 2** APIs for accessing **Preferences** data
| Class | API | Description |
| ----------- | ---------------------------------------------------------- | ------------------------------------------------------------ |
| Preferences | put(key: string, value: ValueType): Promise\<void> | Writes data to the **Preferences** instance. The value to write can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.|
| Preferences | get(key: string, defValue: ValueType): Promise\<ValueType> | Obtains data from the **Preferences** instance. The value to read can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.|
| Preferences | getAll(): Promise<Object> | Obtains an **Object** instance that contains all KV pairs in the **Preferences** instance. |
| Class | API | Description |
| ------- | ---------------------------------------------------------- | ----------------------------------------------- |
| Preferences | get(key: string, defValue: ValueType): Promise\<ValueType> | Obtains data with the value type of number, string, boolean, Array\<number>, Array\<string>, or Array\<boolean>.|
### Storing Data Persistently ### Storing Data Persistently
...@@ -48,18 +51,18 @@ Call the **flush()** method to write the cached data back to its text file for p ...@@ -48,18 +51,18 @@ Call the **flush()** method to write the cached data back to its text file for p
**Table 4** API for data persistence **Table 4** API for data persistence
| Class | API | Description | | Class | API | Description |
| ------- | ----------------------- | --------------------------------------- | | ----------- | ----------------------- | ------------------------------------------- |
| Preferences | flush(): Promise\<void> | Writes data from the **Preferences** instance back to its file through an asynchronous thread.| | Preferences | flush(): Promise\<void> | Flushes data from the **Preferences** instance to its file through an asynchronous thread.|
### Observing Data Changes ### Observing Data Changes
You can subscribe to data changes. When the value of the subscribed key is changed by **flush()**, a callback will be invoked to return the new data. You can subscribe to data changes. When the value of the subscribed key is changed and saved by **flush()**, a callback will be invoked to return the new data.
**Table 5** APIs for observing **Preferences** changes **Table 5** APIs for observing **Preferences** changes
| Class | API | Description | | Class | API | Description |
| ------- | ------------------------------------------------------------ | -------------- | | ----------- | ------------------------------------------------------------ | -------------- |
| Preferences | on(type: 'change', callback: Callback<{ key : string }>): void | Subscribes to data changes.| | Preferences | on(type: 'change', callback: Callback<{ key : string }>): void | Subscribes to data changes.|
| Preferences | off(type: 'change', callback: Callback<{ key : string }>): void | Unsubscribes from data changes. | | Preferences | off(type: 'change', callback: Callback<{ key : string }>): void | Unsubscribes from data changes. |
...@@ -69,57 +72,58 @@ Use the following APIs to delete a **Preferences** instance or data file. ...@@ -69,57 +72,58 @@ Use the following APIs to delete a **Preferences** instance or data file.
**Table 6** APIs for deleting **Preferences** **Table 6** APIs for deleting **Preferences**
| Package | API | Description | | Package | API | Description |
| ----------------- | ---------------------------------------------------- | ------------------------------------------------------------ | | --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ohos.data.preferences | deletePreferences(context: Context, name: string): Promise\<void>; | Deletes a **Preferences** instance from the cache and deletes its file from the device.| | ohos.data.preferences | deletePreferences(context: Context, name: string): Promise\<void> | Deletes a **Preferences** instance from the memory and its files from the device.|
| ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\<void>; | Removes a **Preferences** instance from the memory to release memory. | ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\<void> | Removes a **Preferences** instance from the memory to release memory. |
## How to Develop ## How to Develop
1. Import @ohos.data.preferences and related modules to the development environment. 1. Import @ohos.data.preferences and related modules to the development environment.
```js ```js
import data_preferences from '@ohos.data.preferences' import data_preferences from '@ohos.data.preferences';
``` ```
2. Create a **Preferences** instance. 2. Obtain a **Preferences** instance.
Read the specified file and load its data to the **Preferences** instance for data operations. Read the specified file and load its data to the **Preferences** instance for data operations.
```js ```js
let promise = data_preferences.getPreferences(this.context, 'mystore') let promise = data_preferences.getPreferences(this.context, 'mystore');
``` ```
3. Write data. 3. Write data.
Use the **put()** method of the **Preferences** class to write data to the cached **Preferences** instance. Use the **preferences.put()** method to write data to the **Preferences** instance.
```js ```js
promise.then((preferences) => { promise.then((preferences) => {
let putPromise = preferences.put('startup', 'auto') let putPromise = preferences.put('startup', 'auto');
putPromise.then(() => { putPromise.then(() => {
console.info("Put the value of startup successfully.") console.info("Put the value of 'startup' successfully.");
}).catch((err) => { }).catch((err) => {
console.info("Failed to put the value of startup with err: " + err) console.info("Failed to put the value of 'startup'. Cause: " + err);
}) })
}).catch((err) => { }).catch((err) => {
console.info("Failed to get the preferences") console.info("Failed to get the preferences.");
}) })
``` ```
4. Read data. 4. Read data.
Use the **get()** method of the **Preferences** class to read data. Use the **preferences.get()** method to read data.
```js ```js
promise.then((preferences) => { promise.then((preferences) => {
let getPromise = preferences.get('startup', 'default') let getPromise = preferences.get('startup', 'default');
getPromise.then((value) => { getPromise.then((value) => {
console.info("The value of startup is " + value) console.info("The value of 'startup' is " + value);
}).catch((err) => { }).catch((err) => {
console.info("Failed to get the value of startup with err: " + err) console.info("Failed to get the value of 'startup'. Cause: " + err);
}) })
}).catch((err) => { }).catch((err) => {
console.info("Failed to get the preferences")}) console.info("Failed to get the preferences.")
});
``` ```
5. Store data persistently. 5. Store data persistently.
...@@ -132,38 +136,38 @@ Use the following APIs to delete a **Preferences** instance or data file. ...@@ -132,38 +136,38 @@ Use the following APIs to delete a **Preferences** instance or data file.
6. Observe data changes. 6. Observe data changes.
Specify an observer as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and the **flush()** method is executed, the observe callback will be invoked to return the change. Specify an observer as the callback to subscribe to 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.
```js ```js
var observer = function (key) { var observer = function (key) {
console.info("The key of " + key + " changed.") console.info("The key" + key + " changed.");
} }
preferences.on('change', observer) preferences.on('change', observer);
preferences.put('startup', 'auto', function (err) { preferences.put('startup', 'auto', function (err) {
if (err) { if (err) {
console.info("Failed to put the value of startup with err: " + err) console.info("Failed to put the value of 'startup'. Cause: " + err);
return return;
} }
console.info("Put the value of startup successfully.") console.info("Put the value of 'startup' successfully.");
preferences.flush(function (err) { preferences.flush(function (err) {
if (err) { if (err) {
console.info("Failed to flush data to file with err: " + err) console.info("Failed to flush data. Cause: " + err);
return return;
} }
console.info("Flushed to file successfully.") // Observer will be called. console.info("Flushed data successfully."); // The observer will be called.
}) })
}) })
``` ```
7. Delete the specified file. 7. Delete the specified file.
Use the **deletePreferences** method to delete the **Preferences** singleton of the specified file from the memory, and delete the specified file, its backup file, and corrupted files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will occur. The deleted data and files cannot be restored. Use the **deletePreferences** method to delete the **Preferences** instance and its persistent file and backup and corrupted files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will be caused. The deleted data and files cannot be restored.
```js ```js
let proDelete = data_preferences.deletePreferences(context, 'mystore') let proDelete = data_preferences.deletePreferences(context, 'mystore');
proDelete.then(() => { proDelete.then(() => {
console.info("Data deleted successfully.") console.info("Deleted data successfully.");
}).catch((err) => { }).catch((err) => {
console.info("Failed to delete data with err: " + err) console.info("Failed to delete data. Cause: " + err);
}) })
``` ```
# Preferences Overview # Preferences Overview
Preferences are used for access and persistence operations on the data in the key-value structure. When an application accesses a **Preferences** instance, the data in the instance will be cached in the memory for faster access. The cached data can also be written back to the text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing persistent files. Preferences are used to implement quick access and persistence of the data in the `key-value` structure.
After an application obtains a **Preferences** instance, the data in the instance will be cached in the memory for faster access.
The cached data can also be written to a text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing files.
You do not need to care about the implementation of the database locking mechanism.
## Basic Concepts ## Basic Concepts
- **Key-value data structure** - **Key-value structure**
A type of data structure. The key is the unique identifier for a piece of data, and the value is the specific data being identified. A type of data structure. The `Key` is the unique identifier for a piece of data, and the `Value` is the specific data being identified.
- **Non-relational database** - **Non-relational database**
A database not in compliance with the atomicity, consistency, isolation, and durability (ACID) database management properties of relational data transactions. The data in a non-relational database is independent. A database not in compliance with the atomicity, consistency, isolation, and durability (ACID) properties of relational data transactions. The data in a non-relational database is independent. The database that organizes data in the `key-value` structure is a non-relational database.
## Working Principles ## Working Principles
When an application loads data from a **Preferences** file to a **Preferences** instance, the system stores the instance in the memory through a static container. Each file of an application or process has only one **Preferences** instance in the memory, till the application removes the instance from the memory or deletes the **Preferences** file. 1. An application can load data from a **Preferences** persistent file to a **Preferences** instance. The system stores the **Preferences** instance in the memory through a static container. Each file of an application or process has only one **Preferences** instance in the memory, till the application removes the instance from the memory or deletes the **Preferences** persistent file.
2. When obtaining a **Preferences** instance, the application can read data from or write data to the instance. The data in the `Preferences` instance can be flushed to its **Preferences** persistent file by calling the **flush()** method.
When obtaining a **Preferences** instance, the application can read data from or write data to the instance. The data in the instance can be flushed to its **Preferences** file by calling the **flush()** method.
**Figure 1** How **Preferences** work **Figure 1** Working mechanism
![](figures/preferences.png) ![](figures/preferences.png)
## Constraints ## Constraints
- **Preferences** instances are loaded to the memory. To minimize non-memory overhead, the number of data records stored in a **Preferences** instance cannot exceed 10,000. Delete the instances that are no longer used in a timely manner. - **Preferences** instances are loaded to the memory. To minimize non-memory overhead, the number of data records stored in a **Preferences** instance cannot exceed 10,000. Delete the instances that are no longer used in a timely manner.
- The key in key-value pairs is of the string type. It cannot be empty or exceed 80 bytes. - The `Key` in key-value pairs is of the string type. It cannot be empty or exceed 80 bytes.
- The value of the string type in key-value pairs can be empty, but cannot exceed 8192 bytes if not empty. - The `Value` of the string type in key-value pairs can be empty, but cannot exceed 8192 bytes if not empty.
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements.
You do not need to care about the implementation of the database locking mechanism.
## Basic concepts ## Basic concepts
- **RDB** - **RDB**
......
...@@ -4,7 +4,7 @@ With device usage statistics APIs, you can have a better understanding of the ap ...@@ -4,7 +4,7 @@ With device usage statistics APIs, you can have a better understanding of the ap
## Introduction ## Introduction
Currently you can have access to statistics on the application usage, and notification and system usage statistics feature will be available for use in later versions. Currently you can have access to statistics on the application usage, and the notification and system usage statistics feature will be available for use in later versions.
- **The application usage statistics is updated**: - **The application usage statistics is updated**:
1. Every 30 minutes 1. Every 30 minutes
...@@ -21,7 +21,7 @@ Currently you can have access to statistics on the application usage, and notifi ...@@ -21,7 +21,7 @@ Currently you can have access to statistics on the application usage, and notifi
7. Number of FA usage records specified by **maxNum**, sorted by time (most recent first). If **maxNum** is not specified, the default value **1000** will be used. 7. Number of FA usage records specified by **maxNum**, sorted by time (most recent first). If **maxNum** is not specified, the default value **1000** will be used.
8. Number of notifications from applications based on the specified start time and end time 8. Number of notifications from applications based on the specified start time and end time
9. Statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time 9. Statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time
9. Priority group of the invoker application or a specified application 10. Priority group of the invoker application or a specified application
- **The setters can be used to:** - **The setters can be used to:**
......
...@@ -20,7 +20,7 @@ The following table describes APIs available for obtaining device location infor ...@@ -20,7 +20,7 @@ The following table describes APIs available for obtaining device location infor
| off(type: 'locationChange', callback?: Callback&lt;Location&gt;) : void | Unregisters the listener for location changes with the corresponding location request deleted. | | off(type: 'locationChange', callback?: Callback&lt;Location&gt;) : void | Unregisters the listener for location changes with the corresponding location request deleted. |
| on(type: 'locationServiceState', callback: Callback&lt;boolean&gt;) : void | Registers a listener for location service status change events. | | on(type: 'locationServiceState', callback: Callback&lt;boolean&gt;) : void | Registers a listener for location service status change events. |
| off(type: 'locationServiceState', callback: Callback&lt;boolean&gt;) : void | Unregisters the listener for location service status change events. | | off(type: 'locationServiceState', callback: Callback&lt;boolean&gt;) : void | Unregisters the listener for location service status change events. |
| on(type: 'cachedGnssLocationsReporting', request: CachedGnssLoactionsRequest, callback: Callback&lt;Array&lt;Location&gt;&gt;) : void; | Registers a listener for cached GNSS location reports. | | on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback&lt;Array&lt;Location&gt;&gt;) : void; | Registers a listener for cached GNSS location reports. |
| off(type: 'cachedGnssLocationsReporting', callback?: Callback&lt;Array&lt;Location&gt;&gt;) : void; | Unregisters the listener for cached GNSS location reports. | | off(type: 'cachedGnssLocationsReporting', callback?: Callback&lt;Array&lt;Location&gt;&gt;) : void; | Unregisters the listener for cached GNSS location reports. |
| on(type: 'gnssStatusChange', callback: Callback&lt;SatelliteStatusInfo&gt;) : void; | Registers a listener for satellite status change events. | | on(type: 'gnssStatusChange', callback: Callback&lt;SatelliteStatusInfo&gt;) : void; | Registers a listener for satellite status change events. |
| off(type: 'gnssStatusChange', callback?: Callback&lt;SatelliteStatusInfo&gt;) : void; | Unregisters the listener for satellite status change events. | | off(type: 'gnssStatusChange', callback?: Callback&lt;SatelliteStatusInfo&gt;) : void; | Unregisters the listener for satellite status change events. |
......
...@@ -37,3 +37,9 @@ Location awareness is offered by the system as a basic service for applications. ...@@ -37,3 +37,9 @@ Location awareness is offered by the system as a basic service for applications.
Your application can use the location function only after the user has granted the permission and turned on the function. If the location function is off, the system will not provide the location service for any application. Your application can use the location function only after the user has granted the permission and turned on the function. If the location function is off, the system will not provide the location service for any application.
Since the location information is considered sensitive, your application still needs to obtain the location access permission from the user even if the user has turned on the location function. The system will provide the location service for your application only after it has been granted the permission to access the device location information. Since the location information is considered sensitive, your application still needs to obtain the location access permission from the user even if the user has turned on the location function. The system will provide the location service for your application only after it has been granted the permission to access the device location information.
## Samples
The following sample is provided to help you better understand how to develop location services:
-[`Location`: Location (eTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Location)
# USB Service Development # USB Service Development
The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management.
## When to Use ## When to Use
In Host mode, you can obtain the list of connected devices, enable or disable the devices, manage device access permissions, and perform data transfer or control transfer. In Host mode, you can obtain the list of connected devices, enable or disable the devices, manage device access permissions, and perform data transfer or control transfer.
## APIs ## APIs
The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management.
The following table lists the USB APIs currently available. For details, see the [API Reference](../reference/apis/js-apis-usb.md). The following table lists the USB APIs currently available. For details, see the [API Reference](../reference/apis/js-apis-usb.md).
**Table 1** Open USB APIs **Table 1** Open USB APIs
...@@ -21,7 +21,7 @@ The following table lists the USB APIs currently available. For details, see the ...@@ -21,7 +21,7 @@ The following table lists the USB APIs currently available. For details, see the
| setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. | | setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. |
| setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. | | setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. |
| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number | Claims a USB interface | | claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number | Claims a USB interface |
| bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise\<number> | Performs bulk transfer. | | bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise\<number> | Performs bulk transfer. |
| closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. | | closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. |
| releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. | | releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. |
| getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. | | getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. |
......
...@@ -2,89 +2,164 @@ ...@@ -2,89 +2,164 @@
## When to Use ## When to Use
The event logging function helps applications to log various information generated during running. The event logging function helps applications log various information generated during running.
## Available APIs ## Available APIs
JS application event logging APIs are provided by the **hiAppEvent** module. JS application event logging APIs are provided by the **hiAppEvent** module.
**Table 1** APIs for event logging The following table provides only a brief description of related APIs. For details, see [HiAppEvent](../reference/apis/js-apis-hiappevent.md).
| API | Return Value | Description | **Table 1** APIs for application event logging
| ------------------------------------------------------------ | -------------- | ------------------------------------------------------------ |
| write(string eventName, EventType type, object keyValues, AsyncCallback\<void> callback): void | void | Logs application events in asynchronous mode. This method uses an asynchronous callback to return the result. |
| write(string eventName, EventType type, object keyValues): Promise\<void> | Promise\<void> | Logs application events in asynchronous mode. This method uses a promise to return the result. |
When an asynchronous callback is used, the return value can be processed directly in the callback. When a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Event Verification Result Codes](#event-verification-result-codes). | API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| write(string eventName, EventType type, object keyValues, AsyncCallback\<void> callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result. |
| write(string eventName, EventType type, object keyValues): Promise\<void> | Logs application events in asynchronous mode. This API uses a promise to return the result. |
| write(AppEventInfo info, AsyncCallback\<void> callback): void | Logs application events by domain in asynchronous mode. This API uses an asynchronous callback to return the result.|
| write(AppEventInfo info): Promise\<void> | Logs application events by domain in asynchronous mode. This API uses a promise to return the result.|
**Table 2** APIs for event logging configuration When an asynchronous callback is used, the return value can be processed directly in the callback.
| API | Return Value | Description | If a promise is used, the return value can also be processed in the promise in a similar way.
| ------------------------------ | ------------ | ------------------------------------------------------------ |
| configure(ConfigOption config) | boolean | Sets the configuration options for application event logging.<br>The value **true** indicates that the operation is successful, and value **false** indicates the opposite. |
## Event Verification Result Codes For details about the result codes, see [Event Verification Result Codes](#event-verification-result-codes).
| Result Code | Cause | Check Rule | Processing Method | **Table 2** APIs for event logging configuration
| ----------- | ---------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| 0 | None | Event verification is successful. | Event logging is normal. No action is required. |
| -1 | Invalid event name | The event name is not empty and contains a maximum of 48 characters.<br/>The event name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore (\_).<br/>The event name does not start with a digit or underscore (_). | Ignore this event and do not perform logging. |
| -2 | Invalid event parameter type | The event name must be a string.<br/>The event type must be a number.<br/>The key value must be an object. | Ignore this event and do not perform logging. |
| -99 | Application event logging disabled | The application event logging function is disabled. | Ignore this event and do not perform logging. |
| -100 | Unknown error | None | Ignore this event and do not perform logging. |
| 1 | Invalid key name | The key name is not empty and contains a maximum of 16 characters.<br/>The key name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore (\_).<br/>The key name does not start with a digit or underscore (\_).<br/>The key name does not end with an underscore (_). | Ignore the key-value pair and continue to perform logging. |
| 2 | Invalid key type | The key must be a string. | Ignore the key-value pair and continue to perform logging. |
| 3 | Invalid value type | The supported value types vary depending on the programming language:<br/>boolean, number, string, or Array [basic element] | Ignore the key-value pair and continue to perform logging. |
| 4 | Value too long | The value can contain a maximum of 8*1024 characters. | Ignore the key-value pair and continue to perform logging. |
| 5 | Excess key-value pairs | The number of key-value pairs must be less than or equal to 32. | Ignore the excess key-value pairs and continue to perform logging. |
| 6 | Excess elements in a list value | The number of elements in a list value must be less than or equal to 100. | Truncate the list with only the first 100 elements retained, and continue to perform logging. |
| 7 | Invalid list value | A list value can only be a basic element.<br/>The elements in a list value must be of the same type. | Ignore the key-value pair and continue to perform logging. |
| API | Description |
| --------------------------------------- | ---------------------------------------------------- |
| configure(ConfigOption config): boolean | Sets the configuration options for application event logging.|
## How to Develop **Table 3** APIs for watcher management
In this example, an application event is logged after the application startup execution page is loaded. | API | Description |
| -------------------------------------------------- | -------------------- |
| addWatcher(Watcher watcher): AppEventPackageHolder | Adds an event watcher.|
| removeWatcher(Watcher watcher): void | Removes an event watcher.|
1. Create a JS application project. In the displayed Project window, choose **entry > src > main** > **js** > **default** > **pages > index**, and double-click index.js. Add the code to log the initial application event after page loading. The sample code is as follows: **Table 4** APIs for clearing logging data
```js | API | Description |
import hiAppEvent from '@ohos.hiAppEvent' | ----------------- | -------------------- |
| clearData(): void | Clears local logging data.|
### Event Verification Result Codes
| Result Code| Cause | Verification Rules | Handling Method |
| ------ | ----------------------------- | ------------------------------------------------------------ | ---------------------------------------------------------- |
| 0 | N/A | Event verification is successful. | Event logging is normal. No action is required. |
| -1 | Invalid event name | The name is not empty and contains a maximum of 48 characters.<br>The name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore \(_).<br>The name does not start with a digit or underscore \(_).| Ignore this event and do not perform logging. |
| -2 | Invalid event parameter type | The event name must be a string.<br>The event type must be a number.<br>The event parameter must be an object.| Ignore this event and do not perform logging. |
| -4 | Invalid event domain name | The name is not empty and contains a maximum of 32 characters.<br>The name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore \(_).<br>The name does not start with a digit or underscore \(_).| Ignore this event and do not perform logging. |
| -99 | Application event logging disabled | Application event logging is disabled. | Ignore this event and do not perform logging. |
| -100 | Unknown error | None. | Ignore this event and do not perform logging. |
| 1 | Invalid key name | The name is not empty and contains a maximum of 16 characters.<br>The name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore \(_).<br>The name does not start with a digit or underscore \(_).<br>The name does not end with an underscore \(_).| Ignore the key-value pair and continue to perform logging. |
| 2 | Invalid key type | The key must be a string. | Ignore the key-value pair and continue to perform logging. |
| 3 | Invalid value type | The supported value types vary depending on the programming language:<br>boolean, number, string, or Array [basic element]| Ignore the key-value pair and continue to perform logging. |
| 4 | Invalid length for values of the string type| For a value of the string type, the maximum length is 8*1024 characters. | Truncate the value with the first 8*1024 characters retained, and continue to perform logging.|
| 5 | Excess key-value pairs | The number of key-value pairs must be less than or equal to 32. | Ignore the excess key-value pairs and continue to perform logging. |
| 6 | Invalid number of elements in values of the array type | For a value of the array type, the number of elements must be less than or equal to 100. | Truncate the array with the first 100 elements retained, and continue to perform logging. |
| 7 | Invalid parameters in values of the array type | For a value of the array type, all the parameters must be of the same type, which can only be boolean, number, or string.| Ignore the key-value pair and continue to perform logging. |
## Development Procedure
The following uses a one-time event watcher as an example to illustrate the development procedure.
1. Create an eTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index.ets**, and double-click **index.ets**. Then, add three buttons to simulate the process of watching for application events. Wherein, button 1 is used to invoke application event logging, button 2 to add an event watcher that automatically triggers a callback, and button 3 to remove the watcher. The complete sample code is as follows:
```ts
import hiAppEvent from '@ohos.hiAppEvent';
export default { @Entry
data: { @Component
title: "" struct Index {
}, @State message: string = 'Hello World'
onInit() {
this.title = this.$t('strings.world');
// 1. Callback mode build() {
hiAppEvent.write("start_event", hiAppEvent.EventType.BEHAVIOR, {"int_data":100, "str_data":"strValue"}, (err, value) => { Row() {
if (err) { Column() {
console.error(`failed to write event because ${err.code}`); Text(this.message)
return; .fontSize(50)
.fontWeight(FontWeight.Bold)
Button("1 writeTest").onClick(()=>{
hiAppEvent.write({
domain: "test_domain",
name: "test_event",
eventType: hiAppEvent.EventType.FAULT,
params: {
int_data: 100,
str_data: "strValue"
} }
console.log(`success to write event: ${value}`); }).then((value) => {
}); console.log(`HiAppEvent success to write event: ${value}`);
}).catch((err) => {
console.error(`HiAppEvent failed to write event because ${err.code}`);
});
})
// 2. Promise mode Button("2 addWatcherTest").onClick(()=>{
hiAppEvent.write("start_event", hiAppEvent.EventType.BEHAVIOR, {"int_data":100, "str_data":"strValue"}) hiAppEvent.addWatcher({
.then((value) => { name: "watcher1",
console.log(`success to write event: ${value}`); appEventFilters: [{ domain: "test_domain" }],
}).catch((err) => { triggerCondition: {
console.error(`failed to write event because ${err.code}`); row: 2,
}); size: 1000,
timeOut: 2
// 3. Set the application event logging switch. },
hiAppEvent.configure({ onTrigger: function (curRow, curSize, holder) {
disable: true if (holder == null) {
}); console.error("HiAppEvent holder is null");
return;
}
let eventPkg = null;
while ((eventPkg = holder.takeNext()) != null) {
console.info("HiAppEvent eventPkg.packageId=" + eventPkg.packageId);
console.info("HiAppEvent eventPkg.row=" + eventPkg.row);
console.info("HiAppEvent eventPkg.size=" + eventPkg.size);
for (const eventInfo of eventPkg.data) {
console.info("HiAppEvent eventPkg.data=" + eventInfo);
}
}
}
});
})
// 4. Set the maximum size of the event file storage directory. The default value is 10M. Button("3 removeWatcherTest").onClick(()=>{
hiAppEvent.configure({ hiAppEvent.removeWatcher({
maxStorage: '100M' name: "watcher1"
}); })
})
}
.width('100%')
} }
.height('100%')
}
} }
``` ```
2. Tap the run button on the application UI to run the project. 2. Touch the run button on the IDE to run the project.
3. Touch button 1 on the application UI to start application event logging. If the logging is successful, you'll see the following message in the **Log** window:
```
success to write event: 0
```
4. On the application UI, touch button 2 to add an event watcher, and touch button 1 for multiple times to perform application event logging. If any callback trigger condition (event count, event data size, and timeout duration) is met, the event watcher will invoke a callback and the event package obtained through the callback will be displayed in the **Log** window.
```
HiAppEvent eventPkg.packageId=0
HiAppEvent eventPkg.row=2
HiAppEvent eventPkg.size=308
HiAppEvent eventPkg.data={"domain_":"test_domain","name_":"test_event","type_":1,"time_":1502096107556,"tz_":"+0000","pid_":4204,"tid_":4223,"int_data":100,"str_data":"strValue"}
```
5. On the application UI, touch button 3 to remove the event watcher. Then, touch button 1 for multiple times to perform application event logging. In such a case, there will be no log information about the callback invoked by the event watcher.
## Samples
The following sample is provided to help you better understand how to develop the application event logging feature:
- [`JsDotTest` (JS) (API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/DFX/JsDotTest)
...@@ -2,10 +2,10 @@ ...@@ -2,10 +2,10 @@
HiAppEvent provides event logging APIs for applications to log the fault, statistical, security, and user behavior events reported during running. Based on event information, you will be able to analyze the running status of your application. HiAppEvent provides event logging APIs for applications to log the fault, statistical, security, and user behavior events reported during running. Based on event information, you will be able to analyze the running status of your application.
The HiAppEvent module of OpenHarmony can be used to develop application event services and provide functions related to application events, including flushing application events to a disk and querying historical application event data. The HiAppEvent module can be used to develop application event-related functions, including flushing application events to a disk and querying historical application events.
## Basic Concepts ## Basic Concepts
- **Logging** **Logging**
Logs changes caused by user operations to provide service data for development, product, and O&M analysis. A function that logs changes caused by user operations to provide service data for development, product, and O&M analysis.
\ No newline at end of file
# Internationalization Development (I18N) # Internationalization Development (I18N)
This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N interfaces that are not defined in ECMA 402. This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. For more details about APIs and their usage, see [I18N](../reference/apis/js-apis-i18n.md).
The [Intl](intl-guidelines.md) module provides basic I18N capabilities through the standard I18N interfaces defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities.
## Obtaining System Language and Region Information ## Obtaining System Language and Region Information
...@@ -90,7 +89,7 @@ You can use APIs provided in the following table to obtain the system language a ...@@ -90,7 +89,7 @@ You can use APIs provided in the following table to obtain the system language a
## Obtaining Calendar Information ## Obtaining Calendar Information
[Calendar](../reference/apis/js-apis-intl.md) APIs are used to obtain calendar information, for example, the localized display of the calendar, the first day of a week, and the minimum count of days in the first week of a year. [Calendar](../reference/apis/js-apis-i18n.md#calendar8) APIs are used to obtain calendar information, for example, the localized display of the calendar, the first day of a week, and the minimum count of days in the first week of a year.
### Available APIs ### Available APIs
...@@ -119,7 +118,7 @@ You can use APIs provided in the following table to obtain the system language a ...@@ -119,7 +118,7 @@ You can use APIs provided in the following table to obtain the system language a
```js ```js
var calendar = i18n.getCalendar("zh-CN", "gregory); var calendar = i18n.getCalendar("zh-CN", "gregory");
``` ```
2. Set the time for the **Calendar** object. 2. Set the time for the **Calendar** object.
...@@ -192,7 +191,7 @@ You can use APIs provided in the following table to obtain the system language a ...@@ -192,7 +191,7 @@ You can use APIs provided in the following table to obtain the system language a
## Formatting a Phone Number ## Formatting a Phone Number
[PhoneNumberFormat](../reference/apis/js-apis-intl.md) APIs are used to format phone numbers in different countries and check whether the phone number formats are correct. [PhoneNumberFormat](../reference/apis/js-apis-i18n.md#phonenumberformat8) APIs are used to format phone numbers in different countries and check whether the phone number formats are correct.
### Available APIs ### Available APIs
...@@ -245,7 +244,7 @@ The **unitConvert** API is provided to help you implement measurement conversion ...@@ -245,7 +244,7 @@ The **unitConvert** API is provided to help you implement measurement conversion
### How to Develop ### How to Develop
1. Convert a measurement unit. 1. Convert a measurement unit.
Call the [unitConvert](../reference/apis/js-apis-intl.md) method to convert a measurement unit and format the display result. Call the [unitConvert](../reference/apis/js-apis-i18n.md#unitconvert8) method to convert a measurement unit and format the display result.
```js ```js
...@@ -260,7 +259,7 @@ The **unitConvert** API is provided to help you implement measurement conversion ...@@ -260,7 +259,7 @@ The **unitConvert** API is provided to help you implement measurement conversion
## Alphabet Index ## Alphabet Index
[IndexUtil](../reference/apis/js-apis-intl.md) APIs are used to obtain the alphabet indexes of different locales and calculate the index to which a string belongs. [IndexUtil](../reference/apis/js-apis-i18n.md#indexutil8) APIs are used to obtain the alphabet indexes of different locales and calculate the index to which a string belongs.
### Available APIs ### Available APIs
...@@ -281,7 +280,7 @@ The **unitConvert** API is provided to help you implement measurement conversion ...@@ -281,7 +280,7 @@ The **unitConvert** API is provided to help you implement measurement conversion
```js ```js
var indexUtil = getInstance("zh-CN"); var indexUtil = i18n.getInstance("zh-CN");
``` ```
2. Obtain the index list. 2. Obtain the index list.
...@@ -312,7 +311,7 @@ The **unitConvert** API is provided to help you implement measurement conversion ...@@ -312,7 +311,7 @@ The **unitConvert** API is provided to help you implement measurement conversion
## Obtaining Line Breaks of Text ## Obtaining Line Breaks of Text
When a text is displayed in more than one line, [BreakIterator](../reference/apis/js-apis-intl.md) APIs are used to obtain the line break positions of the text. When a text is displayed in more than one line, [BreakIterator8](../reference/apis/js-apis-i18n.md#breakiterator8) APIs are used to obtain the line break positions of the text.
### Available APIs ### Available APIs
......
# Internationalization Development (Intl) # Internationalization Development (Intl)
This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N interfaces defined in ECMA 402. This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N APIs defined in ECMA 402. For more details about APIs and their usage, see [Intl](../reference/apis/js-apis-intl.md).
The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities.
> **NOTE** > **NOTE**
> >
...@@ -9,7 +8,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug ...@@ -9,7 +8,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
## Setting Locale Information ## Setting Locale Information
Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize locale information. Use [Locale](../reference/apis/js-apis-intl.md#locale) APIs to maximize or minimize locale information.
### Available APIs ### Available APIs
...@@ -27,7 +26,7 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc ...@@ -27,7 +26,7 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc
1. Instantiate a **Locale** object. 1. Instantiate a **Locale** object.
Create a **Locale** object by using the **Locale** constructor. This method receives a string representing the locale and an optional [Attributes](../reference/apis/js-apis-intl.md) list. Create a **Locale** object by using the **Locale** constructor. This method receives a string representing the locale and an optional [Attributes](../reference/apis/js-apis-intl.md#localeoptions) list.
A **Locale** object consists of four parts: language, script, region, and extension, which are separated by using a hyphen (-). A **Locale** object consists of four parts: language, script, region, and extension, which are separated by using a hyphen (-).
- Language: mandatory. It is represented by a two-letter or three-letter code as defined in ISO-639. For example, **en** indicates English and **zh** indicates Chinese. - Language: mandatory. It is represented by a two-letter or three-letter code as defined in ISO-639. For example, **en** indicates English and **zh** indicates Chinese.
...@@ -46,7 +45,7 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc ...@@ -46,7 +45,7 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc
```js ```js
var locale = "zh-CN"; var locale = "zh-CN";
var options = {caseFirst: false, calendar: "chinese", collation: pinyin}; var options = {caseFirst: false, calendar: "chinese", collation: "pinyin"};
var localeObj = new intl.Locale(locale, options); var localeObj = new intl.Locale(locale, options);
``` ```
...@@ -77,7 +76,7 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc ...@@ -77,7 +76,7 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc
## Formatting the Date and Time ## Formatting the Date and Time
Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date and time for a specific locale. Use [DateTimeFormat](../reference/apis/js-apis-intl.md#datetimeformat) APIs to format the date and time for a specific locale.
### Available APIs ### Available APIs
...@@ -102,7 +101,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date ...@@ -102,7 +101,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
var dateTimeFormat = new intl.DateTimeFormat(); var dateTimeFormat = new intl.DateTimeFormat();
``` ```
Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md). Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md#datetimeoptions).
```js ```js
var options = {dateStyle: "full", timeStyle: "full"}; var options = {dateStyle: "full", timeStyle: "full"};
...@@ -114,7 +113,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date ...@@ -114,7 +113,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
Call the **format** method to format the date and time in the **DateTimeFormat** object. This method returns a string representing the formatting result. Call the **format** method to format the date and time in the **DateTimeFormat** object. This method returns a string representing the formatting result.
```js ```js
Date date = new Date(); var date = new Date();
var formatResult = dateTimeFormat.format(date); var formatResult = dateTimeFormat.format(date);
``` ```
...@@ -123,9 +122,10 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date ...@@ -123,9 +122,10 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
Call the **formatRange** method to format the period in the **DateTimeFormat** object. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result. Call the **formatRange** method to format the period in the **DateTimeFormat** object. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result.
```js ```js
Date startDate = new Date(); var startDate = new Date(2021, 11, 17, 3, 24, 0);
Date endDate = new Date(); var endDate = new Date(2021, 11, 18, 3, 24, 0);
var formatResult = dateTimeFormat.formatRange(startDate, endDate); var datefmt = new Intl.DateTimeFormat("en-GB");
datefmt.formatRange(startDate, endDate);
``` ```
4. Obtain attributes of the **DateTimeFormat** object. 4. Obtain attributes of the **DateTimeFormat** object.
...@@ -139,7 +139,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date ...@@ -139,7 +139,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
## Formatting Numbers ## Formatting Numbers
Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for a specific locale. Use [NumberFormat](../reference/apis/js-apis-intl.md#numberformat) APIs to format numbers for a specific locale.
### Available APIs ### Available APIs
...@@ -163,7 +163,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for ...@@ -163,7 +163,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for
var numberFormat = new intl.NumberFormat(); var numberFormat = new intl.NumberFormat();
``` ```
Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md). Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md#numberoptions).
```js ```js
var options = {compactDisplay: "short", notation: "compact"}; var options = {compactDisplay: "short", notation: "compact"};
...@@ -190,7 +190,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for ...@@ -190,7 +190,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for
## Sorting Strings ## Sorting Strings
Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on a specific locale. Users in different regions have different preferences for string sorting. Use [Collator](../reference/apis/js-apis-intl.md#collator8) APIs to sort strings based on a specific locale. Users in different regions have different preferences for string sorting.
### Available APIs ### Available APIs
...@@ -214,7 +214,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on ...@@ -214,7 +214,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on
var collator = new intl.Collator(); var collator = new intl.Collator();
``` ```
Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md). Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions8).
```js ```js
var collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"}); var collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"});
...@@ -222,7 +222,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on ...@@ -222,7 +222,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on
2. Compare two strings. 2. Compare two strings.
Call the **compare** method to compare two input strings. This method returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths. Call the **compare** method to compare two input strings. This method returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths. This allows you to sort character strings based on the comparison result.
```js ```js
var str1 = "first string"; var str1 = "first string";
...@@ -241,7 +241,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on ...@@ -241,7 +241,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on
## Determining the Singular-Plural Type ## Determining the Singular-Plural Type
Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singular-plural type for a specific locale. According to the grammar of certain languages, the singular or plural form of a noun depends on its preceding number. Use [PluralRules](../reference/apis/js-apis-intl.md#pluralrules8) APIs to determine the singular-plural type for a specific locale. According to the grammar of certain languages, the singular or plural form of a noun depends on its preceding number.
### Available APIs ### Available APIs
...@@ -264,10 +264,10 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu ...@@ -264,10 +264,10 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu
var pluralRules = new intl.PluralRules(); var pluralRules = new intl.PluralRules();
``` ```
Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md). Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions8).
```js ```js
var plurals = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); var pluralRules = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"});
``` ```
2. Determine the singular-plural type. 2. Determine the singular-plural type.
...@@ -282,7 +282,7 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu ...@@ -282,7 +282,7 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu
## Formatting the Relative Time ## Formatting the Relative Time
Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the relative time for a specific locale. Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) APIs to format the relative time for a specific locale.
### Available APIs ### Available APIs
...@@ -307,7 +307,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r ...@@ -307,7 +307,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r
var relativeTimeFormat = new intl.RelativeTimeFormat(); var relativeTimeFormat = new intl.RelativeTimeFormat();
``` ```
Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [ RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md). Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions8).
```js ```js
var relativeTimeFormat = new intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); var relativeTimeFormat = new intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
...@@ -335,8 +335,16 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r ...@@ -335,8 +335,16 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r
4. Obtain attributes of the **RelativeTimeFormat** object. 4. Obtain attributes of the **RelativeTimeFormat** object.
Call the **resolvedOptions** method to obtain attributes of the **RelativeTimeFormat** object. This method will return an array that contains all attributes and values of the object. For a full list of attributes, see [ RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md). Call the **resolvedOptions** method to obtain attributes of the **RelativeTimeFormat** object. This method will return an array that contains all attributes and values of the object. For a full list of attributes, see [RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md#relativetimeformatresolvedoptions8).
```js ```js
var options = numberFormat.resolvedOptions(); var options = numberFormat.resolvedOptions();
``` ```
## Samples
The following sample is provided to help you better understand how to develop internationalization capabilities:
-[`International`: Internationalization (JS) (API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/International)
-[`International`: Internationalization (eTS) (API8) (Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/International)
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
- [Audio Playback Development](audio-playback.md) - [Audio Playback Development](audio-playback.md)
- [Audio Recording Development](audio-recorder.md) - [Audio Recording Development](audio-recorder.md)
- [Audio Rendering Development](audio-renderer.md) - [Audio Rendering Development](audio-renderer.md)
- [Audio Stream Management Development](audio-stream-manager.md)
- [Audio Capture Development](audio-capturer.md) - [Audio Capture Development](audio-capturer.md)
- [OpenSL ES Audio Playback Development](opensles-playback.md) - [OpenSL ES Audio Playback Development](opensles-playback.md)
- [OpenSL ES Audio Recording Development](opensles-capture.md) - [OpenSL ES Audio Recording Development](opensles-capture.md)
......
# Audio Stream Management Development
## When to Use
You can use **AudioStreamManager** to manage audio streams.
### Development Process
During application development, use **getStreamManager()** to create an **AudioStreamManager** instance. Then, you can call **on('audioRendererChange')** or **on('audioCapturerChange')** to listen for status, client, and audio attribute changes of the audio playback or recording application. To cancel the listening for these changes, call **off('audioRendererChange')** or **off('audioCapturerChange')**. You can call **getCurrentAudioRendererInfoArray()** to obtain information about the audio playback application, such as the unique audio stream ID, UID of the audio playback client, and audio status. Similarly, you can call **getCurrentAudioCapturerInfoArray()** to obtain information about the audio recording application. The figure below shows the invoking relationship.
For details about the APIs, see [AudioStreamManager](../reference/apis/js-apis-audio.md#audiostreammanager9).
**Figure 1** Audio stream management invoking relationship
![](figures/zh-ch_image_audio_stream_manager.png)
## How to Develop
1. Create an **AudioStreamManager** instance.
Before using **AudioStreamManager** APIs, you must use **getStreamManager()** to create an **AudioStreamManager** instance.
```js
var audioStreamManager = audio.getStreamManager();
```
2. (Optional) Call **on('audioRendererChange')** to listen for audio renderer changes.
If an application needs to receive notifications when the audio playback application status, audio playback client, or audio attribute changes, it can subscribe to this event. For more events that can be subscribed to, see [Audio Management](../reference/apis/js-apis-audio.md).
```js
audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => {
for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
AudioRendererChangeInfo = AudioRendererChangeInfoArray[i];
console.info('## RendererChange on is called for ' + i + ' ##');
console.info('StreamId for ' + i + ' is:' + AudioRendererChangeInfo.streamId);
console.info('ClientUid for ' + i + ' is:' + AudioRendererChangeInfo.clientUid);
console.info('Content for ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.content);
console.info('Stream for ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.usage);
console.info('Flag ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.rendererFlags);
console.info('State for ' + i + ' is:' + AudioRendererChangeInfo.rendererState);
var devDescriptor = AudioRendererChangeInfo.deviceDescriptors;
for (let j = 0; j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
console.info('Id:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].id);
console.info('Type:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceType);
console.info('Role:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole);
console.info('Name:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].name);
console.info('Address:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].address);
console.info('SampleRates:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]);
console.info('ChannelCounts' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]);
console.info('ChannelMask:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks);
}
}
});
```
3. (Optional) Call **off('audioRendererChange')** to cancel listening for audio renderer changes.
```js
audioStreamManager.off('audioRendererChange');
console.info('######### RendererChange Off is called #########');
```
4. (Optional) Call **on('audioCapturerChange')** to listen for audio capturer changes.
If an application needs to receive notifications when the audio recording application status, audio recording client, or audio attribute changes, it can subscribe to this event. For more events that can be subscribed to, see [Audio Management](../reference/apis/js-apis-audio.md).
```js
audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => {
for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
console.info(' ## audioCapturerChange on is called for element ' + i + ' ##');
console.info('StreamId for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].streamId);
console.info('ClientUid for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].clientUid);
console.info('Source for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.source);
console.info('Flag ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags);
console.info('State for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerState);
for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
console.info('Id:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id);
console.info('Type:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType);
console.info('Role:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole);
console.info('Name:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name);
console.info('Address:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address);
console.info('SampleRates:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]);
console.info('ChannelCounts' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]);
console.info('ChannelMask:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks);
}
}
});
```
5. (Optional) Call **off('audioCapturerChange')** to cancel listening for audio capturer changes.
```js
audioStreamManager.off('audioCapturerChange');
console.info('######### CapturerChange Off is called #########');
```
6. (Optional) Call **getCurrentAudioRendererInfoArray()** to obtain information about the current audio renderer.
This API can be used to obtain the unique ID of the audio stream, UID of the audio playback client, audio status, and other information about the audio player. Before calling this API, a third-party application must have the **ohos.permission.USE_BLUETOOTH** permission configured, for the device name and device address to be displayed correctly.
```js
await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) {
console.info('######### Get Promise is called ##########');
if (AudioRendererChangeInfoArray != null) {
for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
AudioRendererChangeInfo = AudioRendererChangeInfoArray[i];
console.info('StreamId for ' + i +' is:' + AudioRendererChangeInfo.streamId);
console.info('ClientUid for ' + i + ' is:' + AudioRendererChangeInfo.clientUid);
console.info('Content ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.content);
console.info('Stream' + i +' is:' + AudioRendererChangeInfo.rendererInfo.usage);
console.info('Flag' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.rendererFlags);
console.info('State for ' + i + ' is:' + AudioRendererChangeInfo.rendererState);
var devDescriptor = AudioRendererChangeInfo.deviceDescriptors;
for (let j = 0; j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
console.info('Id:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].id);
console.info('Type:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceType);
console.info('Role:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole);
console.info('Name:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].name);
console.info('Address:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].address);
console.info('SampleRates:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]);
console.info('ChannelCounts' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]);
console.info('ChannnelMask:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks);
}
}
}
}).catch((err) => {
console.log('getCurrentAudioRendererInfoArray :ERROR: ' + err.message);
});
```
7. (Optional) Call **getCurrentAudioCapturerInfoArray()** to obtain information about the current audio capturer.
This API can be used to obtain the unique ID of the audio stream, UID of the audio recording client, audio status, and other information about the audio capturer. Before calling this API, a third-party application must have the **ohos.permission.USE_BLUETOOTH** permission configured, for the device name and device address to be displayed correctly.
```js
await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) {
console.info('getCurrentAudioCapturerInfoArray: **** Get Promise Called ****');
if (AudioCapturerChangeInfoArray != null) {
for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
console.info('StreamId for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].streamId);
console.info('ClientUid for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].clientUid);
console.info('Source for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.source);
console.info('Flag ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags);
console.info('State for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerState);
var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors;
for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
console.info('Id:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id);
console.info('Type:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType);
console.info('Role:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole);
console.info('Name:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name)
console.info('Address:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address);
console.info('SampleRates:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]);
console.info('ChannelCounts' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]);
console.info('ChannelMask:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks);
}
}
}
}).catch((err) => {
console.log('getCurrentAudioCapturerInfoArray :ERROR: ' + err.message);
});
```
# Distributed Camera Development
## When to Use
You can call the APIs provided by the **Camera** module to develop a distributed camera that provides the basic camera functions such as shooting and video recording.
## How to Develop
Connect your calculator to a distributed device. Your calculator will call **getCameras()** to obtain the camera list and traverse the returned camera list to check **ConnctionType** of the **Camera** objects. If **ConnctionType** of a **Camera** object is **CAMERA_CONNECTION_REMOTE**, your calculator will use this object to create a **CameraInput** object. The subsequent call process is the same as that of the local camera development. For details about the local camera development, see [Camera Development](./camera.md).
For details about the APIs, see [Camera Management](../reference/apis/js-apis-camera.md).
### Connecting to a Distributed Camera
Connect the calculator and the distributed device to the same LAN.
Open the calculator and click the arrow icon in the upper right corner. A new window is displayed. Enter the verification code as prompted, and the calculator will be connected to the distributed device.
### Creating an Instance
```js
import camera from '@ohos.multimedia.camera'
import image from '@ohos.multimedia.image'
import media from '@ohos.multimedia.media'
import featureAbility from '@ohos.ability.featureAbility'
// Create a CameraManager object.
let cameraManager
await camera.getCameraManager(globalThis.Context, (err, manager) => {
if (err) {
console.error('Failed to get the CameraManager instance ${err.message}');
return;
}
console.log('Callback returned with the CameraManager instance');
cameraManager = manager
})
// Register a callback to listen for camera status changes and obtain the updated camera status information.
cameraManager.on('cameraStatus', (cameraStatusInfo) => {
console.log('camera : ' + cameraStatusInfo.camera.cameraId);
console.log('status: ' + cameraStatusInfo.status);
})
// Obtain the camera list.
let cameraArray
let remoteCamera
await cameraManager.getCameras((err, cameras) => {
if (err) {
console.error('Failed to get the cameras. ${err.message}');
return;
}
console.log('Callback returned with an array of supported cameras: ' + cameras.length);
cameraArray = cameras
})
for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex) {
console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // Obtain the camera ID.
console.log('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) // Obtain the camera position.
console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type.
console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) // Obtain the camera connection type.
if (cameraArray[cameraIndex].connectionType == CAMERA_CONNECTION_REMOTE) {
remoteCamera = cameraArray[cameraIndex].cameraId
}
}
// Create a camera input stream.
let cameraInput
await cameraManager.createCameraInput(remoteCamera).then((input) => {
console.log('Promise returned with the CameraInput instance');
cameraInput = input
})
```
For details about the subsequent steps, see [Camera Development](./camera.md).
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
- [Using Native APIs in Application Projects](napi-guidelines.md) - [Using Native APIs in Application Projects](napi-guidelines.md)
- [Drawing Development](drawing-guidelines.md) - [Drawing Development](drawing-guidelines.md)
- [Native Window Development](native-window-guidelines.md)
- [Raw File Development](rawfile-guidelines.md) - [Raw File Development](rawfile-guidelines.md)
- [Native Window Development](native-window-guidelines.md)
...@@ -89,7 +89,7 @@ Register four synchronous APIs (`getSync`, `setSync`, `removeSync`, and`clearSyn ...@@ -89,7 +89,7 @@ Register four synchronous APIs (`getSync`, `setSync`, `removeSync`, and`clearSyn
/*********************************************** /***********************************************
* Module export and register * Module export and register
***********************************************/ ***********************************************/
static napi_value StorgeExport(napi_env env, napi_value exports) static napi_value StorageExport(napi_env env, napi_value exports)
{ {
napi_property_descriptor desc[] = { napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("get", JSStorageGet), DECLARE_NAPI_FUNCTION("get", JSStorageGet),
...@@ -110,7 +110,7 @@ static napi_value StorgeExport(napi_env env, napi_value exports) ...@@ -110,7 +110,7 @@ static napi_value StorgeExport(napi_env env, napi_value exports)
static napi_module storage_module = {.nm_version = 1, static napi_module storage_module = {.nm_version = 1,
.nm_flags = 0, .nm_flags = 0,
.nm_filename = nullptr, .nm_filename = nullptr,
.nm_register_func = StorgeExport, .nm_register_func = StorageExport,
.nm_modname = "storage", .nm_modname = "storage",
.nm_priv = ((void*)0), .nm_priv = ((void*)0),
.reserved = {0}}; .reserved = {0}};
......
...@@ -6,7 +6,7 @@ The common event and notification module provides debugging tools to facilitate ...@@ -6,7 +6,7 @@ The common event and notification module provides debugging tools to facilitate
### publish ### publish
* Functionality * Function
Publishes a common event. Publishes a common event.
...@@ -16,14 +16,14 @@ The common event and notification module provides debugging tools to facilitate ...@@ -16,14 +16,14 @@ The common event and notification module provides debugging tools to facilitate
The table below describes the available options. The table below describes the available options.
| Option | Description | | Option | Description |
| ------------ | ------------------------------------------ | | ------------ | ------------------------------------------ |
| -e/--event | Indicates the name of the common event to publish. Mandatory. | | -e/--event | Indicates the name of the common event to publish. Mandatory. |
| -s/--sticky | Indicates that the common event to publish is sticky. Optional. By default, non-sticky events are published.| | -s/--sticky | Indicates that the common event to publish is sticky. Optional. By default, non-sticky events are published. |
| -o/--ordered | Indicates that the common event to publish is ordered. Optional. By default, non-ordered events are published. | | -o/--ordered | Indicates that the common event to publish is ordered. Optional. By default, non-ordered events are published. |
| -c/--code | Indicates the result code of the common event. Optional. | | -c/--code | Indicates the result code of the common event. Optional. |
| -d/--data | Indicates the data carried in the common event. Optional. | | -d/--data | Indicates the data carried in the common event. Optional. |
| -h/--help | Indicates the help Information | | -h/--help | Indicates the help Information |
* Example * Example
...@@ -43,7 +43,7 @@ The common event and notification module provides debugging tools to facilitate ...@@ -43,7 +43,7 @@ The common event and notification module provides debugging tools to facilitate
### dump ### dump
* Functionality * Function
Displays information about common events. Displays information about common events.
...@@ -53,11 +53,11 @@ The common event and notification module provides debugging tools to facilitate ...@@ -53,11 +53,11 @@ The common event and notification module provides debugging tools to facilitate
The table below describes the available options. The table below describes the available options.
| Option | Description | | Option | Description |
| ---------- | -------------------------------------------- | | ---------- | -------------------------------------------- |
| -a/--all | Displays information about all common events that have been sent since system startup.| | -a/--all | Displays information about all common events that have been sent since system startup. |
| -e/--event | Displays information about a specific event. | | -e/--event | Displays information about a specific event. |
| -h/--help | Displays the help information. | | -h/--help | Displays the help information. |
* Example * Example
...@@ -69,7 +69,7 @@ The common event and notification module provides debugging tools to facilitate ...@@ -69,7 +69,7 @@ The common event and notification module provides debugging tools to facilitate
### help ### help
* Functionality * Function
Displays the help information. Displays the help information.
...@@ -87,7 +87,7 @@ The common event and notification module provides debugging tools to facilitate ...@@ -87,7 +87,7 @@ The common event and notification module provides debugging tools to facilitate
### dump ### dump
* Functionality * Function
Displays information about notifications. Displays information about notifications.
...@@ -97,19 +97,19 @@ The common event and notification module provides debugging tools to facilitate ...@@ -97,19 +97,19 @@ The common event and notification module provides debugging tools to facilitate
The table below describes the available options. The table below describes the available options.
| Option | Description | | Option | Description |
| ---------------- | ---------------------------------------- | | ---------------- | ---------------------------------------- |
| -A/--active | Displays information about all active notifications. | | -A/--active | Displays information about all active notifications. |
| -R/--recent | Displays information about the recent notifications. | | -R/--recent | Displays information about the recent notifications. |
| -D/--distributed | Displays information about distributed notifications from other devices. | | -D/--distributed | Displays information about distributed notifications from other devices. |
| --setRecentCount | Indicates the number of the cached recent notifications to be displayed. Optional.| | --setRecentCount | Indicates the number of the cached recent notifications to be displayed. Optional. |
| -h/--help | Displays the help information. | | -h/--help | Displays the help information. |
* Example * Example
`anm dump -A` `anm dump -A`
Displays information about all active notifications. Display information about all active notifications.
![anm-dump-A](figures/anm-dump-A.png) ![anm-dump-A](figures/anm-dump-A.png)
...@@ -117,11 +117,11 @@ The common event and notification module provides debugging tools to facilitate ...@@ -117,11 +117,11 @@ The common event and notification module provides debugging tools to facilitate
`anm dump --setRecentCount 10` `anm dump --setRecentCount 10`
Set the number of the cached recent notifications to be displayed to 10. Set the number of the cached recent notifications to be displayed to **10**.
### help ### help
* Functionality * Function
Displays the help information. Displays the help information.
......
...@@ -7,139 +7,33 @@ You can set your application to call the **ReminderRequest** class to create sch ...@@ -7,139 +7,33 @@ You can set your application to call the **ReminderRequest** class to create sch
## Available APIs ## Available APIs
**reminderAgent** encapsulates the methods for publishing and canceling reminders. **reminderAgent** encapsulates the APIs for publishing and canceling reminders.
**Table 1** Major APIs in reminderAgent For details about the APIs, see [reminderAgent](../reference/apis/js-apis-reminderAgent.md).
| Name| Description|
| -------- | -------- |
| function publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback&lt;number&gt;): void;<br>function publishReminder(reminderReq: ReminderRequest): Promise&lt;number&gt;; | Publishes a scheduled reminder.<br>The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application and 2000 for the entire system. |
| function cancelReminder(reminderId: number, callback: AsyncCallback&lt;void&gt;): void;<br>function cancelReminder(reminderId: number): Promise&lt;void&gt;; | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.)|
| function getValidReminders(callback: AsyncCallback&lt;Array&lt;ReminderRequest&gt;&gt;): void;<br>function getValidReminders(): Promise&lt;Array&lt;ReminderRequest&gt;&gt;; | Obtains all valid reminders set by the current application.|
| function cancelAllReminders(callback: AsyncCallback&lt;void&gt;): void;<br>function cancelAllReminders(): Promise&lt;void&gt;; | Cancels all reminders set by the current application.|
| function addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback&lt;void&gt;): void;<br>function addNotificationSlot(slot: NotificationSlot): Promise&lt;void&gt;; | Registers a **NotificationSlot** instance to be used by the reminder. |
| function removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback&lt;void&gt;): void;<br>function removeNotificationSlot(slotType: notification.SlotType): Promise&lt;void&gt;; | Removes a **NotificationSlot** instance of a specified type. |
**ActionButtonType** enumerates types of buttons displayed in a reminder notification. **Table 1** Major APIs in reminderAgent
**Table 2** ActionButtonType enums
| Name| Description|
| -------- | -------- |
| ACTION_BUTTON_TYPE_CLOSE | Close button, which can stop the reminder alert tone, close the reminder notification, and cancel the reminder snoozing.|
| ACTION_BUTTON_TYPE_SNOOZE | Snooze button, which can snooze the reminder.|
**ReminderType** enumerates the reminder types.
**Table 3** ReminderType enums
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| REMINDER_TYPE_TIMER | Countdown reminder.| | publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback&lt;number&gt;): void<br>publishReminder(reminderReq: ReminderRequest): Promise&lt;number&gt; | Publishes a scheduled reminder.<br>The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application and 2000 for the entire system. |
| REMINDER_TYPE_CALENDAR | Calendar reminder.| | cancelReminder(reminderId: number, callback: AsyncCallback&lt;void&gt;): void<br>cancelReminder(reminderId: number): Promise&lt;void&gt; | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.)|
| REMINDER_TYPE_ALARM | Alarm reminder.| | getValidReminders(callback: AsyncCallback&lt;Array&lt;ReminderRequest&gt;&gt;): void<br>getValidReminders(): Promise&lt;Array&lt;ReminderRequest&gt;&gt; | Obtains all valid reminders set by the current application.|
| cancelAllReminders(callback: AsyncCallback&lt;void&gt;): void<br>cancelAllReminders(): Promise&lt;void&gt; | Cancels all reminders set by the current application.|
**ActionButton** defines a button displayed in the reminder notification. | addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback&lt;void&gt;): void<br>addNotificationSlot(slot: NotificationSlot): Promise&lt;void&gt; | Registers a **NotificationSlot** instance to be used by the reminder.|
| removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback&lt;void&gt;): void<br>removeNotificationSlot(slotType: notification.SlotType): Promise&lt;void&gt; | Removes a **NotificationSlot** instance of a specified type.|
**Table 4** ActionButton
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| title | string | Yes| Text on the button.|
| type | ActionButtonType | Yes| Button type.|
**WantAgent** sets the package and ability that are redirected to when the reminder notification is clicked.
**Table 5** WantAgent
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pkgName | string | Yes| Name of the package redirected to when the reminder notification is clicked.|
| abilityName | string | Yes| Name of the ability redirected to when the reminder notification is clicked.|
**MaxScreenWantAgent** sets the name of the target package and ability to start automatically when the reminder arrives and the device is not in use. If the device is in use, a notification will be displayed.
**Table 6** MaxScreenWantAgent
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pkgName | string | Yes| Name of the package that is automatically started when the reminder arrives and the device is not in use.|
| abilityName | string | Yes| Name of the ability that is automatically started when the reminder arrives and the device is not in use.|
**ReminderRequest** defines the reminder to publish.
**Table 7** ReminderRequest
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| reminderType | ReminderType | Yes| Type of the reminder.|
| actionButton | [ActionButton?,ActionButton?] | No| Action button displayed in the reminder notification.|
| wantAgent | WantAgent | No| Information about the ability that is redirected to when the notification is clicked.|
| maxScreenWantAgent | MaxScreenWantAgent | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.|
| ringDuration | number | No| Ring duration.|
| snoozeTimes | number | No| Number of reminder snooze times.|
| timeInterval | number | No| Reminder snooze interval.|
| title | string | No| Reminder title.|
| content | string | No| Reminder content.|
| expiredContent | string | No| Extended content to be displayed when the reminder expires.|
| snoozeContent | string | No| Extended content to be displayed when the reminder is snoozing.|
| notificationId | number | No| Notification ID used by the reminder. For details, see **NotificationRequest::SetNotificationId(int32_t id)**.|
| slotType | SlotType | No| Type of the slot used by the reminder. |
**ReminderRequestCalendar** extends **ReminderRequest** and defines a reminder for a calendar event.
For the application to run properly, if both **repeatMonths** and **repeatDays** are not specified, the earliest reminder time must be later than the current time.
**Table 8** ReminderRequestCalendar
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| dateTime | LocalDateTime | Yes| Reminder time, accurate to the minute.|
| repeatMonths | Array&lt;number&gt; | No| Months in which the reminder repeats. The value range is 1 to 12.|
| repeatDays | Array&lt;number&gt; | No| Date on which the reminder repeats. The value range is 1 to 31.|
**ReminderRequestAlarm** extends **ReminderRequest** and defines a reminder for the alarm clock.
**Table 9** ReminderRequestAlarm
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| hour | number | Yes| Hour portion of the reminder time. The value range is 0 to 23.|
| minute | number | Yes| Minute portion of the reminder time. The value range is 0 to 59.|
| daysOfWeek | Array&lt;number&gt; | No| Days of a week when the reminder repeats. The value range is 1 to 7.|
**ReminderRequestTimer** extends **ReminderRequest** and defines a reminder for a scheduled timer.
**Table 10** ReminderRequestTimer
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| triggerTimeInSeconds | number | Yes| Number of seconds in the countdown timer.|
**LocalDateTime** defines a **LocalDateTime** instance.
**Table 11** LocalDateTime
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| year | number | Yes| Year.|
| month | number | Yes| Month.|
| day | number | Yes| Date.|
| hour | number | Yes| Hour.|
| minute | number | Yes| Minute.|
| second | number | No| Second.|
## How to Develop ## How to Develop
> **NOTE** > **NOTE**
> >
> To publish a reminder, your application needs to apply for the **ohos.permission.PUBLISH_AGENT_REMINDER** permission. > 1. To publish a reminder through the reminder agent, your application needs to apply for the **ohos.permission.PUBLISH_AGENT_REMINDER** permission.
>
> 2. Your application must have notification enabled. For details, see [Notification.requestEnableNotification](../reference/apis/js-apis-notification.md#notificationrequestenablenotification8).
Publish a 10-second countdown reminder. 1. Define a reminder agent.
1. Define a countdown timer instance. Sample code for defining a reminder agent for a countdown timer:
``` ```js
import reminderAgent from '@ohos.reminderAgent'; import reminderAgent from '@ohos.reminderAgent';
import notification from '@ohos.notification'; import notification from '@ohos.notification';
export default { export default {
...@@ -172,8 +66,97 @@ Publish a 10-second countdown reminder. ...@@ -172,8 +66,97 @@ Publish a 10-second countdown reminder.
} }
``` ```
2. Publish the reminder. Sample code for defining a reminder agent for a calendar event:
```
```js
// For a JS project:
// calendar: {
// For an eTS project:
let calendar : reminderAgent.ReminderRequestCalendar = {
reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR,
dateTime: {
year: 2050,
month: 7,
day: 30,
hour: 11,
minute: 14,
second: 30
},
repeatMonths: [1],
repeatDays: [1],
actionButton: [
{
title: "close",
type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE
},
{
title: "snooze",
type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE
},
],
wantAgent: {
pkgName: "com.example.device",
abilityName: "com.example.device.MainAbility"
},
maxScreenWantAgent: {
pkgName: "com.example.device",
abilityName: "com.example.device.MainAbility"
},
ringDuration: 5,
snoozeTimes: 2,
timeInterval: 5,
title: "this is title",
content: "this is content",
expiredContent: "this reminder has expired",
snoozeContent: "remind later",
notificationId: 100,
slotType: notification.SlotType.SOCIAL_COMMUNICATION
}
```
Sample code for defining a reminder agent for an alarm:
```js
// For a JS project:
// alarm: {
// For an eTS project:
let alarm : reminderAgent.ReminderRequestAlarm = {
reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM,
hour: 11,
minute: 14,
daysOfWeek: [0],
actionButton: [
{
title: "close",
type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE
},
{
title: "snooze",
type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE
},
],
wantAgent: {
pkgName: "com.example.device",
abilityName: "com.example.device.MainAbility"
},
maxScreenWantAgent: {
pkgName: "com.example.device",
abilityName: "com.example.device.MainAbility"
},
ringDuration: 5,
snoozeTimes: 2,
timeInterval: 5,
title: "this is title",
content: "this is content",
expiredContent: "this reminder has expired",
snoozeContent: "remind later",
notificationId: 100,
slotType: notification.SlotType.SOCIAL_COMMUNICATION
}
```
2. Publish a countdown reminder.
```js
startTimer() { startTimer() {
reminderAgent.publishReminder(this.timer, (err, reminderId) =>{ reminderAgent.publishReminder(this.timer, (err, reminderId) =>{
this.printInfo(JSON.stringify(err)); this.printInfo(JSON.stringify(err));
...@@ -183,98 +166,9 @@ Publish a 10-second countdown reminder. ...@@ -183,98 +166,9 @@ Publish a 10-second countdown reminder.
``` ```
HML page code: HML page code:
``` ```html
<div class="container"> <div class="container">
<button type="text" value="publishReminder" onclick="startTimer"></button> <button type="text" value="publishReminder" onclick="startTimer"></button>
</div> </div>
``` ```
Sample code for defining a calendar reminder instance:
```
// For a JS project:
// calendar: {
// For an eTS project:
let calendar : reminderAgent.ReminderRequestCalendar = {
reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR,
dateTime: {
year: 2050,
month: 7,
day: 30,
hour: 11,
minute: 14,
second: 30
},
repeatMonths: [1],
repeatDays: [1],
actionButton: [
{
title: "close",
type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE
},
{
title: "snooze",
type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE
},
],
wantAgent: {
pkgName: "com.example.device",
abilityName: "com.example.device.MainAbility"
},
maxScreenWantAgent: {
pkgName: "com.example.device",
abilityName: "com.example.device.MainAbility"
},
ringDuration: 5,
snoozeTimes: 2,
timeInterval: 5,
title: "this is title",
content: "this is content",
expiredContent: "this reminder has expired",
snoozeContent: "remind later",
notificationId: 100,
slotType: notification.SlotType.SOCIAL_COMMUNICATION
}
```
Sample code for defining an alarm reminder instance:
```
// For a JS project:
// alarm: {
// For an eTS project:
let alarm : reminderAgent.ReminderRequestAlarm = {
reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM,
hour: 11,
minute: 14,
daysOfWeek: [0],
actionButton: [
{
title: "close",
type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE
},
{
title: "snooze",
type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE
},
],
wantAgent: {
pkgName: "com.example.device",
abilityName: "com.example.device.MainAbility"
},
maxScreenWantAgent: {
pkgName: "com.example.device",
abilityName: "com.example.device.MainAbility"
},
ringDuration: 5,
snoozeTimes: 2,
timeInterval: 5,
title: "this is title",
content: "this is content",
expiredContent: "this reminder has expired",
snoozeContent: "remind later",
notificationId: 100,
slotType: notification.SlotType.SOCIAL_COMMUNICATION
}
```
...@@ -28,14 +28,14 @@ System applications also support notification-related configuration options, suc ...@@ -28,14 +28,14 @@ System applications also support notification-related configuration options, suc
## Available APIs ## Available APIs
Certain APIs can be invoked only by system applications that have been granted the **SystemCapability.Notification.Notification** permission. The APIs use either a callback or promise to return the result. The tables below list the APIs that use a callback, which provide same functions as their counterparts that use a promise. For details about the APIs, see the [API document](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-notification.md). Certain APIs can be called only by system applications that have been granted the **SystemCapability.Notification.Notification** permission. The APIs use either a callback or promise to return the result. The tables below list the APIs that use a callback, which provide the same functions as their counterparts that use a promise. For details about the APIs, see the [API document](../reference/apis/js-apis-notification.md).
**Table 1** APIs for notification enabling **Table 1** APIs for notification enabling
| API | Description | | API | Description |
| ------------------------------------------------------------ | ---------------- | | ------------------------------------------------------------ | ---------------- |
| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback<boolean>): void | Checks whether notification is enabled.| | isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\<boolean>): void | Checks whether notification is enabled.|
| enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback<void>): void | Sets whether to enable notification. | | enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\<void>): void | Sets whether to enable notification. |
If the notification function of an application is disabled, it cannot send notifications. If the notification function of an application is disabled, it cannot send notifications.
...@@ -45,11 +45,11 @@ If the notification function of an application is disabled, it cannot send notif ...@@ -45,11 +45,11 @@ If the notification function of an application is disabled, it cannot send notif
| API | Description | | API | Description |
| ------------------------------------------------------------ | ---------------- | | ------------------------------------------------------------ | ---------------- |
| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback<void>): void | Subscribes to a notification with the subscription information specified.| | subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\<void>): void | Subscribes to a notification with the subscription information specified.|
| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback<void>): void | Subscribes to all notifications. | | subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\<void>): void | Subscribes to all notifications. |
| unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback<void>): void | Unsubscribes from a notification. | | unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\<void>): void | Unsubscribes from a notification. |
The subscription APIs support subscription to all notifications or notifications from specific applications. The subscription APIs support subscription to all notifications and notifications from specific applications.
...@@ -69,10 +69,10 @@ The subscription APIs support subscription to all notifications or notifications ...@@ -69,10 +69,10 @@ The subscription APIs support subscription to all notifications or notifications
| API | Description | | API | Description |
| ------------------------------------------------------------ | ------------------------ | | ------------------------------------------------------------ | ------------------------ |
| publish(request: NotificationRequest, callback: AsyncCallback<void>): void | Publishes a notification. | | publish(request: NotificationRequest, callback: AsyncCallback\<void>): void | Publishes a notification. |
| publish(request: NotificationRequest, userId: number, callback: AsyncCallback<void>): void | Publishes a notification to the specified user. | | publish(request: NotificationRequest, userId: number, callback: AsyncCallback\<void>): void | Publishes a notification to the specified user. |
| cancel(id: number, label: string, callback: AsyncCallback<void>): void | Cancels a specified notification. | | cancel(id: number, label: string, callback: AsyncCallback\<void>): void | Cancels a specified notification. |
| cancelAll(callback: AsyncCallback<void>): void; | Cancels all notifications published by the application.| | cancelAll(callback: AsyncCallback\<void>): void; | Cancels all notifications published by the application.|
The **publish** API that carries **userId** can be used to publish notifications to subscribers of a specified user. The **publish** API that carries **userId** can be used to publish notifications to subscribers of a specified user.
...@@ -136,7 +136,7 @@ var subscriber = { ...@@ -136,7 +136,7 @@ var subscriber = {
Before publishing a notification, check whether the notification feature is enabled for your application. By default, the feature is disabled. The application calls **Notification.requestEnableNotification** to prompt the user to enable the feature. Before publishing a notification, check whether the notification feature is enabled for your application. By default, the feature is disabled. The application calls **Notification.requestEnableNotification** to prompt the user to enable the feature.
```js ```js
Notification.requestEnableNotification() .then((data) => { Notification.requestEnableNotification().then((data) => {
console.info('===>requestEnableNotification success'); console.info('===>requestEnableNotification success');
}).catch((err) => { }).catch((err) => {
console.error('===>requestEnableNotification failed because ' + JSON.stringify(err)); console.error('===>requestEnableNotification failed because ' + JSON.stringify(err));
...@@ -166,7 +166,7 @@ var notificationRequest = { ...@@ -166,7 +166,7 @@ var notificationRequest = {
} }
// Publish the notification. // Publish the notification.
Notification.publish(notificationRequest) .then((data) => { Notification.publish(notificationRequest).then((data) => {
console.info('===>publish promise success req.id : ' + notificationRequest.id); console.info('===>publish promise success req.id : ' + notificationRequest.id);
}).catch((err) => { }).catch((err) => {
console.error('===>publish promise failed because ' + JSON.stringify(err)); console.error('===>publish promise failed because ' + JSON.stringify(err));
...@@ -235,7 +235,7 @@ var notificationRequest = { ...@@ -235,7 +235,7 @@ var notificationRequest = {
} }
// Publish the notification. // Publish the notification.
Notification.publish(notificationRequest) .then((data) => { Notification.publish(notificationRequest).then((data) => {
console.info('===>publish promise success req.id : ' + notificationRequest.id); console.info('===>publish promise success req.id : ' + notificationRequest.id);
}).catch((err) => { }).catch((err) => {
console.error('===>publish promise failed because ' + JSON.stringify(err)); console.error('===>publish promise failed because ' + JSON.stringify(err));
......
# Guide to Switching to Full SDK # Guide to Switching to Full SDK
Both the public SDK and full SDK are toolkits for application development. Both the public SDK and full SDK are toolkits for application development. <br>The public SDK is intended for application developers and provided as standard in DevEco Studio. It does not contain system APIs – APIs required by system applications.
The public SDK is intended for application developers and provided as standard in DevEco Studio. It does not contain system APIs – APIs required by system applications.
The full SDK is intended for original equipment manufacturers (OEMs) and provided separately. It contains system APIs. The full SDK is intended for original equipment manufacturers (OEMs) and provided separately. It contains system APIs.
The SDK of API version 8 provided in DevEco Studio is a public SDK. If your project depends on any system API, such as the **animator** component, **xcomponent** component, or APIs in **@ohos.application.abilityManager.d.ts**, **@ohos.application.formInfo.d.ts**, or **@ohos.bluetooth.d.ts**, switch to the full SDK by performing the following steps. The SDK of API version 8 provided in DevEco Studio is a public SDK. If your project depends on any system API, such as the **animator** component, **xcomponent** component, or APIs in **@ohos.application.abilityManager.d.ts**, **@ohos.application.formInfo.d.ts**, or **@ohos.bluetooth.d.ts**, switch to the full SDK by performing the following steps.
## Downloading the Full SDK (of 3.1.1 Release in this example) > **NOTE**
>
Manually download the full SDK. For details, see the source code acquisition section in [OpenHarmony 3.1.1 Release](https://gitee.com/openharmony/docs/blob/master/en/release-notes/OpenHarmony-v3.1.1-release.md). > The screenshots in this document are for reference only.
![image-20220613161049897](figures/en-us_image_0000001655128646.png)
## Downloading the Full SDK
Manually download the system-specific full SDK package from the mirror. For details, see [Release Notes](../../release-notes/OpenHarmony-v3.2-beta2.md).
## Checking the Local SDK Location
## Checking the Local SDK Location<br>In this example, an eTS project is used. For a JS project, replace **ets** with **js**. In this example, an eTS project is used. For a JS project, replace **ets** with **js**.
In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the location of the local SDK. In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the location of the local SDK.
...@@ -38,61 +37,58 @@ In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the lo ...@@ -38,61 +37,58 @@ In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the lo
Note: The criteria for identifying system APIs are subject to the released API documentation. Note: The criteria for identifying system APIs are subject to the released API documentation.
2. Replace the SDK. The following uses public-SDK-3.x.x.x for Windows as an example.
2. Replace the SDK. The following uses full SDK 3.1.6.6 for Windows as an example.
a. Decompress the downloaded full SDK file: `ets-windows-3.x.x.x-Release.zip`
a. Decompress the downloaded full SDK file: `ets-windows-3.1.6.5-Release.zip`
![image-20220613165018184](figures/en-us_image_0000001655129264.png) ![image-20220613165018184](figures/en-us_image_0000001655129264.png)
b. Replace the SDK files. b. Replace the SDK files.
Back up the local SDK files. (Copy and rename the version number directory in the **ets** directory, or copy the entire **ets** directory to another local path.) Back up the local SDK files. (Copy and rename the version directory in the **ets** directory, or copy the entire **ets** directory to another local path.)
Go to the obtained location of the local installed SDK and back up the files therein. Go to the obtained location of the local installed SDK and back up the files therein.
![image-20220613161352157](figures/en-us_image_0000001655129041.png) ![image-20220613161352157](figures/en-us_image_0000001655129041.png)
Note: The name of the backup version number directory must be different from the value of **version** field in the **oh-uni-package.json** file. In the example below, the name of the backup version number directory is **3.1.6.6_backup**. Note: The name of the backup version directory must be different from the value of **version** field in the **oh-uni-package.json** file. In the example below, the name of the backup version directory is **3.x.x.x_backup**.
![image-20220613165018184](figures/en-us_image_0000001655129398.png) ![image-20220613165018184](figures/en-us_image_0000001655129398.png)
The configuration in the **oh-uni-package.json** file is as follows: The configuration in the **oh-uni-package.json** file is as follows, where the value of `apiVersion` is subject to the API version of the SDK, and the value of `version` is subject to the version number in the SDK file.
``` ```
{ {
"apiVersion": "8", "apiVersion": "X",
"displayName": "Ets", "displayName": "Ets",
"meta": { "meta": {
"metaVersion": "3.0.0" "metaVersion": "3.0.0"
}, },
"path": "ets", "path": "ets",
"releaseType": "Release", "releaseType": "Release",
"version": "3.1.6.6" "version": "3.x.x.x"
} }
``` ```
**Delete all files in the original SDK (3.1.6.6) directory.** Failure to do so may result in some files being unable to be overwritten. Delete all files in the original SDK (3.x.x.x) directory. Failure to do so may result in some files being unable to be overwritten.
Copy the full SDK to the location of the local SDK. Copy the full SDK to the location of the local SDK.
Copy all files in the **ets** directory in the full SDK to the **ets\3.1.6.6** directory in the location of the local SDK. Copy all files in the **ets** directory in the full SDK to the **ets\*3.x.x.x*** directory in the location of the local SDK.
Change the value of **version** in the **oh-uni-package.json** file to the current SDK version number. Change the value of **version** in the **oh-uni-package.json** file to the current SDK version number.
In the **3.1.6.6\build-tools\ets-loader** directory, open the **cmd/powerShell** window and run the **npm install** command to download the **node_modules** dependency package. In the ***3.x.x.x*\build-tools\ets-loader** directory, open the **cmd/powerShell** window and run the `npm install` command to download the **node_modules** dependency package.
![image-20220613171111405](figures/en-us_image_0000001655129333.png) ![image-20220613171111405](figures/en-us_image_0000001655129333.png)
c. Check for system APIs. c. Check for system APIs.
![image-20220613213038104](figures/en-us_image_0000001655129372.png) ![image-20220613213038104](figures/en-us_image_0000001655129372.png)
...@@ -501,7 +501,7 @@ Example of the **requestPermissions** attribute structure: ...@@ -501,7 +501,7 @@ Example of the **requestPermissions** attribute structure:
"usedScene": { "usedScene": {
"abilities": [ "abilities": [
"AudioAbility", "AudioAbility",
"VedioAbility", "VideoAbility",
], ],
"when": "inuse" "when": "inuse"
} }
......
...@@ -45,8 +45,8 @@ This document provides an ability with two pages. For more information about abi ...@@ -45,8 +45,8 @@ This document provides an ability with two pages. For more information about abi
## Tool Preparation ## Tool Preparation
1. Download the latest version of [DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta). 1. Download the latest version of [DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio#download).
2. Install DevEco Studio and configure the development environment. For details, see [Setting Up the Development Environment](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-setting-up-environment-0000001263160443). 2. Install DevEco Studio and configure the development environment. For details, see [Setting Up the Development Environment](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-setting-up-environment-0000001263160443).
When you are done, follow the instructions in [Getting Started with eTS in Stage Model](start-with-ets-stage.md), [Getting Started with eTS in FA Model](start-with-ets-fa.md), and [Getting Started with JavaScript in FA Model](../quick-start/start-with-js-fa.md). When you are done, follow the instructions in [Getting Started with eTS in Stage Model](start-with-ets-stage.md), [Getting Started with eTS in FA Model](start-with-ets-fa.md), and [Getting Started with JavaScript in FA Model](start-with-js-fa.md).
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
> >
> To use eTS, your DevEco Studio must be V3.0.0.601 Beta1 or later. > To use eTS, your DevEco Studio must be V3.0.0.601 Beta1 or later.
> >
> For best possible results, use [DevEco Studio V3.0.0.991 Beta4](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta) for your development. > For best possible results, use [DevEco Studio V3.0.0.993](https://developer.harmonyos.com/cn/develop/deveco-studio#download) for your development.
## Creating an eTS Project ## Creating an eTS Project
...@@ -128,7 +128,6 @@ ...@@ -128,7 +128,6 @@
![en-us_image_0000001311334932](figures/en-us_image_0000001311334932.png) ![en-us_image_0000001311334932](figures/en-us_image_0000001311334932.png)
> **NOTE** > **NOTE**
>
> You can also right-click the **pages** folder and choose **New** > **Page** from the shortcut menu. In this scenario, you do not need to manually configure page routes. > You can also right-click the **pages** folder and choose **New** > **Page** from the shortcut menu. In this scenario, you do not need to manually configure page routes.
- Configure the route for the second page, by setting **pages/second** under **module - js - pages** in the **config.json** The sample code is as follows: The sample code is as follows: - Configure the route for the second page, by setting **pages/second** under **module - js - pages** in the **config.json** The sample code is as follows: The sample code is as follows:
...@@ -140,7 +139,7 @@ ...@@ -140,7 +139,7 @@
"pages": [ "pages": [
"pages/index", "pages/index",
"pages/second" "pages/second"
], ]
} }
] ]
} }
...@@ -288,7 +287,7 @@ You can implement page redirection through the page router, which finds the targ ...@@ -288,7 +287,7 @@ You can implement page redirection through the page router, which finds the targ
1. Connect the development board running the OpenHarmony standard system to the computer. 1. Connect the development board running the OpenHarmony standard system to the computer.
2. Choose **File** > **Project Structure...** > **Project** > **SigningConfigs**, and select **Automatically generate signing**. Wait until the automatic signing is complete, and click **OK**. See the following figure. 2. Choose **File** > **Project Structure...** > **Project** > **SigningConfigs**, and select **Automatically generate signature**. Wait until the automatic signing is complete, and click **OK**. See the following figure.
![06](figures/06.png) ![06](figures/06.png)
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
> >
> To use eTS, your DevEco Studio must be V3.0.0.900 Beta3 or later. > To use eTS, your DevEco Studio must be V3.0.0.900 Beta3 or later.
> >
> For best possible results, use [DevEco Studio V3.0.0.991 Beta4](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta) for your development. > For best possible results, use [DevEco Studio V3.0.0.993](https://developer.harmonyos.com/cn/develop/deveco-studio#download) for your development.
## Creating an eTS Project ## Creating an eTS Project
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
![01](figures/01.png) ![01](figures/01.png)
2. On the project configuration page, set **Compile SDK** to **9**, **Model** to **Stage**, **Language** to **eTS** and retain the default values for other parameters. 2. On the project configuration page, set **Compile SDK** to **9**, **Model** to **Stage**, and retain the default values for other parameters.
![07](figures/07.png) ![07](figures/07.png)
...@@ -132,7 +132,6 @@ ...@@ -132,7 +132,6 @@
![09](figures/09.png) ![09](figures/09.png)
> **NOTE** > **NOTE**
>
> You can also right-click the **pages** folder and choose **New** > **Page** from the shortcut menu. In this scenario, you do not need to manually configure page routes. > You can also right-click the **pages** folder and choose **New** > **Page** from the shortcut menu. In this scenario, you do not need to manually configure page routes.
- Configure the route for the second page: In the **Project** window, choose **entry** > **src** > **main** > **resources** > **base** > **profile**. In the **main_pages.json** file, set **pages/second** under **src**. The sample code is as follows: - Configure the route for the second page: In the **Project** window, choose **entry** > **src** > **main** > **resources** > **base** > **profile**. In the **main_pages.json** file, set **pages/second** under **src**. The sample code is as follows:
...@@ -286,7 +285,7 @@ You can implement page redirection through the page router, which finds the targ ...@@ -286,7 +285,7 @@ You can implement page redirection through the page router, which finds the targ
1. Connect the development board running the OpenHarmony standard system to the computer. 1. Connect the development board running the OpenHarmony standard system to the computer.
2. Choose **File** > **Project Structure...** > **Project** > **SigningConfigs**, and select **Automatically generate signing**. Wait until the automatic signing is complete, and click **OK**. See the following figure. 2. Choose **File** > **Project Structure...** > **Project** > **SigningConfigs**, and select **Automatically generate signaure**. Wait until the automatic signing is complete, and click **OK**. See the following figure.
![06](figures/06.png) ![06](figures/06.png)
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
> **NOTE** > **NOTE**
> >
> For best possible results, use [DevEco Studio V3.0.0.991 Beta4](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta) for your development. > For best possible results, use [DevEco Studio V3.0.0.993](https://developer.harmonyos.com/cn/develop/deveco-studio#download) for your development.
## Creating a JavaScript Project ## Creating a JavaScript Project
...@@ -226,7 +226,7 @@ You can implement page redirection through the [page router](../ui/ui-js-buildin ...@@ -226,7 +226,7 @@ You can implement page redirection through the [page router](../ui/ui-js-buildin
1. Connect the development board running the OpenHarmony standard system to the computer. 1. Connect the development board running the OpenHarmony standard system to the computer.
2. Choose **File** > **Project Structure...** > **Project** > **Signing Configs**, and select **Automatically generate signing**. Wait until the automatic signing is complete, and click **OK**. See the following figure. 2. Choose **File** > **Project Structure...** > **Project** > **Signing Configs**, and select **Automatically generate signature**. Wait until the automatic signing is complete, and click **OK**. See the following figure.
![06](figures/06.png) ![06](figures/06.png)
......
...@@ -28,6 +28,8 @@ ...@@ -28,6 +28,8 @@
- application/[FormExtensionContext](js-apis-formextensioncontext.md) - application/[FormExtensionContext](js-apis-formextensioncontext.md)
- application/[PermissionRequestResult](js-apis-permissionrequestresult.md) - application/[PermissionRequestResult](js-apis-permissionrequestresult.md)
- application/[ServiceExtensionContext](js-apis-service-extension-context.md) - application/[ServiceExtensionContext](js-apis-service-extension-context.md)
- [InputMethodExtensionAbility](js-apis-inputmethod-extension-ability.md)
- [InputMethodExtensionContext](js-apis-inputmethod-extension-context.md)
- FA and Stage Models - FA and Stage Models
- [@ohos.ability.dataUriUtils](js-apis-DataUriUtils.md) - [@ohos.ability.dataUriUtils](js-apis-DataUriUtils.md)
- [@ohos.ability.errorCode](js-apis-ability-errorCode.md) - [@ohos.ability.errorCode](js-apis-ability-errorCode.md)
...@@ -136,6 +138,7 @@ ...@@ -136,6 +138,7 @@
- [@ohos.configPolicy](js-apis-config-policy.md) - [@ohos.configPolicy](js-apis-config-policy.md)
- [@ohos.enterpriseDeviceManager](js-apis-enterprise-device-manager.md) - [@ohos.enterpriseDeviceManager](js-apis-enterprise-device-manager.md)
- [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) - [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md)
- enterpriseDeviceManager/[DeviceSettingsManager](js-apis-enterpriseDeviceManager-DeviceSettingsManager.md)
- Security - Security
...@@ -216,6 +219,7 @@ ...@@ -216,6 +219,7 @@
- [@ohos.pasteboard](js-apis-pasteboard.md) - [@ohos.pasteboard](js-apis-pasteboard.md)
- [@ohos.screenLock](js-apis-screen-lock.md) - [@ohos.screenLock](js-apis-screen-lock.md)
- [@ohos.systemTime](js-apis-system-time.md) - [@ohos.systemTime](js-apis-system-time.md)
- [@ohos.systemTimer](js-apis-system-timer.md)
- [@ohos.wallpaper](js-apis-wallpaper.md) - [@ohos.wallpaper](js-apis-wallpaper.md)
- [Timer](js-apis-timer.md) - [Timer](js-apis-timer.md)
......
...@@ -14,6 +14,14 @@ The **AccessibilityExtensionAbility** module is based on the ExtensionAbility fr ...@@ -14,6 +14,14 @@ The **AccessibilityExtensionAbility** module is based on the ExtensionAbility fr
import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility' import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility'
``` ```
## Attributes
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
| Name | Type | Readable | Writable | Description |
| --------- | -------- | ---- | ---- | ------------------------- |
| context | [AccessibilityExtensionContext](js-apis-accessibility-extension-context.md) | Yes | No | Context of the accessibility extension ability. |
## AccessibilityEvent ## AccessibilityEvent
Defines an accessibility event. Defines an accessibility event.
...@@ -24,7 +32,7 @@ Defines an accessibility event. ...@@ -24,7 +32,7 @@ Defines an accessibility event.
| Name | Type | Readable | Writable | Description | | Name | Type | Readable | Writable | Description |
| --------- | ---------------------------------------- | ---- | ---- | ---------- | | --------- | ---------------------------------------- | ---- | ---- | ---------- |
| eventType | [EventType](js-apis-accessibility.md#EventType) \| [WindowUpdateType](js-apis-accessibility.md#WindowUpdateType) \| [TouchGuideType](touchguidetype) \| [GestureType](gesturetype) \| [PageUpdateType](pageupdatetype) | Yes | No | Event type. | | eventType | [EventType](js-apis-accessibility.md#eventtype) \| [WindowUpdateType](js-apis-accessibility.md#windowupdatetype) \| [TouchGuideType](#touchguidetype) \| [GestureType](#gesturetype) \| [PageUpdateType](#pageupdatetype) | Yes | No | Event type. |
| target | AccessibilityElement | Yes | No | Target component where the event occurs.| | target | AccessibilityElement | Yes | No | Target component where the event occurs.|
| timeStamp | number | Yes | No | Timestamp of the event. | | timeStamp | number | Yes | No | Timestamp of the event. |
...@@ -41,24 +49,6 @@ Defines a gesture path. ...@@ -41,24 +49,6 @@ Defines a gesture path.
| points | Array&lt;[GesturePoint](gesturepoint)&gt; | Yes | Yes | An array of gesture touch points. | | points | Array&lt;[GesturePoint](gesturepoint)&gt; | Yes | Yes | An array of gesture touch points. |
| durationTime | number | Yes | Yes | Total time consumed by the gesture.| | durationTime | number | Yes | Yes | Total time consumed by the gesture.|
### constructor
constructor(durationTime: number)
A constructor used to create a **GesturePath** object.
**Parameters**
| Name | Type | Mandatory | Description |
| ------------ | ------ | ---- | ------ |
| durationTime | number | Yes | Total time consumed by the gesture.|
**Example**
```typescript
let gesturePath = new GesturePath(100);
```
## GesturePoint ## GesturePoint
Defines a gesture touch point. Defines a gesture touch point.
...@@ -72,25 +62,6 @@ Defines a gesture touch point. ...@@ -72,25 +62,6 @@ Defines a gesture touch point.
| positionX | number | Yes | Yes | X-coordinate of the touch point.| | positionX | number | Yes | Yes | X-coordinate of the touch point.|
| positionY | number | Yes | Yes | Y-coordinate of the touch point.| | positionY | number | Yes | Yes | Y-coordinate of the touch point.|
### constructor
constructor(positionX: number, positionY: number)
A constructor used to create a **GesturePoint** object.
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ------- |
| positionX | number | Yes | X-coordinate of the touch point.|
| positionY | number | Yes | Y-coordinate of the touch point.|
**Example**
```typescript
let gesturePoint = new GesturePoint(100, 200);
```
## GestureType ## GestureType
Enumerates gesture types. Enumerates gesture types.
...@@ -190,7 +161,7 @@ Called when an event that matches the specified bundle and event type occurs. In ...@@ -190,7 +161,7 @@ Called when an event that matches the specified bundle and event type occurs. In
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----- | ---------------------------------------- | ---- | --------------- | | ----- | ---------------------------------------- | ---- | --------------- |
| event | [AccessibilityEvent](accessibilityevent) | Yes | Accessibility event. No value is returned.| | event | [AccessibilityEvent](#accessibilityevent) | Yes | Accessibility event. No value is returned.|
**Example** **Example**
...@@ -215,7 +186,7 @@ Called when a physical key is pressed. In this API, you can determine whether to ...@@ -215,7 +186,7 @@ Called when a physical key is pressed. In this API, you can determine whether to
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------- | | -------- | ---------------------------------------- | ---- | ----------------------- |
| keyEvent | [KeyEvent](js-apis-inputeventclient.md#KeyEvent) | Yes | Key event. If **true** is returned, the key is intercepted.| | keyEvent | [KeyEvent](js-apis-keyevent.md#KeyEvent) | Yes | Key event. If **true** is returned, the key is intercepted.|
**Example** **Example**
......
...@@ -4,11 +4,11 @@ The **DataShareExtensionAbility** module provides Extension abilities for data s ...@@ -4,11 +4,11 @@ The **DataShareExtensionAbility** module provides Extension abilities for data s
>**NOTE** >**NOTE**
> >
>The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> >
>The APIs provided by this module are system APIs. > The APIs provided by this module are system APIs.
> >
>The APIs of this module can be used only in the stage model. > The APIs of this module can be used only in the stage model.
## Modules to Import ## Modules to Import
...@@ -70,62 +70,6 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { ...@@ -70,62 +70,6 @@ export default class DataShareExtAbility extends DataShareExtensionAbility {
}; };
``` ```
## getFileTypes
getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void
Obtains the Multipurpose Internet Mail Extensions (MIME) types supported by a file. This API is called by the server and can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name | Type | Mandatory| Description |
| -------------- | ---------------------------------------- | ---- | ---------------------------------- |
| uri | string | Yes | URI of the file. |
| mimeTypeFilter | string | Yes | MIME types to match. |
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback invoked to return the MIME types obtained.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
getFileTypes(uri, mimeTypeFilter, callback) {
let err = {"code":0};
let ret = new Array("type01", "type02", "type03");
callback(err, ret);
}
};
```
## openFile
openFile?(uri: string, mode: string, callback: AsyncCallback&lt;number&gt;): void
Opens a file. This API is called by the server and can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------------------------------ |
| uri | string | Yes | URI of the file to open. |
| mode | string | Yes | File open mode, which can be read-only or read/write.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the file descriptor. |
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
openFile(uri, mode, callback) {
let err = {"code":0};
let fd = 0;
callback(err,fd);
}
};
```
## insert ## insert
insert?(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback&lt;number&gt;): void insert?(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback&lt;number&gt;): void
...@@ -301,33 +245,6 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { ...@@ -301,33 +245,6 @@ export default class DataShareExtAbility extends DataShareExtensionAbility {
}; };
``` ```
## getType
getType?(uri: string, callback: AsyncCallback&lt;string&gt;): void
Obtains the MIME type corresponding to the given URI. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name| Type| Mandatory| Description|
| ----- | ------ | ------ | ------ |
| uri | string | Yes | URI of the target data.|
| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the MIME type obtained.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
getType(uri, callback) {
let err = {"code":0};
let ret = "image";
callback(err, ret);
}
};
```
## batchInsert ## batchInsert
batchInsert?(uri: string, valueBuckets: Array&lt;ValuesBucket&gt;, callback: AsyncCallback&lt;number&gt;): void batchInsert?(uri: string, valueBuckets: Array&lt;ValuesBucket&gt;, callback: AsyncCallback&lt;number&gt;): void
......
...@@ -20,7 +20,7 @@ import Want from '@ohos.application.Want'; ...@@ -20,7 +20,7 @@ import Want from '@ohos.application.Want';
| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | | ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| deviceId | Read only | string | No | ID of the device running the ability. | | deviceId | Read only | string | No | ID of the device running the ability. |
| bundleName | Read only | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.| | bundleName | Read only | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.|
| abilityName | Read only | string | No | Name of the ability. If both **package** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| | abilityName | Read only | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.|
| uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| | uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.|
| type | Read only | string | No | MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | | type | Read only | string | No | MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. |
| flags | Read only | number | No | How the **Want** object will be handled. For details, see [flags](js-apis-featureAbility.md#flags).| | flags | Read only | number | No | How the **Want** object will be handled. For details, see [flags](js-apis-featureAbility.md#flags).|
...@@ -73,29 +73,32 @@ import Want from '@ohos.application.Want'; ...@@ -73,29 +73,32 @@ import Want from '@ohos.application.Want';
- Passing **RemoteObject** data - Passing **RemoteObject** data
``` js ``` js
import rpc from '@ohos.rpc';
import Ability from '@ohos.application.Ability'
class Stub extends rpc.RemoteObject { class Stub extends rpc.RemoteObject {
constructor(des) { constructor(des) {
if (typeof des == 'string') { if (typeof des == 'string') {
super(des); super(des);
} else { } else {
return null; return null;
} }
} }
onRemoteRequest(code, data, reply, option) { onRemoteRequest(code, data, reply, option) {
if (code === 1) { if (code === 1) {
console.log('onRemoteRequest called') console.log('onRemoteRequest called')
let token = data.readInterfaceToken(); let token = data.readInterfaceToken();
let num = data.readInt(); let num = data.readInt();
this.method(); this.method();
return true; return true;
} }
return false; return false;
} }
method() { method() {
console.log('method called'); console.log('method called');
} }
} }
var remoteObject = new Stub('want-test'); var remoteObject = new Stub('want-test');
...@@ -103,15 +106,16 @@ import Want from '@ohos.application.Want'; ...@@ -103,15 +106,16 @@ import Want from '@ohos.application.Want';
"deviceId": "", // An empty deviceId indicates the local device. "deviceId": "", // An empty deviceId indicates the local device.
"bundleName": "com.extreme.test", "bundleName": "com.extreme.test",
"abilityName": "MainAbility", "abilityName": "MainAbility",
"moduleName": "entry" // moduleName is optional. "moduleName": "entry", // moduleName is optional.
"parameters": { "parameters": {
"keyRemoteObject":{"type":"RemoteObject", "value":remoteObject} "keyRemoteObject":{"type":"RemoteObject", "value":remoteObject}
} }
}; };
this.context.startAbility(want, (error) => { this.context.startAbility(want, (error) => {
// Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability.
console.log("error.code = " + error.code) console.log("error.code = " + error.code)
}) })
```
<!--no_check--> ```
\ No newline at end of file <!--no_check-->
此差异已折叠。
...@@ -2746,7 +2746,7 @@ Defines the dialup options. ...@@ -2746,7 +2746,7 @@ Defines the dialup options.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------------------ | ---------------------------------- | ---- | ------------------------------------------------------------ | | ------------------------ | ---------------------------------- | ---- | ------------------------------------------------------------ |
| extras | boolean | No | Indication of a video call. <br>- **true**: video call<br>- **false** (default): voice call| | extras | boolean | No | Indication of a video call. <br>- **true**: video call<br>- **false** (default): voice call|
| accountId <sup>8+</sup> | number | No | Account ID. This is a system API. | | accountId <sup>8+</sup> | number | No | Account ID.<br>- **0**: card slot 1<br>- **1**: card slot 2<br>This is a system API. |
| videoState <sup>8+</sup> | [VideoStateType](#videostatetype7) | No | Video state type. This is a system API. | | videoState <sup>8+</sup> | [VideoStateType](#videostatetype7) | No | Video state type. This is a system API. |
| dialScene <sup>8+</sup> | [DialScene](#dialscene8) | No | Dialup scenario. This is a system API. | | dialScene <sup>8+</sup> | [DialScene](#dialscene8) | No | Dialup scenario. This is a system API. |
| dialType <sup>8+</sup> | [DialType](#dialtype8) | No | Dialup type. This is a system API. | | dialType <sup>8+</sup> | [DialType](#dialtype8) | No | Dialup type. This is a system API. |
......
...@@ -112,33 +112,37 @@ Registers the continuation management service and obtains a token. This API uses ...@@ -112,33 +112,37 @@ Registers the continuation management service and obtains a token. This API uses
``` ```
## continuationManager.on("deviceConnect")<sup>(deprecated)</sup> ## continuationManager.on("deviceConnect")<sup>(deprecated)</sup>
> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondeviceconnect) instead.
on(type: "deviceConnect", callback: Callback\<ContinuationResult>): void; on(type: "deviceConnect", callback: Callback\<ContinuationResult>): void;
Subscribes to device connection events. This API uses an asynchronous callback to return the result. Subscribes to device connection events. This API uses an asynchronous callback to return the result.
> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondeviceconnect9) instead.
## continuationManager.on("deviceDisconnect")<sup>(deprecated)</sup> ## continuationManager.on("deviceDisconnect")<sup>(deprecated)</sup>
> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondevicedisconnect) instead.
on(type: "deviceDisconnect", callback: Callback\<string>): void; on(type: "deviceDisconnect", callback: Callback\<string>): void;
Subscribes to device disconnection events. This API uses an asynchronous callback to return the result. Subscribes to device disconnection events. This API uses an asynchronous callback to return the result.
> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondevicedisconnect9) instead.
## continuationManager.off("deviceConnect")<sup>(deprecated)</sup> ## continuationManager.off("deviceConnect")<sup>(deprecated)</sup>
> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdeviceconnect) instead.
off(type: "deviceConnect", callback?: Callback\<ContinuationResult>): void; off(type: "deviceConnect", callback?: Callback\<ContinuationResult>): void;
Unsubscribes from device connection events. This API uses an asynchronous callback to return the result. Unsubscribes from device connection events. This API uses an asynchronous callback to return the result.
> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdeviceconnect9) instead.
## continuationManager.off("deviceDisconnect")<sup>(deprecated)</sup> ## continuationManager.off("deviceDisconnect")<sup>(deprecated)</sup>
> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdevicedisconnect) instead.
off(type: "deviceDisconnect", callback?: Callback\<string>): void; off(type: "deviceDisconnect", callback?: Callback\<string>): void;
Unsubscribes from device disconnection events. This API uses an asynchronous callback to return the result. Unsubscribes from device disconnection events. This API uses an asynchronous callback to return the result.
> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdevicedisconnect9) instead.
## continuationManager.on("deviceConnect")<sup>9+</sup> ## continuationManager.on("deviceConnect")<sup>9+</sup>
on(type: "deviceConnect", token: number, callback: Callback\<Array\<ContinuationResult>>): void; on(type: "deviceConnect", token: number, callback: Callback\<Array\<ContinuationResult>>): void;
......
...@@ -56,6 +56,8 @@ let options = {trim : false, declarationKey:"_declaration", ...@@ -56,6 +56,8 @@ let options = {trim : false, declarationKey:"_declaration",
nameKey : "_name", elementsKey : "_elements"} nameKey : "_name", elementsKey : "_elements"}
let result = JSON.stringify(conv.convert(xml, options)); let result = JSON.stringify(conv.convert(xml, options));
console.log(result) console.log(result)
// Output(Non compact)
// {"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}},"_elements":[{"_type":"element","_name":"note","_attributes":{"importance":"high","logged":"true"},"_elements":[{"_type":"element","_name":"title","_elements":[{"_type":"text","_text":"Happy"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"text","_text":"Work"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"text","_text":"Play"}]}]}]}
``` ```
## ConvertOptions ## ConvertOptions
......
...@@ -2,9 +2,11 @@ ...@@ -2,9 +2,11 @@
The **ValueBucket** module holds data in key-value (KV) pairs. You can use it to insert data into a database. The **ValueBucket** module holds data in key-value (KV) pairs. You can use it to insert data into a database.
>**NOTE** > **NOTE**
> >
>The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The APIs provided by this module are system APIs.
## Modules to Import ## Modules to Import
......
...@@ -2,9 +2,13 @@ ...@@ -2,9 +2,13 @@
The **DataShare** module allows an application to manage its own data and share data with other applications on the same device. The **DataShare** module allows an application to manage its own data and share data with other applications on the same device.
>**NOTE** > **NOTE**
> >
>The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The APIs provided by this module are system APIs.
>
> The APIs of this module can be used only in the stage model.
## Modules to Import ## Modules to Import
...@@ -87,85 +91,12 @@ dataShare.createDataShareHelper(this.context, uri).then((data) => { ...@@ -87,85 +91,12 @@ dataShare.createDataShareHelper(this.context, uri).then((data) => {
Provides a **DataShareHelper** instance to access or manage data on the server. Before calling an API provided by **DataShareHelper**, you must create a **DataShareHelper** instance using [createDataShareHelper](#datasharecreatedatasharehelper). Provides a **DataShareHelper** instance to access or manage data on the server. Before calling an API provided by **DataShareHelper**, you must create a **DataShareHelper** instance using [createDataShareHelper](#datasharecreatedatasharehelper).
This API can be used only in the stage model.
### openFile
openFile(uri: string, mode: string, callback: AsyncCallback&lt;number&gt;): void
Opens a file. This API uses an asynchronous callback to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ---------------------------------- |
| uri | string | Yes | URI of the file to open. |
| mode | string | Yes | File open mode.<br>**r** means to open a file for reading; **w** means to open a file for writing (erasing any data in the file); **wa** means to open a file in append mode for writing at the end of the file; **rw** means to open a file for both reading and writing.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the file descriptor. Otherwise, **err** is an error object.|
**Example**
```ts
import Ability from '@ohos.application.Ability'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.openFile(uri, "rwt", (err, data) => {
if (err != undefined) {
console.info("openFile failed, error message : " + err);
}else {
console.info("openFile succeed, data : " + data);
let fd = data;
}
});
```
### openFile
openFile(uri: string, mode: string): Promise&lt;number&gt;
Opens a file. This API uses a promise to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters**
| Name| Type | Mandatory| Description |
| ---- | ------ | ---- | ------------------------------------------------------------ |
| uri | string | Yes | URI of the file to open. |
| mode | string | Yes | File open mode.<br>**r** means to open a file for reading; **w** means to open a file for writing (erasing any data in the file); **wa** means to open a file in append mode for writing at the end of the file; **rw** means to open a file for both reading and writing.|
**Return value**
| Type | Description |
| --------------- | ---------------- |
| Promise&lt;number&gt; | Promise used to return the file descriptor.|
**Example**
```ts
import Ability from '@ohos.application.Ability'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.openFile(uri, "rwt").then((data) => {
console.info("openFile succeed, data : " + data);
let fd = data;
}).catch((err) => {
console.info("openFile failed, error message : " + err);
})
```
### on('dataChange') ### on('dataChange')
on(type: 'dataChange', uri: string, callback: AsyncCallback&lt;void&gt;): void on(type: 'dataChange', uri: string, callback: AsyncCallback&lt;void&gt;): void
Subscribes to changes of the specified data. After an observer is registered, the subscriber will receive a notification when the change notification is triggered (the **notifyChange()** method is called). This API uses an asynchronous callback to return the result. Subscribes to changes of the specified data. After an observer is registered, the subscriber will receive a notification when the change notification is triggered (the **notifyChange()** method is called). This API uses an asynchronous callback to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -174,7 +105,7 @@ This API can be used only in the stage model. ...@@ -174,7 +105,7 @@ This API can be used only in the stage model.
| -------- | -------------------- | ---- | ------------------------ | | -------- | -------------------- | ---- | ------------------------ |
| type | string | Yes | Event type to subscribe to. The value is **dataChange**, which indicates data change events.| | type | string | Yes | Event type to subscribe to. The value is **dataChange**, which indicates data change events.|
| uri | string | Yes | URI of the data.| | uri | string | Yes | URI of the data.|
| callback | AsyncCallback&lt;void&gt; | Yes | Called when the change notification is triggered. In this case, **err** is **undefined**. Otherwise, it is not called or **err** is an error object.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the data is changed, the value of **err** is **undefined**. Otherwise, this callback is not invoked or the value of **err** is an error object.|
**Example** **Example**
...@@ -193,8 +124,6 @@ off(type: 'dataChange', uri: string, callback?: AsyncCallback&lt;void&gt;): void ...@@ -193,8 +124,6 @@ off(type: 'dataChange', uri: string, callback?: AsyncCallback&lt;void&gt;): void
Unsubscribes from the changes of the specified data. This API uses an asynchronous callback to return the result. Unsubscribes from the changes of the specified data. This API uses an asynchronous callback to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -222,8 +151,6 @@ insert(uri: string, value: ValuesBucket, callback: AsyncCallback&lt;number&gt;): ...@@ -222,8 +151,6 @@ insert(uri: string, value: ValuesBucket, callback: AsyncCallback&lt;number&gt;):
Inserts a single data record into the database. This API uses an asynchronous callback to return the result. Inserts a single data record into the database. This API uses an asynchronous callback to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -259,8 +186,6 @@ insert(uri: string, value: ValuesBucket): Promise&lt;number&gt; ...@@ -259,8 +186,6 @@ insert(uri: string, value: ValuesBucket): Promise&lt;number&gt;
Inserts a single data record into the database. This API uses a promise to return the result. Inserts a single data record into the database. This API uses a promise to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -299,8 +224,6 @@ delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callbac ...@@ -299,8 +224,6 @@ delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callbac
Deletes one or more data records from the database. This API uses an asynchronous callback to return the result. Deletes one or more data records from the database. This API uses an asynchronous callback to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -335,8 +258,6 @@ delete(uri: string, predicates: dataSharePredicates.DataSharePredicates): Promis ...@@ -335,8 +258,6 @@ delete(uri: string, predicates: dataSharePredicates.DataSharePredicates): Promis
Deletes one or more data records from the database. This API uses a promise to return the result. Deletes one or more data records from the database. This API uses a promise to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -374,8 +295,6 @@ query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: ...@@ -374,8 +295,6 @@ query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns:
Queries data in the database. This API uses an asynchronous callback to return the result. Queries data in the database. This API uses an asynchronous callback to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -412,8 +331,6 @@ query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: ...@@ -412,8 +331,6 @@ query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns:
Queries data in the database. This API uses a promise to return the result. Queries data in the database. This API uses a promise to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -453,8 +370,6 @@ update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ...@@ -453,8 +370,6 @@ update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value:
Updates data in the database. This API uses an asynchronous callback to return the result. Updates data in the database. This API uses an asynchronous callback to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -496,8 +411,6 @@ update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ...@@ -496,8 +411,6 @@ update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value:
Updates data in the database. This API uses a promise to return the result. Updates data in the database. This API uses a promise to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -542,8 +455,6 @@ batchInsert(uri: string, values: Array&lt;ValuesBucket&gt;, callback: AsyncCallb ...@@ -542,8 +455,6 @@ batchInsert(uri: string, values: Array&lt;ValuesBucket&gt;, callback: AsyncCallb
Batch inserts data into the database. This API uses an asynchronous callback to return the result. Batch inserts data into the database. This API uses an asynchronous callback to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -577,8 +488,6 @@ batchInsert(uri: string, values: Array&lt;ValuesBucket&gt;): Promise&lt;number&g ...@@ -577,8 +488,6 @@ batchInsert(uri: string, values: Array&lt;ValuesBucket&gt;): Promise&lt;number&g
Batch inserts data into the database. This API uses a promise to return the result. Batch inserts data into the database. This API uses a promise to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -609,149 +518,12 @@ dataShareHelper.batchInsert(uri, vbs).then((data) => { ...@@ -609,149 +518,12 @@ dataShareHelper.batchInsert(uri, vbs).then((data) => {
}); });
``` ```
### getType
getType(uri: string, callback: AsyncCallback&lt;string&gt;): void
Obtains the Multipurpose Internet Mail Extensions (MIME) type of the specified data. This API uses an asynchronous callback to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | --------------------------------------------- |
| uri | string | Yes | URI of the data. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the MIME type obtained. Otherwise, **err** is an error object.|
**Example**
```ts
import Ability from '@ohos.application.Ability'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.getType(uri, (err, data)=>{
if (err != undefined) {
console.log("getType failed, error message : " + err);
}else{
console.log("getType succeed, data : " + data);
let result = data;
}
});
```
### getType
getType(uri: string): Promise&lt;string&gt;
Obtains the MIME type of the specified data. This API uses a promise to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters**
| Name| Type | Mandatory| Description |
| ---- | ------ | ---- | -------------------- |
| uri | string | Yes | URI of the data.|
**Return value**
| Type | Description |
| ---------------- | ----------------------------------- |
| Promise&lt;string&gt; | Promise used to return the MIME type obtained.|
**Example**
```ts
import Ability from '@ohos.application.Ability'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.getType(uri).then((data) => {
console.log("getType succeed, data : " + data);
}).catch((err) => {
console.log("getType failed, error message : " + err);
});
```
### getFileTypes
getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void
Obtains the supported MIME types. This API uses an asynchronous callback to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters**
| Name | Type | Mandatory| Description |
| -------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| uri | string | Yes | URI of the file. |
| mimeTypeFilter | string | Yes | MIME types to match. Example:<br>**\*/\***: Obtain all supported types.<br>**image/\***: Obtain the MIMEs with the main type of **image**.<br>**\*/jpg**: Obtain the MIMEs with the subtype of **jpg**.|
| callback | AsyncCallback<Array\<string>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the MIME types obtained. Otherwise, **err** is an error object.|
**Example**
```ts
import Ability from '@ohos.application.Ability'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
let mimeTypeFilter = "image/*";
dataShareHelper.getFileTypes(uri, mimeTypeFilter, (err,data) => {
if (err != undefined) {
console.log("getFileTypes failed, error message : " + err);
}else{
console.log("getFileTypes succeed, data : " + data);
}
});
```
### getFileTypes
getFileTypes(uri: string, mimeTypeFilter: string): Promise&lt;Array&lt;string&gt;&gt;
Obtains the supported MIME types. This API uses a promise to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters**
| Name | Type | Mandatory| Description |
| -------------- | ------ | ---- | ------------------------------------------------------------ |
| uri | string | Yes | URI of the file. |
| mimeTypeFilter | string | Yes | MIME types to match. Example:<br>**\*/\***: Obtain all supported types.<br>**image/\***: Obtain the MIMEs with the main type of **image**.<br>**\*/jpg**: Obtain the MIMEs with the subtype of **jpg**.|
**Return value**
| Type | Description |
| ------------------------ | ------------------------ |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the MIME types obtained.|
**Example**
```ts
import Ability from '@ohos.application.Ability'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
let mimeTypeFilter = "image/*";
dataShareHelper.getFileTypes(uri, mimeTypeFilter).then((data) => {
console.log("getFileTypes succeed, data : " + data);
}).catch((err) => {
console.log("getFileTypes failed, error message : " + err);
});
```
### normalizeUri ### normalizeUri
normalizeUri(uri: string, callback: AsyncCallback&lt;string&gt;): void normalizeUri(uri: string, callback: AsyncCallback&lt;string&gt;): void
Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the local device, but the normalized URI can be used across devices. This API uses an asynchronous callback to return the result. Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the local device, but the normalized URI can be used across devices. This API uses an asynchronous callback to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -781,8 +553,6 @@ normalizeUri(uri: string): Promise&lt;string&gt; ...@@ -781,8 +553,6 @@ normalizeUri(uri: string): Promise&lt;string&gt;
Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the local device, but the normalized URI can be used across devices. This API uses a promise to return the result. Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the local device, but the normalized URI can be used across devices. This API uses a promise to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -815,8 +585,6 @@ denormalizeUri(uri: string, callback: AsyncCallback&lt;string&gt;): void ...@@ -815,8 +585,6 @@ denormalizeUri(uri: string, callback: AsyncCallback&lt;string&gt;): void
Denormalizes a URI. This API uses an asynchronous callback to return the result. Denormalizes a URI. This API uses an asynchronous callback to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -846,8 +614,6 @@ denormalizeUri(uri: string): Promise&lt;string&gt; ...@@ -846,8 +614,6 @@ denormalizeUri(uri: string): Promise&lt;string&gt;
Denormalizes a URI. This API uses a promise to return the result. Denormalizes a URI. This API uses a promise to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -880,8 +646,6 @@ notifyChange(uri: string, callback: AsyncCallback&lt;void&gt;): void ...@@ -880,8 +646,6 @@ notifyChange(uri: string, callback: AsyncCallback&lt;void&gt;): void
Notifies the registered observer of data changes. This API uses an asynchronous callback to return the result. Notifies the registered observer of data changes. This API uses an asynchronous callback to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
...@@ -907,8 +671,6 @@ notifyChange(uri: string): Promise&lt;void&gt; ...@@ -907,8 +671,6 @@ notifyChange(uri: string): Promise&lt;void&gt;
Notifies the registered observer of data changes. This API uses a promise to return the result. Notifies the registered observer of data changes. This API uses a promise to return the result.
This API can be used only in the stage model.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters** **Parameters**
......
...@@ -676,7 +676,7 @@ Formats a phone number. ...@@ -676,7 +676,7 @@ Formats a phone number.
### getLocationName<sup>9+</sup> ### getLocationName<sup>9+</sup>
static getLocationName(number: string, locale: string): string getLocationName(number: string, locale: string): string
Obtains the home location of a phone number. Obtains the home location of a phone number.
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册