提交 4f6dbf0f 编写于 作者: 田雨 提交者: Gitee

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

Signed-off-by: N田雨 <tianyu55@huawei.com>
......@@ -17,5 +17,7 @@
- Other
- [WantAgent Development](wantagent.md)
- [Ability Assistant Usage](ability-assistant-guidelines.md)
- [ContinuationManager Development](continuationmanager.md)
- [Test Framework Usage](ability-delegator.md)
......@@ -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.
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.
- 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
| 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. |
| 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). |
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)
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));
});
```
......@@ -3,7 +3,7 @@
## 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 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:
- 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.
| 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 |
| 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**) |
| 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**) |
| 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.<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) |
| 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 |
......@@ -189,7 +189,6 @@ Configure the **config.json** file for the widget.
"scheduledUpdateTime": "10:30",
"supportDimensions": ["2*2"],
"type": "JS",
"updateDuration": 1,
"updateEnabled": true
}]
}]
......@@ -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 tempFlag = want.parameters["ohos.extra.param.key.form_temporary"];
// 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);
let obj = {
......@@ -227,7 +226,7 @@ You should override **onDestroy** to delete widget data.
console.log('FormAbility onDestroy');
// 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);
}
```
......@@ -336,7 +335,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
"actions": {
"routerEvent": {
"action": "router",
"abilityName": "com.example.MyApplication.hmservice.FormAbility",
"abilityName": "com.example.entry.MainAbility",
"params": {
"message": "add detail"
}
......@@ -349,3 +348,57 @@ Now you've got a widget shown below.
![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
# Ability Development
## 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.
- 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).
......@@ -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).
### 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 |
| ----------- | ------- |---------------- |
......@@ -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.|
| 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
{
"module": {
......@@ -87,7 +87,7 @@ To create Page abilities for an application in the stage model, you must impleme
onWindowStageCreate(windowStage) {
console.log("MainAbility onWindowStageCreate")
windowStage.loadContent("pages/index").then((data) => {
windowStage.loadContent("pages/index").then(() => {
console.log("MainAbility load content succeed")
}).catch((error) => {
console.error("MainAbility load content failed with error: " + JSON.stringify(error))
......@@ -149,9 +149,9 @@ export default class MainAbility extends Ability {
}
```
### 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
"requestPermissions": [
{
......@@ -231,8 +231,8 @@ var want = {
"bundleName": "com.example.MyApplication",
"abilityName": "MainAbility"
};
context.startAbility(want).then((data) => {
console.log("Succeed to start ability with data: " + JSON.stringify(data))
context.startAbility(want).then(() => {
console.log("Succeed to start ability")
}).catch((error) => {
console.error("Failed to start ability with error: "+ JSON.stringify(error))
})
......@@ -248,8 +248,8 @@ var want = {
"bundleName": "com.example.MyApplication",
"abilityName": "MainAbility"
};
context.startAbility(want).then((data) => {
console.log("Succeed to start remote ability with data: " + JSON.stringify(data))
context.startAbility(want).then(() => {
console.log("Succeed to start remote ability")
}).catch((error) => {
console.error("Failed to start remote ability with error: " + JSON.stringify(error))
})
......
......@@ -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 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:
......@@ -49,10 +49,10 @@ The **FormExtension** class also has a member context, that is, the **FormExtens
**Table 2** FormExtensionContext APIs
| 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. |
| updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise\<void> | Updates a widget. This API uses a promise to return the result.|
| API | Description |
| :----------------------------------------------------------- | :----------------------------------------------------------- |
| 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.)|
| 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).
......@@ -86,7 +86,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo
export default class FormAbility extends FormExtension {
onCreate(want) {
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 = {
"title": "titleOnCreate",
"detail": "detailOnCreate"
......@@ -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 |
| 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 |
| scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | 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**) |
| 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.<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) |
| 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) |
......@@ -200,7 +200,6 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo
"defaultDimension": "2*2",
"updateEnabled": true,
"scheduledUpdateTime": "10:30",
"updateDuration": 1,
"formConfigAbility": "ability://ohos.samples.FormApplication.MainAbility"
}]
}
......@@ -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 formName = want.parameters["ohos.extra.param.key.form_name"];
let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"];
// Persistently store widget data for subsequent use, such as widget instance retrieval and update.
// The storeFormInfo API is not implemented here. For details about the implementation, see "Samples" below.
// Persistently store widget data for subsequent use, such as widget instance retrieval or update.
// The storeFormInfo API is not implemented here.
storeFormInfo(formId, formName, tempFlag, want);
let obj = {
......@@ -238,7 +237,7 @@ You should override **onDestroy** to delete widget data.
console.log('FormAbility onDestroy');
// 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);
}
```
......@@ -277,10 +276,11 @@ onUpdate(formId) {
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.
- hml:
- In the HML file:
```html
<div class="container">
<stack>
......@@ -295,7 +295,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
</div>
```
- css:
- In the CSS file:
```css
.container {
......@@ -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
{
"data": {
......@@ -346,7 +346,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
"actions": {
"routerEvent": {
"action": "router",
"abilityName": "com.example.MyApplication.hmservice.FormAbility",
"abilityName": "MainAbility",
"params": {
"message": "add detail"
}
......@@ -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.
![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
## 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
**Table 1** ServiceExtensionAbility lifecycle APIs
|API|Description|
|:------|:------|
|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.|
|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.|
|onDestroy(): void|Called when **terminateSelf** is invoked to terminate the ability.|
|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.|
|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.|
|onDestroy(): void|Called when `terminateSelf` is invoked to terminate the ability.|
## Constraints
......@@ -24,7 +24,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p
## 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
......@@ -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
import ServiceExtensionAbility from '@ohos.application.ServiceExtensionAbility'
......
......@@ -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.
For details about how to apply for permissions, see [Access Control Development](../security/accesstoken-guidelines.md).
The following table describes the related APIs.
| API | Description |
......@@ -65,7 +67,7 @@ httpRequest.request(
console.info('cookies:' + data.cookies); // 8+
} else {
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();
}
}
......
......@@ -74,7 +74,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
console.log("on close")
});
// Bind the IP address and port number.
// Bind the local IP address and port number.
let bindAddress = {
address: '192.168.xx.xx',
port: 1234, // Bound port, for example, 1234.
......
......@@ -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. |
| 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. |
| 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. |
| 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. |
......
......@@ -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.
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
The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management.
## 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.
## 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).
**Table 1** Open USB APIs
......@@ -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. |
| setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets 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. |
| releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. |
| getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. |
......
......@@ -2,89 +2,164 @@
## 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
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 |
| ------------------------------------------------------------ | -------------- | ------------------------------------------------------------ |
| 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. |
**Table 1** APIs for application event logging
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 |
| ------------------------------ | ------------ | ------------------------------------------------------------ |
| 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. |
If a promise is used, the return value can also be processed in the promise in a similar way.
## 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 |
| ----------- | ---------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| 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. |
**Table 2** APIs for event logging configuration
| 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
import hiAppEvent from '@ohos.hiAppEvent'
| API | Description |
| ----------------- | -------------------- |
| 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 {
data: {
title: ""
},
onInit() {
this.title = this.$t('strings.world');
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
// 1. Callback mode
hiAppEvent.write("start_event", hiAppEvent.EventType.BEHAVIOR, {"int_data":100, "str_data":"strValue"}, (err, value) => {
if (err) {
console.error(`failed to write event because ${err.code}`);
return;
build() {
Row() {
Column() {
Text(this.message)
.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
hiAppEvent.write("start_event", hiAppEvent.EventType.BEHAVIOR, {"int_data":100, "str_data":"strValue"})
.then((value) => {
console.log(`success to write event: ${value}`);
}).catch((err) => {
console.error(`failed to write event because ${err.code}`);
});
// 3. Set the application event logging switch.
hiAppEvent.configure({
disable: true
});
Button("2 addWatcherTest").onClick(()=>{
hiAppEvent.addWatcher({
name: "watcher1",
appEventFilters: [{ domain: "test_domain" }],
triggerCondition: {
row: 2,
size: 1000,
timeOut: 2
},
onTrigger: function (curRow, curSize, holder) {
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.
hiAppEvent.configure({
maxStorage: '100M'
});
Button("3 removeWatcherTest").onClick(()=>{
hiAppEvent.removeWatcher({
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 @@
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
- **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)
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.
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.
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).
## 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
## 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
......@@ -119,7 +118,7 @@ You can use APIs provided in the following table to obtain the system language a
```js
var calendar = i18n.getCalendar("zh-CN", "gregory);
var calendar = i18n.getCalendar("zh-CN", "gregory");
```
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
## 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
......@@ -245,7 +244,7 @@ The **unitConvert** API is provided to help you implement measurement conversion
### How to Develop
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
......@@ -260,7 +259,7 @@ The **unitConvert** API is provided to help you implement measurement conversion
## 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
......@@ -281,7 +280,7 @@ The **unitConvert** API is provided to help you implement measurement conversion
```js
var indexUtil = getInstance("zh-CN");
var indexUtil = i18n.getInstance("zh-CN");
```
2. Obtain the index list.
......@@ -312,7 +311,7 @@ The **unitConvert** API is provided to help you implement measurement conversion
## 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
......
# 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.
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.
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).
> **NOTE**
>
......@@ -9,7 +8,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
## 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
......@@ -27,7 +26,7 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc
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 (-).
- 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
```js
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);
```
......@@ -77,7 +76,7 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc
## 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
......@@ -102,7 +101,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
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
var options = {dateStyle: "full", timeStyle: "full"};
......@@ -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.
```js
Date date = new Date();
var date = new Date();
var formatResult = dateTimeFormat.format(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.
```js
Date startDate = new Date();
Date endDate = new Date();
var formatResult = dateTimeFormat.formatRange(startDate, endDate);
var startDate = new Date(2021, 11, 17, 3, 24, 0);
var endDate = new Date(2021, 11, 18, 3, 24, 0);
var datefmt = new Intl.DateTimeFormat("en-GB");
datefmt.formatRange(startDate, endDate);
```
4. Obtain attributes of the **DateTimeFormat** object.
......@@ -139,7 +139,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
## 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
......@@ -163,7 +163,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for
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
var options = {compactDisplay: "short", notation: "compact"};
......@@ -190,7 +190,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for
## 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
......@@ -214,7 +214,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on
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
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
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
var str1 = "first string";
......@@ -241,7 +241,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on
## 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
......@@ -264,10 +264,10 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu
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
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.
......@@ -282,7 +282,7 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu
## 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
......@@ -307,7 +307,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r
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
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
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
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)
# 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).
......@@ -501,7 +501,7 @@ Example of the **requestPermissions** attribute structure:
"usedScene": {
"abilities": [
"AudioAbility",
"VedioAbility",
"VideoAbility",
],
"when": "inuse"
}
......
......@@ -28,6 +28,8 @@
- application/[FormExtensionContext](js-apis-formextensioncontext.md)
- application/[PermissionRequestResult](js-apis-permissionrequestresult.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
- [@ohos.ability.dataUriUtils](js-apis-DataUriUtils.md)
- [@ohos.ability.errorCode](js-apis-ability-errorCode.md)
......
......@@ -20,7 +20,7 @@ import Want from '@ohos.application.Want';
| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| 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.|
| 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**.|
| 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).|
......@@ -73,29 +73,32 @@ import Want from '@ohos.application.Want';
- Passing **RemoteObject** data
``` js
import rpc from '@ohos.rpc';
import Ability from '@ohos.application.Ability'
class Stub extends rpc.RemoteObject {
constructor(des) {
if (typeof des == 'string') {
super(des);
} else {
return null;
}
}
onRemoteRequest(code, data, reply, option) {
if (code === 1) {
console.log('onRemoteRequest called')
let token = data.readInterfaceToken();
let num = data.readInt();
this.method();
return true;
}
return false;
}
method() {
console.log('method called');
}
constructor(des) {
if (typeof des == 'string') {
super(des);
} else {
return null;
}
}
onRemoteRequest(code, data, reply, option) {
if (code === 1) {
console.log('onRemoteRequest called')
let token = data.readInterfaceToken();
let num = data.readInt();
this.method();
return true;
}
return false;
}
method() {
console.log('method called');
}
}
var remoteObject = new Stub('want-test');
......@@ -103,15 +106,16 @@ import Want from '@ohos.application.Want';
"deviceId": "", // An empty deviceId indicates the local device.
"bundleName": "com.extreme.test",
"abilityName": "MainAbility",
"moduleName": "entry" // moduleName is optional.
"moduleName": "entry", // moduleName is optional.
"parameters": {
"keyRemoteObject":{"type":"RemoteObject", "value":remoteObject}
"keyRemoteObject":{"type":"RemoteObject", "value":remoteObject}
}
};
this.context.startAbility(want, (error) => {
// Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability.
console.log("error.code = " + error.code)
})
```
<!--no_check-->
\ No newline at end of file
```
<!--no_check-->
......@@ -2746,7 +2746,7 @@ Defines the dialup options.
| Name | Type | Mandatory| Description |
| ------------------------ | ---------------------------------- | ---- | ------------------------------------------------------------ |
| 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. |
| 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. |
......
......@@ -112,33 +112,37 @@ Registers the continuation management service and obtains a token. This API uses
```
## 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;
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>
> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondevicedisconnect) instead.
on(type: "deviceDisconnect", callback: Callback\<string>): void;
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>
> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdeviceconnect) instead.
off(type: "deviceConnect", callback?: Callback\<ContinuationResult>): void;
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>
> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdevicedisconnect) instead.
off(type: "deviceDisconnect", callback?: Callback\<string>): void;
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>
on(type: "deviceConnect", token: number, callback: Callback\<Array\<ContinuationResult>>): void;
......
......@@ -56,6 +56,8 @@ let options = {trim : false, declarationKey:"_declaration",
nameKey : "_name", elementsKey : "_elements"}
let result = JSON.stringify(conv.convert(xml, options));
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
......
......@@ -28,29 +28,42 @@ Enumerates the display states.
| STATE_VR | 5 | The display is in VR mode.|
| STATE_ON_SUSPEND | 6 | The display is powered on, and the CPU is suspended.|
## Rect<sup>9+</sup>
## Display
Describes a rectangle on the display.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
Describes the attributes of a display.
| Name | Type| Readable| Writable| Description |
| ------ | -------- | ---- | ---- | ------------------ |
| left | number | Yes | Yes | Left boundary of the rectangle.|
| top | number | Yes | Yes | Top boundary of the rectangle.|
| width | number | Yes | Yes | Width of the rectangle. |
| height | number | Yes | Yes | Height of the rectangle. |
## WaterfallDisplayAreaRects<sup>9+</sup>
Describes the curved area (an area that is not intended for displaying content) on the waterfall display.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| id | number | Yes| No| ID of the display.|
| name | string | Yes| No| Name of the display.|
| alive | boolean | Yes| No| Whether the display is alive.|
| state | [DisplayState](#displaystate) | Yes| No| State of the display.|
| refreshRate | number | Yes| No| Refresh rate of the display.|
| rotation | number | Yes| No| Screen rotation angle of the display.|
| width | number | Yes| No| Width of the display, in pixels.|
| height | number | Yes| No| Height of the display, in pixels.|
| densityDPI | number | Yes| No| Screen density of the display, in DPI.|
| densityPixels | number | Yes| No| Screen density of the display, in pixels.|
| scaledDensity | number | Yes| No| Scaling factor for fonts displayed on the display.|
| xDPI | number | Yes| No| Exact physical dots per inch of the screen in the horizontal direction.|
| yDPI | number | Yes| No| Exact physical dots per inch of the screen in the vertical direction.|
| Name | Type | Readable| Writable| Description |
| ------ | ------------- | ---- | ---- | ------------------ |
| left | [Rect](#rect9) | Yes | No | Bounding rectangle for the curved area, which is located on the left of the display surface.|
| top | [Rect](#rect9) | Yes | No | Bounding rectangle for the curved area, which is located at the top of the display surface.|
| right | [Rect](#rect9) | Yes | No | Bounding rectangle for the curved area, which is located on the right of the display surface.|
| bottom | [Rect](#rect9) | Yes | No | Bounding rectangle for the curved area, which is located at the bottom of the display surface.|
## CutoutInfo<sup>9+</sup>
Describes the cutout, which is an area that is not intended for displaying content on the display.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
| Name | Type | Readable| Writable| Description |
| --------------------------- | ------------- | ---- | ---- | ------------------ |
| boundingRects | Array\<[Rect](#rect9)> | Yes | No | Bounding rectangle for punch holes and notches.|
| waterfallDisplayAreaRects | [WaterfallDisplayAreaRects](#waterfalldisplayarearects9) | Yes| No| Curved area on the waterfall display.|
## display.getDefaultDisplay
......@@ -61,22 +74,24 @@ Obtains the default display object. This API uses an asynchronous callback to re
**System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[Display](#display)&gt; | Yes| Callback used to return the default display object.|
**Example**
```js
var displayClass = null;
display.getDefaultDisplay((err, data) => {
if (err.code) {
console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data));
displayClass = data;
});
```
```js
var displayClass = null;
display.getDefaultDisplay((err, data) => {
if (err.code) {
console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data));
displayClass = data;
});
```
## display.getDefaultDisplay
......@@ -94,14 +109,16 @@ Obtains the default display object. This API uses a promise to return the result
**Example**
```js
let promise = display.getDefaultDisplay();
promise.then(() => {
console.log('getDefaultDisplay success');
}).catch((err) => {
console.log('getDefaultDisplay fail: ' + JSON.stringify(err));
});
```
```js
var displayClass = null;
let promise = display.getDefaultDisplay();
promise.then((data) => {
displayClass = data;
console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data));
}).catch((err) => {
console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err));
});
```
## display.getDefaultDisplaySync<sup>9+</sup>
......@@ -139,15 +156,15 @@ Obtains all display objects. This API uses an asynchronous callback to return th
**Example**
```js
display.getAllDisplay((err, data) => {
if (err.code) {
console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data))
});
```
```js
display.getAllDisplay((err, data) => {
if (err.code) {
console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data));
});
```
## display.getAllDisplay
......@@ -165,22 +182,22 @@ Obtains all display objects. This API uses a promise to return the result.
**Example**
```js
let promise = display.getAllDisplay();
promise.then(() => {
console.log('getAllDisplay success');
}).catch((err) => {
console.log('getAllDisplay fail: ' + JSON.stringify(err));
});
```
```js
let promise = display.getAllDisplay();
promise.then((data) => {
console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data));
}).catch((err) => {
console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err));
});
```
## display.hasPrivateWindow<sup>9+</sup>
hasPrivateWindow(displayId: number): boolean
Checks whether there is a visible privacy window on a display. The privacy window can be set by calling **[setPrivacyMode](js-apis-window.md#setprivacymode7)**. The content in the privacy window cannot be captured or recorded.
Checks whether there is a visible privacy window on a display. The privacy window can be set by calling `[setPrivacyMode](js-apis-window.md#setprivacymode7)`. The content in the privacy window cannot be captured or recorded.
This is a system API.
**System API**: This is a system API.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
......@@ -194,21 +211,31 @@ This is a system API.
| Type | Description |
| -------------------------------- |-----------------------------------------------------------------------|
|boolean | Whether there is a visible privacy window on the display.<br>The value **true** means that there is a visible privacy window on the display, and **false** means the opposite.<br>|
|boolean | Whether there is a visible privacy window on the display.<br>The value `true` means that there is a visible privacy window on the display, and `false` means the opposite.<br>|
**Example**
```js
var ret = display.hasPrivateWindow(displayClass.id);
if (ret == undefined) {
console.log("HasPrivateWindow undefined.");
}
if (ret) {
console.log("HasPrivateWindow.");
} else if (!ret) {
console.log("Don't HasPrivateWindow.");
```js
var displayClass = null;
display.getDefaultDisplay((err, data) => {
if (err.code) {
console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err));
return;
}
```
console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data));
displayClass = data;
});
var ret = display.hasPrivateWindow(displayClass.id);
if (ret == undefined) {
console.log("Failed to check has privateWindow or not.");
}
if (ret) {
console.log("There has privateWindow.");
} else if (!ret) {
console.log("There has no privateWindow.");
}
```
## display.on('add'|'remove'|'change')
......@@ -219,19 +246,20 @@ Subscribes to display changes.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type.<br>- **add**, indicating the display addition event.<br>- **remove**, indicating the display removal event.<br>- **change**, indicating the display change event.|
| callback | Callback&lt;number&gt; | Yes| Callback used to return the ID of the display.|
**Example**
```js
var callback = (data) => {
console.info('Listening enabled. Data: ' + JSON.stringify(data))
}
display.on("add", callback);
```
```js
var callback = (data) => {
console.info('Listening enabled. Data: ' + JSON.stringify(data));
}
display.on("add", callback);
```
## display.off('add'|'remove'|'change')
......@@ -242,12 +270,81 @@ Unsubscribes from display changes.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type.<br>- **add**, indicating the display addition event.<br>- **remove**, indicating the display removal event.<br>- **change**, indicating the display change event.|
| callback | Callback&lt;number&gt; | No| Callback used to return the ID of the display.|
**Example**
```js
display.off("remove");
```
```js
display.off("remove");
```
## Display
Implements a `Display` instance, with properties and APIs defined.
To call an API in the following API examples, you must first use `[getAllDisplay()](#displaygetalldisplay)`, `[getDefaultDisplay()](#displaygetdefaultdisplay)`, or `[getDefaultDisplaySync()](#displaygetdefaultdisplaysync)` to obtain a `Display` instance.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| id | number | Yes| No| ID of the display.|
| name | string | Yes| No| Name of the display.|
| alive | boolean | Yes| No| Whether the display is alive.|
| state | [DisplayState](#displaystate) | Yes| No| State of the display.|
| refreshRate | number | Yes| No| Refresh rate of the display.|
| rotation | number | Yes| No| Screen rotation angle of the display.|
| width | number | Yes| No| Width of the display, in pixels.|
| height | number | Yes| No| Height of the display, in pixels.|
| densityDPI | number | Yes| No| Screen density of the display, in DPI.|
| densityPixels | number | Yes| No| Screen density of the display, in pixels.|
| scaledDensity | number | Yes| No| Scaling factor for fonts displayed on the display.|
| xDPI | number | Yes| No| Exact physical dots per inch of the screen in the horizontal direction.|
| yDPI | number | Yes| No| Exact physical dots per inch of the screen in the vertical direction.|
### getCutoutInfo<sup>9+</sup>
getCutoutInfo(callback: AsyncCallback&lt;CutoutInfo&gt;): void
Obtains the cutout information of the display. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
| Name | Type | Mandatory| Description |
| ----------- | --------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback&lt;[CutoutInfo](#cutoutinfo9)&gt; | Yes | Callback used to If the operation is successful, `err` is `undefined` and `data` is the `CutoutInfo` object obtained. Otherwise, `err` is an error object.|
**Example**
```js
displayClass.getCutoutInfo((err, data) => {
if (err.code) {
console.error('Failed to get cutoutInfo. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in getting cutoutInfo. data: ' + JSON.stringify(data));
})
```
### getCutoutInfo<sup>9+</sup>
getCutoutInfo(): Promise&lt;CutoutInfo&gt;
Obtains the cutout information of the display. This API uses a promise to return the result.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
**Return value**
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;[CutoutInfo](#cutoutinfo9)&gt; | Promise used to return the `CutoutInfo` object.|
**Example**
```js
let promise = displayClass.getCutoutInfo();
promise.then((data) => {
console.info('Succeeded in getting cutoutInfo. Data: ' + JSON.stringify(data));
});
```
......@@ -2,7 +2,7 @@
> **NOTE**<br/>
> - The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module will be deprecated and are not recommended for use. An exception will be thrown if any of the APIs is called.
> - The APIs of this module have been deprecated since API version 9 and are not recommended for use. An exception will be thrown if any of the APIs is called.
## Modules to Import
......@@ -10,7 +10,7 @@
import document from '@ohos.document';
```
## document.choose
## document.choose<sup>(deprecated)</sup>
choose(types? : string[]): Promise&lt;string&gt;
......@@ -20,15 +20,15 @@ Chooses files of the specified types using the file manager. This API uses a pro
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------------- |
| types | string[] | No | Types of the files to choose. |
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------------- |
| types | string[] | No | Types of the files to choose.|
**Return value**
| Type | Description |
| --------------------- | -------------- |
| Promise&lt;string&gt; | Promise used to return the result. An error code is returned.|
| Type | Description |
| --------------------- | -------------- |
| Promise&lt;string&gt; | Promise used to return the result. An error code is returned.|
**Example**
......@@ -36,7 +36,7 @@ Chooses files of the specified types using the file manager. This API uses a pro
let types = [];
document.choose(types);
```
## document.choose
## document.choose<sup>(deprecated)</sup>
choose(callback:AsyncCallback&lt;string&gt;): void
......@@ -46,9 +46,9 @@ Chooses a file using the file manager. This API uses an asynchronous callback to
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result. An error code is returned.|
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result. An error code is returned.|
**Example**
......@@ -58,7 +58,7 @@ Chooses a file using the file manager. This API uses an asynchronous callback to
// Do something with the URI.
});
```
## document.choose
## document.choose<sup>(deprecated)</sup>
choose(types:string[], callback:AsyncCallback&lt;string&gt;): void
......@@ -68,10 +68,10 @@ Chooses files using the file manager. This API uses an asynchronous callback to
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- |
| types | string[] | No | Types of the files to choose.|
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result. An error code is returned.|
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- |
| types | string[] | No | Types of the files to choose.|
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result. An error code is returned.|
**Example**
......@@ -83,7 +83,7 @@ Chooses files using the file manager. This API uses an asynchronous callback to
});
```
## document.show
## document.show<sup>(deprecated)</sup>
show(uri:string, type:string):Promise&lt;void&gt;
......@@ -93,16 +93,16 @@ Opens a file. This API uses a promise to return the result.
**Parameters**
| Name| Type | Mandatory| Description |
| ---- | ------ | ---- | ---------------------------- |
| uri | string | Yes | URI of the file to open.|
| type | string | Yes | Type of the file to open.|
| Name| Type | Mandatory| Description |
| ---- | ------ | ---- | ---------------------------- |
| uri | string | Yes | URI of the file to open.|
| type | string | Yes | Type of the file to open.|
**Return value**
| Type | Description |
| --------------------- | ------------ |
| Promise&lt;void&gt; | Promise used to return the result. An error code is returned.|
| Type | Description |
| --------------------- | ------------ |
| Promise&lt;void&gt; | Promise used to return the result. An error code is returned.|
**Example**
......@@ -112,7 +112,7 @@ Opens a file. This API uses a promise to return the result.
document.show(uri, type);
```
## document.show
## document.show<sup>(deprecated)</sup>
show(uri:string, type:string, callback:AsyncCallback&lt;void&gt;): void
......@@ -122,11 +122,11 @@ Opens a file. This API uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- |
| uri | string | Yes | URI of the file to open.|
| type | string | Yes | Type of the file to open.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. An error code is returned. |
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- |
| uri | string | Yes | URI of the file to open.|
| type | string | Yes | Type of the file to open.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. An error code is returned. |
**Example**
......
......@@ -33,14 +33,8 @@ var observer = {
console.log('onUnhandledException, errorMsg: ', errorMsg)
}
}
errorManager.registerErrorObserver(observer)
.then((data) => {
console.log('----------- registerErrorObserver success ----------', data);
})
.catch((err) => {
console.log('----------- registerErrorObserver fail ----------', err);
})
const registerErrorObserverNumber=errorManager.registerErrorObserver(observer)
console.info(registerErrorObserverNumber)
```
## ErrorManager.unregisterErrorObserver
......
......@@ -96,10 +96,27 @@ Enumerates the widget parameters.
| Name | Value | Description |
| ----------- | ---- | ------------ |
| IDENTITY_KEY | "ohos.extra.param.key.form_identity" | ID of a widget.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| IDENTITY_KEY<sup>9+</sup> | "ohos.extra.param.key.form_identity" | ID of a widget.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| DIMENSION_KEY | "ohos.extra.param.key.form_dimension" | Widget dimension. |
| NAME_KEY | "ohos.extra.param.key.form_name" | Widget name. |
| MODULE_NAME_KEY | "ohos.extra.param.key.module_name" | Name of the module to which the widget belongs. |
| WIDTH_KEY | "ohos.extra.param.key.form_width" | Widget width. |
| HEIGHT_KEY | "ohos.extra.param.key.form_height" | Widget height. |
| TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. |
| ABILITY_NAME_KEY<sup>9+</sup> | "ohos.extra.param.key.ability_name" | Ability name. |
| DEVICE_ID_KEY<sup>9+</sup> | "ohos.extra.param.key.device_id" | Device ID.<br>This is a system API. |
| BUNDLE_NAME_KEY<sup>9+</sup> | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.<br>This is a system API. |
## FormDimension
Enumerates the widget dimensions.
**System capability**: SystemCapability.Ability.Form
| Name | Value | Description |
| ----------- | ---- | ------------ |
| Dimension_1_2<sup>9+</sup> | 1 | 1 x 2. |
| Dimension_2_2<sup>9+</sup> | 2 | 2 x 2. |
| Dimension_2_4<sup>9+</sup> | 3 | 2 x 4. |
| Dimension_4_4<sup>9+</sup> | 4 | 4 x 4. |
| Dimension_2_1<sup>9+</sup> | 5 | 2 x 1. |
......@@ -28,16 +28,16 @@ SystemCapability.Ability.Form
| ----------- | ---- | ------------ |
| ERR_COMMON | 1 | Default error code. |
| ERR_PERMISSION_DENY | 2 | No permission to perform the operation. |
| ERR_GET_INFO_FAILED | 4 | Failed to query widget information. |
| ERR_GET_BUNDLE_FAILED | 5 | Failed to query the bundle information. |
| ERR_GET_LAYOUT_FAILED | 6 | Failed to query the layout information. |
| ERR_GET_INFO_FAILED | 4 | Failed to obtain the widget information. |
| ERR_GET_BUNDLE_FAILED | 5 | Failed to obtain the bundle information. |
| ERR_GET_LAYOUT_FAILED | 6 | Failed to obtain the layout information. |
| ERR_ADD_INVALID_PARAM | 7 | Invalid parameter. |
| ERR_CFG_NOT_MATCH_ID | 8 | The widget ID does not match. |
| ERR_CFG_NOT_MATCH_ID | 8 | The widget ID does not match any widget. |
| ERR_NOT_EXIST_ID | 9 | The widget ID does not exist. |
| ERR_BIND_PROVIDER_FAILED | 10 | Failed to bind to the widget provider. |
| ERR_MAX_SYSTEM_FORMS | 11 | The number of system widgets exceeds the upper limit. |
| ERR_MAX_INSTANCES_PER_FORM | 12 | The number of instances per widget exceeds the upper limit. |
| ERR_OPERATION_FORM_NOT_SELF | 13 | The application is not allowed to operate widgets applied by other applications. |
| ERR_OPERATION_FORM_NOT_SELF | 13 | The application is not allowed to operate widgets provided by other applications. |
| ERR_PROVIDER_DEL_FAIL | 14 | The widget provider failed to delete the widget. |
| ERR_MAX_FORMS_PER_CLIENT | 15 | The number of widgets applied for by the widget host exceeds the upper limit. |
| ERR_MAX_SYSTEM_TEMP_FORMS | 16 | The number of temporary widgets exceeds the upper limit. |
......@@ -48,3 +48,4 @@ SystemCapability.Ability.Form
| ERR_SYSTEM_RESPONSES_FAILED | 30 | The system service failed to respond. |
| ERR_FORM_DUPLICATE_ADDED | 31 | The widget has been added. |
| ERR_IN_RECOVERY | 36 | Failed to overwrite the widget data. |
| ERR_DISTRIBUTED_SCHEDULE_FAILED<sup>9+</sup> | 37 | The distributed scheduler failed.<br>This is a system API. |
# InputMethodExtensionAbility
The **InputMethodExtensionAbility** module provides the **InputMethodExtensionAbility** and **InputMethodExtensionContext** APIs that you can implement to develop input methods and manage their lifecycles.
> **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 APIs of this module can be used only in the stage model.
## Modules to Import
```
import InputMethodExtensionAbility from '@ohos.inputmethodextensionability';
```
## Attributes
**System capability**: SystemCapability.MiscServices.InputMethodFramework
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| context | [InputMethodExtensionContext](js-apis-inputmethod-extension-context.md) | Yes| No| Context of the **InputMethodExtension**, which is inherited from **ExtensionContext**.|
## InputMethodExtensionAbility.onCreate()
onCreate(want: Want): void;
Called when the **InputMethodExtension** ability is started to implement initialization.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | Yes| Information related to the **InputMethodExtension** ability, including the ability name and bundle name. |
**Example**
```js
class InputMethodExt extends InputMethodExtensionAbility {
onCreate(want) {
console.log('onCreate, want:' + want.abilityName);
}
}
```
## InputMethodExtensionAbility.onDestroy()
onDestroy(): void;
Called when this **InputMethodExtension** ability is destroyed to clear resources.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Example**
```js
class InputMethodExt extends InputMethodExtensionAbility {
onDestroy() {
console.log('onDestroy');
}
}
```
# InputMethodExtensionContext
The **InputMethodExtensionContext** module, inherited from **ExtensionContext**, provides context for **InputMethodExtension** abilities.
You can use the APIs of this module to start, terminate, connect, and disconnect abilities.
> **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 APIs of this module can be used only in the stage model.
## Modules to Import
```
import InputMethodExtensionContext from '@ohos.inputmethodextensioncontext';
```
## Usage
Before using the **InputMethodExtensionContext** module, you must define a child class that inherits from **InputMethodExtensionAbility**.
```js
import InputMethodExtensionAbility from '@ohos.inputmethodextensionability';
class MainAbility extends InputMethodExtensionAbility {
onCreate() {
let context = this.context;
}
}
```
## InputMethodExtensionContext.startAbility
startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void;
Starts an ability with the **want** parameter. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability, such as the ability name and bundle name.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
```js
let want = {
"bundleName": "com.example.myapp",
"abilityName": "MyAbility"};
this.context.startAbility(want, (err) => {
console.log('startAbility result:' + JSON.stringify(err));
});
```
## InputMethodExtensionContext.startAbility
startAbility(want: Want, options?: StartOptions): Promise\<void>;
Starts an ability with the mandatory **want** and optional **options** parameters. This API uses a promise to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability, such as the ability name and bundle name.|
| options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```js
let want = {
"bundleName": "com.example.myapp",
"abilityName": "MyAbility"
};
this.context.startAbility(want).then((data) => {
console.log('success:' + JSON.stringify(data));
}).catch((error) => {
console.log('failed:' + JSON.stringify(error));
});
```
## InputMethodExtensionContext.startAbility
startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&gt;): void
Starts an ability with the **want** and **options** parameters. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.|
| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
```js
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "MainAbility"
};
var options = {
windowMode: 0,
};
this.context.startAbility(want, options, (error) => {
console.log("error.code = " + error.code)
})
```
## InputMethodExtensionContext.terminateSelf
terminateSelf(callback: AsyncCallback&lt;void&gt;): void;
Terminates this ability. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example**
```js
this.context.terminateSelf((err) => {
console.log('terminateSelf result:' + JSON.stringify(err));
});
```
## InputMethodExtensionContext.terminateSelf
terminateSelf(): Promise&lt;void&gt;;
Terminates this ability. This API uses a promise to return the result.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```js
this.context.terminateSelf().then((data) => {
console.log('success:' + JSON.stringify(data));
}).catch((error) => {
console.log('failed:' + JSON.stringify(error));
});
```
# Media Query
The **mediaquery** module provides different styles for different media types.
> **NOTE**
>
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
......@@ -28,7 +30,7 @@ Sets the media query criteria and returns the corresponding listening handle.
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ---------------------------------------- |
| condition | string | Yes | Matching condition of a media event. For details, see "Syntax of Media Query Conditions" in [Media Query](../../ui/ui-ts-layout-mediaquery.md). |
| condition | string | Yes | Matching condition of a media event. For details, see [Syntax of Media Query Conditions](../../ui/ui-ts-layout-mediaquery.md#syntax-of-media-query-conditions).|
**Return value**
| Type | Description |
......@@ -36,9 +38,8 @@ Sets the media query criteria and returns the corresponding listening handle.
| MediaQueryListener | Listening handle to a media event, which is used to register or deregister the listening callback.|
**Example**
```js
listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events.
let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events.
```
......@@ -92,7 +93,7 @@ Deregisters a callback with the corresponding query condition by using the handl
```js
import mediaquery from '@ohos.mediaquery'
listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events.
let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events.
function onPortrait(mediaQueryResult) {
if (mediaQueryResult.matches) {
// do something here
......@@ -118,10 +119,9 @@ Deregisters a callback with the corresponding query condition by using the handl
### Example
```js
```ts
import mediaquery from '@ohos.mediaquery'
let portraitFunc = null
@Entry
@Component
......@@ -141,7 +141,7 @@ struct MediaQueryExample {
}
aboutToAppear() {
portraitFunc = this.onPortrait.bind(this) // Bind the current JS instance.
let portraitFunc = this.onPortrait.bind(this) // Bind the current JS instance.
this.listener.on('change', portraitFunc)
}
......
......@@ -491,7 +491,7 @@ plainArray.forEach((value, index) => {
[Symbol.iterator]\(): IterableIterator&lt;[number, T]&gt;
Obtains an iterator, each item of which is a JavaScript object.
Obtains an iterator object that contains key-value pairs, where the key is of the number type.
**System capability**: SystemCapability.Utils.Lang
......@@ -510,7 +510,7 @@ plainArray.add(2, "sffdfhf");
// Method 1:
for (let item of plainArray) {
console.log("index:" + item[0]);
console.log("key:" + item[0]);
console.log("value:" + item[1]);
}
......@@ -518,7 +518,7 @@ for (let item of plainArray) {
let iter = plainArray[Symbol.iterator]();
let temp = iter.next().value;
while(temp != undefined) {
console.log("index:" + temp[0]);
console.log("key:" + temp[0]);
console.log("value:" + temp[1]);
temp = iter.next().value;
}
......
......@@ -183,6 +183,7 @@ Obtains state information about the current page.
| Type | Description |
| --------------------------- | ------- |
| [RouterState](#routerstate) | Page routing state.|
**Example**
```js
......
......@@ -1894,7 +1894,7 @@ sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000
console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message);
return;
}
console.info('sensor_getGeomagneticField_promise x: ' + data.x + ',y: ' + data.y + ',z: ' +
console.info('sensor_getGeomagneticField_callback x: ' + data.x + ',y: ' + data.y + ',z: ' +
data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle +
',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity);
});
......@@ -2012,7 +2012,7 @@ Obtains the magnetic dip based on the inclination matrix. This API uses a callba
```js
sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) {
if (err) {
console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' +
console.error('SensorJsAPI--->Failed to register data, error code is:' + err.code + ', message: ' +
err.message);
return;
}
......@@ -2045,7 +2045,7 @@ Obtains the magnetic dip based on the inclination matrix. This API uses a promis
```js
const promise = sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1]);
promise.then((data) => {
console.info(' getGeomagneticDip_promise successed', data);
console.info('getGeomagneticDip_promise successed', data);
}).catch((err) => {
console.error("Operation failed");
})
......@@ -2593,9 +2593,9 @@ Describes the Hall effect sensor data. It extends from [Response](#response).
**System capability**: SystemCapability.Sensors.Sensor
| Name | Type | Readable | Writable | Description |
| ------ | ------ | ---- | ---- | --------------------------------- |
| status | number | Yes | Yes | Hall effect sensor status. This parameter specifies whether a magnetic field exists around a device. The value **0** means that a magnetic field exists around the device, and **1** means the opposite.|
| Name | Type| Readable| Writable| Description |
| ------ | -------- | ---- | ---- | ------------------------------------------------------------ |
| status | number | Yes | Yes | Hall effect sensor status. This parameter specifies whether a magnetic field exists around a device. The value **0** means that a magnetic field does not exist, and a value greater than **0** means the opposite.|
## MagneticFieldResponse
......
......@@ -2,7 +2,7 @@
The **ServiceExtensionContext** module, inherited from **ExtensionContext**, provides context for Service Extension abilities.
You can use the APIs of this module to start, terminate, connection, and disconnect abilities.
You can use the APIs of this module to start, terminate, connect, and disconnect abilities.
> **NOTE**
>
......
# Thermal Manager
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
This module provides thermal level-related callback and query APIs to obtain the information required for thermal control.
......@@ -42,7 +43,7 @@ Subscribes to thermal level changes.
| Name | Type | Mandatory | Description |
| -------- | --------------------------------- | ---- | ---------------------------------------- |
| callback | AsyncCallback&lt;ThermalLevel&gt; | Yes | Callback used to obtain the return value.<br>Return value: thermal level|
| callback | AsyncCallback&lt;ThermalLevel&gt; | Yes | Callback used to obtain the return value.<br>The return value contains only one parameter, that is, thermal level. If an alarm is generated, you can use `// @ts-ignore` to suppress the alarm.|
**Example**
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册