提交 41e0ca97 编写于 作者: S shawn_he

update doc

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
上级 d6686d92
# MDNS Management
## Overview
## Introduction
Multicast DNS (mDNS) provides functions such as adding, removing, discovering, and resolving local services on a LAN.
- Local service: a service provider on a LAN, for example, a printer or scanner.
......@@ -28,9 +28,13 @@ For the complete list of APIs and example code, see [mDNS Management](../referen
| ohos.net.mdns.DiscoveryService | startSearchingMDNS(): void | Searches for mDNS services on the LAN.|
| ohos.net.mdns.DiscoveryService | stopSearchingMDNS(): void | Stops searching for mDNS services on the LAN.|
| ohos.net.mdns.DiscoveryService | on(type: 'discoveryStart', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void | Enables listening for **discoveryStart** events.|
| ohos.net.mdns.DiscoveryService | off(type: 'discoveryStart', callback?: Callback<{ serviceInfo: LocalServiceInfo, errorCode?: MdnsError }>): void | Disables listening for **discoveryStart** events.|
| ohos.net.mdns.DiscoveryService | on(type: 'discoveryStop', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void | Enables listening for **discoveryStop** events.|
| ohos.net.mdns.DiscoveryService | off(type: 'discoveryStop', callback?: Callback<{ serviceInfo: LocalServiceInfo, errorCode?: MdnsError }>): void | Disables listening for **discoveryStop** events.|
| ohos.net.mdns.DiscoveryService | on(type: 'serviceFound', callback: Callback\<LocalServiceInfo>): void | Enables listening for **serviceFound** events.|
| ohos.net.mdns.DiscoveryService | off(type: 'serviceFound', callback?: Callback\<LocalServiceInfo>): void | Disables listening for **serviceFound** events.|
| ohos.net.mdns.DiscoveryService | on(type: 'serviceLost', callback: Callback\<LocalServiceInfo>): void | Enables listening for **serviceLost** events.|
| ohos.net.mdns.DiscoveryService | off(type: 'serviceLost', callback?: Callback\<LocalServiceInfo>): void | Disables listening for **serviceLost** events.|
## Managing Local Services
......@@ -94,10 +98,11 @@ mdns.removeLocalService(context, localServiceInfo, function (error, data) {
1. Connect the device to the Wi-Fi network.
2. Import the **mdns** namespace from **@ohos.net.mdns**.
3. Creates a **DiscoveryService** object, which is used to discover mDNS services of the specified type.
3. Create a **DiscoveryService** object, which is used to discover mDNS services of the specified type.
4. Subscribe to mDNS service discovery status changes.
5. Enable discovery of mDNS services on the LAN.
6. Stop searching for mDNS services on the LAN.
7. Unsubscribe from mDNS service discovery status changes.
```js
// Import the mdns namespace from @ohos.net.mdns.
......@@ -139,4 +144,18 @@ discoveryService.startSearchingMDNS();
// Stop searching for mDNS services on the LAN.
discoveryService.stopSearchingMDNS();
// Unsubscribe from mDNS service discovery status changes.
discoveryService.off('discoveryStart', (data) => {
console.log(JSON.stringify(data));
});
discoveryService.off('discoveryStop', (data) => {
console.log(JSON.stringify(data));
});
discoveryService.off('serviceFound', (data) => {
console.log(JSON.stringify(data));
});
discoveryService.off('serviceLost', (data) => {
console.log(JSON.stringify(data));
});
```
......@@ -304,6 +304,7 @@
- AI
- [@ohos.ai.mindSporeLite (Inference)](js-apis-mindSporeLite.md)
- [@ohos.ai.intelligentVoice (Intelligent Voice)](js-apis-intelligentVoice.md)
- Telephony Service
- [@ohos.contact (Contacts)](js-apis-contact.md)
......@@ -396,7 +397,7 @@
- [@ohos.charger (Charging Type)](js-apis-charger.md)
- [@ohos.cooperate (Screen Hopping)](js-apis-devicestatus-cooperate.md)
- [@ohos.deviceAttest (Device Attestation)](js-apis-deviceAttest.md)
- [@ohos.deviceStatus.dragInteraction (Drag)](js-apis-devicestatus-draginteraction.md)
- [@ohos.deviceStatus.dragInteraction (Drag Interaction)](js-apis-devicestatus-draginteraction.md)
- [@ohos.deviceInfo (Device Information)](js-apis-device-info.md)
- [@ohos.distributedDeviceManager (Device Management)](js-apis-distributedDeviceManager.md)
- [@ohos.distributedHardware.deviceManager (Device Management)](js-apis-device-manager.md)
......
# @ohos.deviceStatus.dragInteraction (Drag Interaction)
The **dragInteraction** module provides the APIs to enable and disable listening for dragging status changes.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> - The APIs provided by this module are system APIs.
## Modules to Import
```js
import dragInteraction from '@ohos.deviceStatus.dragInteraction'
```
## dragInteraction.on('drag')
on(type: 'drag', callback: Callback&lt;DragState&gt;): void;
Enables listening for dragging status changes.
**System capability**: SystemCapability.Msdp.DeviceStatus.Drag
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------- | ---- | ---------------------------- |
| type | string | Yes | Event type. This field has a fixed value of **drag**.|
| callback | Callback&lt;[DragState](#dragstate)&gt; | Yes | Callback used to return the dragging status.|
**Example**
```js
try {
dragInteraction.on('drag', (data) => {
console.log(`Drag interaction event: ${JSON.stringify(data)}`);
});
} catch (error) {
console.log(`Register failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## dragInteraction.off('drag')
off(type: 'drag', callback?: Callback&lt;DragState&gt;): void;
Disables listening for dragging status changes.
**System capability**: SystemCapability.Msdp.DeviceStatus.Drag
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------- | ---- | ---------------------------- |
| type | string | Yes | Event type. This field has a fixed value of **drag**.|
| callback | Callback&lt;[DragState](#dragstate)> | No | Callback to be unregistered. If this parameter is not specified, all callbacks registered by the current application will be unregistered.|
**Example**
```js
// Unregister a single callback.
function callback(event) {
console.log(`Drag interaction event: ${JSON.stringify(event)}`);
return false;
}
try {
dragInteraction.on('drag', callback);
dragInteraction.off("drag", callback);
} catch (error) {
console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
```js
// Unregister all callbacks.
function callback(event) {
console.log(`Drag interaction event: ${JSON.stringify(event)}`);
return false;
}
try {
dragInteraction.on('drag', callback);
dragInteraction.off("drag");
} catch (error) {
console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## DragState
Enumerates dragging states.
**System capability**: SystemCapability.Msdp.DeviceStatus.Drag
| Name | Value | Description |
| -------- | ----------------- | ----------------- |
| MSG_DRAG_STATE_START | 1 | Dragging starts.|
| MSG_DRAG_STATE_STOP | 2 | Dragging is ended. |
| MSG_DRAG_STATE_CANCEL | 3 | Dragging is canceled. |
# @ohos. deviceStatus.dragInteraction (Drag)
# @ohos.deviceStatus.dragInteraction (Drag Interaction)
The **dragInteraction** module provides the APIs to enable and disable listening for dragging status changes.
......@@ -14,7 +14,7 @@
import dragInteraction from '@ohos.deviceStatus.dragInteraction'
```
## dragInteraction.on
## dragInteraction.on('drag')
on(type: 'drag', callback: Callback&lt;DragState&gt;): void;
......@@ -41,7 +41,7 @@ try {
}
```
## dragInteraction.off
## dragInteraction.off('drag')
off(type: 'drag', callback?: Callback&lt;DragState&gt;): void;
......
......@@ -874,7 +874,7 @@ Specifies the type and value range of the optional parameters in the HTTP reques
| Name | Type | Mandatory| Description |
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method | [RequestMethod](#requestmethod) | No | Request method. The default value is **GET**. |
| extraData | string<sup>6+</sup> \| Object<sup>6+</sup> \| ArrayBuffer<sup>8+</sup> | No | Additional data for sending a request. This parameter is not used by default.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request and is encoded in UTF-8 format. If **'Content-Type'** is **'application/x-www-form-urlencoded'**, the data in the request body must be encoded in the format of **key1=value1&key2=value2&key3=value3** after URL transcoding. - If the HTTP request uses the GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter serves as a supplement to HTTP request parameters. Parameters of the string type need to be encoded before being passed to the HTTP request. Parameters of the object type do not need to be precoded and will be directly concatenated to the URL. Parameters of the ArrayBuffer type will not be concatenated to the URL.|
| extraData | string<sup>6+</sup> \| Object<sup>6+</sup> \| ArrayBuffer<sup>8+</sup> | No | Additional data for sending a request. This parameter is not used by default.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request and is encoded in UTF-8 format. If **'Content-Type'** is **'application/x-www-form-urlencoded'**, the data in the request body must be encoded in the format of **key1=value1&key2=value2&key3=value3** after URL transcoding and passed to the API as a string.<br>- If the HTTP request uses the GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter serves as a supplement to HTTP request parameters. Parameters of the string type need to be encoded before being passed to the HTTP request. Parameters of the object type do not need to be precoded and will be directly concatenated to the URL. Parameters of the ArrayBuffer type will not be concatenated to the URL.|
| expectDataType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | No | Type of the returned data. This parameter is not used by default. If this parameter is set, the system returns the specified type of data preferentially.|
| usingCache<sup>9+</sup> | boolean | No | Whether to use the cache. The default value is **true**. |
| priority<sup>9+</sup> | number | No | Priority. The value range is [1,1000]. The default value is **1**. |
......@@ -883,7 +883,7 @@ Specifies the type and value range of the optional parameters in the HTTP reques
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
| usingProtocol<sup>9+</sup> | [HttpProtocol](#httpprotocol9) | No | Protocol. The default value is automatically specified by the system. |
| usingProxy<sup>10+</sup> | boolean \| Object | No | Whether to use HTTP proxy. The default value is **false**, which means not to use HTTP proxy.<br>- If **usingProxy** is of the **Boolean** type and the value is **true**, network proxy is used by default.<br>- If **usingProxy** is of the **object** type, the specified network proxy is used.
| caPath<sup>10+</sup> | string | No | Path of the CA certificate. If this parameter is set, the system uses the CA certificate in the specified path. Otherwise, the system uses the preset CA certificate. |
| caPath<sup>10+</sup> | string | No | Path of CA certificates. If a path is set, the system uses the CA certificates in this path. If a path is not set, the system uses the preset CA certificates. The path is the sandbox mapping path, and preset CA certificates are stored in **/etc/ssl/certs/cacert.pem**. You are advised to store CA certificates in this path. Currently, only **.pem** certificates are supported. |
## RequestMethod<sup>6+</sup>
......
......@@ -11,7 +11,7 @@ The [Intl](js-apis-intl.md) module provides basic I18N capabilities through the
## Modules to Import
```js
```ts
import I18n from '@ohos.i18n';
```
......@@ -49,11 +49,14 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
try {
let displayCountry = I18n.System.getDisplayCountry("zh-CN", "en-GB"); // displayCountry = "China"
} catch(error) {
console.error(`call System.getDisplayCountry failed, error code: ${error.code}, message: ${error.message}.`);
let displayCountry: string = I18n.System.getDisplayCountry("zh-CN", "en-GB"); // displayCountry = "China"
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -88,11 +91,14 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
try {
let displayLanguage = I18n.System.getDisplayLanguage("zh", "en-GB"); // displayLanguage = Chinese
let displayLanguage: string = I18n.System.getDisplayLanguage("zh", "en-GB"); // displayLanguage = Chinese
} catch(error) {
console.error(`call System.getDisplayLanguage failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -119,11 +125,14 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
try {
let systemLanguages = I18n.System.getSystemLanguages(); // [ "en-Latn-US", "zh-Hans" ]
let systemLanguages: Array<string> = I18n.System.getSystemLanguages(); // [ "en-Latn-US", "zh-Hans" ]
} catch(error) {
console.error(`call System.getSystemLanguages failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -156,11 +165,14 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
try {
let systemCountries = I18n.System.getSystemCountries('zh'); // systemCountries = [ "ZW", "YT", "YE", ..., "ER", "CN", "DE" ], 240 countries or regions in total
let systemCountries: Array<string> = I18n.System.getSystemCountries('zh'); // systemCountries = [ "ZW", "YT", "YE", ..., "ER", "CN", "DE" ], 240 countries or regions in total
} catch(error) {
console.error(`call System.getSystemCountries failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -183,7 +195,7 @@ Checks whether the system language matches the specified region.
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the system language matches the specified region; returns **false** otherwise.|
| boolean | The value **true** indicates that the system language matches the specified region, and the value **false** indicates the opposite.|
**Error codes**
......@@ -194,11 +206,14 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
try {
let res = I18n.System.isSuggested('zh', 'CN'); // res = true
let res: boolean = I18n.System.isSuggested('zh', 'CN'); // res = true
} catch(error) {
console.error(`call System.isSuggested failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -225,11 +240,14 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
try {
let systemLanguage = I18n.System.getSystemLanguage(); // systemLanguage indicates the current system language.
let systemLanguage: string = I18n.System.getSystemLanguage(); // systemLanguage indicates the current system language.
} catch(error) {
console.error(`call System.getSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -260,11 +278,14 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
try {
I18n.System.setSystemLanguage('zh'); // Set the current system language to zh.
} catch(error) {
console.error(`call System.setSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -291,11 +312,14 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
try {
let systemRegion = I18n.System.getSystemRegion(); // Obtain the current system region.
let systemRegion: string = I18n.System.getSystemRegion(); // Obtain the current system region.
} catch(error) {
console.error(`call System.getSystemRegion failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -326,11 +350,14 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
try {
I18n.System.setSystemRegion('CN'); // Set the current system region to CN.
} catch(error) {
console.error(`call System.setSystemRegion failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -357,11 +384,14 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
try {
let systemLocale = I18n.System.getSystemLocale(); // Obtain the current system locale.
let systemLocale: string = I18n.System.getSystemLocale(); // Obtain the current system locale.
} catch(error) {
console.error(`call System.getSystemLocale failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -392,11 +422,14 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
try {
I18n.System.setSystemLocale('zh-CN'); // Set the current system locale to zh-CN.
} catch(error) {
console.error(`call System.setSystemLocale failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -412,7 +445,7 @@ Checks whether the 24-hour clock is used.
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the 24-hour clock is used; returns **false** otherwise.|
| boolean | The value **true** indicates that the 24-hour clock is used, and the value **false** indicates the opposite.|
**Error codes**
......@@ -423,11 +456,14 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
try {
let is24HourClock = I18n.System.is24HourClock(); // Check whether the 24-hour clock is enabled.
let is24HourClock: boolean = I18n.System.is24HourClock(); // Check whether the 24-hour clock is enabled.
} catch(error) {
console.error(`call System.is24HourClock failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -458,12 +494,15 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
// Set the system time to the 24-hour clock.
try {
I18n.System.set24HourClock(true);
} catch(error) {
console.error(`call System.set24HourClock failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -495,14 +534,17 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
// Add zh-CN to the preferred language list.
let language = 'zh-CN';
let index = 0;
try {
I18n.System.addPreferredLanguage(language, index); // Add zh-CN to the first place in the preferred language list.
} catch(error) {
console.error(`call System.addPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -533,13 +575,16 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
// Delete the first preferred language from the preferred language list.
let index = 0;
let index: number = 0;
try {
I18n.System.removePreferredLanguage(index);
} catch(error) {
console.error(`call System.removePreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -566,11 +611,14 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
try {
let preferredLanguageList = I18n.System.getPreferredLanguageList(); // Obtain the current preferred language list.
let preferredLanguageList: Array<string> = I18n.System.getPreferredLanguageList(); // Obtain the current preferred language list.
} catch(error) {
console.error(`call System.getPreferredLanguageList failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -597,11 +645,14 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
try {
let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // Obtain the first language in the preferred language list.
let firstPreferredLanguage: string = I18n.System.getFirstPreferredLanguage(); // Obtain the first language in the preferred language list.
} catch(error) {
console.error(`call System.getFirstPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -628,11 +679,14 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
try {
let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // Obtain the preferred language of an application.
let appPreferredLanguage: string = I18n.System.getAppPreferredLanguage(); // Obtain the preferred language of an application.
} catch(error) {
console.error(`call System.getAppPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -664,10 +718,13 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
I18n.System.setUsingLocalDigit(true); // Enable the local digit switch.
} catch(error) {
console.error(`call System.setUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -683,7 +740,7 @@ Checks whether use of local digits is enabled.
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the local digit switch is turned on; returns **false** otherwise.|
| boolean | The value **true** indicates that the local digit switch is turned on, and the value **false** indicates the opposite.|
**Error codes**
......@@ -695,10 +752,13 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
let status = I18n.System.getUsingLocalDigit(); // Check whether the local digit switch is enabled.
let status: boolean = I18n.System.getUsingLocalDigit(); // Check whether the local digit switch is enabled.
} catch(error) {
console.error(`call System.getUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -721,10 +781,10 @@ Checks whether a locale uses an RTL language.
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the localized script is displayed from right to left; returns **false** otherwise.|
| boolean | The value **true** indicates that the localized script is displayed from right to left, and the value **false** indicates the opposite.|
**Example**
```js
```ts
i18n.isRTL("zh-CN");// Since Chinese is not written from right to left, false is returned.
i18n.isRTL("ar-EG");// Since Arabic is written from right to left, true is returned.
```
......@@ -752,7 +812,7 @@ Obtains a **Calendar** object.
| [Calendar](#calendar8) | **Calendar** object.|
**Example**
```js
```ts
I18n.getCalendar("zh-Hans", "chinese"); // Obtain the Calendar object for the Chinese lunar calendar.
```
......@@ -775,9 +835,9 @@ Sets the date for this **Calendar** object.
| date | Date | Yes | Date to be set for the **Calendar** object.|
**Example**
```js
let calendar = I18n.getCalendar("en-US", "gregory");
let date = new Date(2021, 10, 7, 8, 0, 0, 0);
```ts
let calendar: I18n.Calendar = I18n.getCalendar("en-US", "gregory");
let date: Date = new Date(2021, 10, 7, 8, 0, 0, 0);
calendar.setTime(date);
```
......@@ -797,8 +857,8 @@ Sets the date and time for this **Calendar** object. The value is represented by
| time | number | Yes | Number of milliseconds that have elapsed since the Unix epoch.|
**Example**
```js
let calendar = I18n.getCalendar("en-US", "gregory");
```ts
let calendar: I18n.Calendar = I18n.getCalendar("en-US", "gregory");
calendar.setTime(10540800000);
```
......@@ -823,8 +883,8 @@ Sets the year, month, day, hour, minute, and second for this **Calendar** object
| second | number | No | Second to set. The default value is the system second.|
**Example**
```js
let calendar = I18n.getCalendar("zh-Hans");
```ts
let calendar: I18n.Calendar = I18n.getCalendar("zh-Hans");
calendar.set(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00
```
......@@ -844,8 +904,8 @@ Sets the time zone of this **Calendar** object.
| timezone | string | Yes | Time zone, for example, **Asia/Shanghai**.|
**Example**
```js
let calendar = I18n.getCalendar("zh-Hans");
```ts
let calendar: I18n.Calendar = I18n.getCalendar("zh-Hans");
calendar.setTimeZone("Asia/Shanghai");
```
......@@ -865,10 +925,10 @@ Obtains the time zone of this **Calendar** object.
| string | Time zone of the **Calendar** object.|
**Example**
```js
let calendar = I18n.getCalendar("zh-Hans");
```ts
let calendar: I18n.Calendar = I18n.getCalendar("zh-Hans");
calendar.setTimeZone("Asia/Shanghai");
let timezone = calendar.getTimeZone(); // timezone = "Asia/Shanghai"
let timezone: string = calendar.getTimeZone(); // timezone = "Asia/Shanghai"
```
......@@ -887,9 +947,9 @@ Obtains the start day of a week for this **Calendar** object.
| number | Start day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.|
**Example**
```js
let calendar = I18n.getCalendar("en-US", "gregory");
let firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 1
```ts
let calendar: I18n.Calendar = I18n.getCalendar("en-US", "gregory");
let firstDayOfWeek: number = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 1
```
......@@ -908,10 +968,10 @@ Sets the start day of a week for this **Calendar** object.
| value | number | Yes | Start day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.|
**Example**
```js
let calendar = I18n.getCalendar("zh-Hans");
```ts
let calendar: I18n.Calendar = I18n.getCalendar("zh-Hans");
calendar.setFirstDayOfWeek(3);
let firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 3
let firstDayOfWeek: number = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 3
```
......@@ -930,9 +990,9 @@ Obtains the minimum number of days in the first week of a year.
| number | Minimum number of days in the first week of a year.|
**Example**
```js
let calendar = I18n.getCalendar("zh-Hans");
let minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 1
```ts
let calendar: I18n.Calendar = I18n.getCalendar("zh-Hans");
let minimalDaysInFirstWeek: number = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 1
```
......@@ -951,10 +1011,10 @@ Sets the minimum number of days in the first week of a year.
| value | number | Yes | Minimum number of days in the first week of a year.|
**Example**
```js
let calendar = I18n.getCalendar("zh-Hans");
```ts
let calendar: I18n.Calendar = I18n.getCalendar("zh-Hans");
calendar.setMinimalDaysInFirstWeek(3);
let minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 3
let minimalDaysInFirstWeek: number = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 3
```
......@@ -979,10 +1039,10 @@ Obtains the value of the specified field in the **Calendar** object.
| number | Value of the specified field. For example, if the year in the internal date of this **Calendar** object is **1990**, the **get("year")** function will return **1990**.|
**Example**
```js
let calendar = I18n.getCalendar("zh-Hans");
```ts
let calendar: I18n.Calendar = I18n.getCalendar("zh-Hans");
calendar.set(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00
let hourOfDay = calendar.get("hour_of_day"); // hourOfDay = 8
let hourOfDay: number = calendar.get("hour_of_day"); // hourOfDay = 8
```
......@@ -1007,9 +1067,9 @@ Obtains the displayed name of the **Calendar** object for the specified locale.
| string | Displayed name of the **Calendar** object for the specified locale.|
**Example**
```js
let calendar = I18n.getCalendar("en-US", "buddhist");
let calendarName = calendar.getDisplayName("zh"); // calendarName = "Buddhist Calendar"
```ts
let calendar: I18n.Calendar = I18n.getCalendar("en-US", "buddhist");
let calendarName: string = calendar.getDisplayName("zh"); // calendarName = "Buddhist Calendar"
```
......@@ -1031,14 +1091,14 @@ Checks whether a given date is a weekend in the calendar.
| Type | Description |
| ------- | ----------------------------------- |
| boolean | Returns **true** if the specified date is a weekend; returns **false** otherwise.|
| boolean | The value **true** indicates that the specified date is a weekend, and the value **false** indicates the opposite.|
**Example**
```js
let calendar = I18n.getCalendar("zh-Hans");
```ts
let calendar: I18n.Calendar = I18n.getCalendar("zh-Hans");
calendar.set(2021, 11, 11, 8, 0, 0); // set time to 2021.11.11 08:00:00
calendar.isWeekend(); // false
let date = new Date(2011, 11, 6, 9, 0, 0);
let date: Date = new Date(2011, 11, 6, 9, 0, 0);
calendar.isWeekend(date); // true
```
......@@ -1062,8 +1122,9 @@ Creates a **PhoneNumberFormat** object.
| options | [PhoneNumberFormatOptions](#phonenumberformatoptions8) | No | Options of the **PhoneNumberFormat** object. The default value is **NATIONAL**. |
**Example**
```js
let phoneNumberFormat= new I18n.PhoneNumberFormat("CN", {"type": "E164"});
```ts
let option: I18n.PhoneNumberFormatOptions = {type: "E164"};
let phoneNumberFormat: I18n.PhoneNumberFormat = new I18n.PhoneNumberFormat("CN", option);
```
......@@ -1085,12 +1146,12 @@ Checks whether the format of the specified phone number is valid.
| Type | Description |
| ------- | ------------------------------------- |
| boolean | Returns **true** if the phone number format is valid; returns **false** otherwise.|
| boolean | The value **true** indicates that the phone number format is valid, and the value **false** indicates the opposite.|
**Example**
```js
let phonenumberfmt = new I18n.PhoneNumberFormat("CN");
let isValidNumber = phonenumberfmt.isValidNumber("15812312312"); // isValidNumber = true
```ts
let phonenumberfmt: I18n.PhoneNumberFormat = new I18n.PhoneNumberFormat("CN");
let isValidNumber: boolean = phonenumberfmt.isValidNumber("15812312312"); // isValidNumber = true
```
......@@ -1115,9 +1176,9 @@ Formats a phone number.
| string | Formatted phone number.|
**Example**
```js
let phonenumberfmt = new I18n.PhoneNumberFormat("CN");
let formattedPhoneNumber = phonenumberfmt.format("15812312312"); // formattedPhoneNumber = "158 1231 2312"
```ts
let phonenumberfmt: I18n.PhoneNumberFormat = new I18n.PhoneNumberFormat("CN");
let formattedPhoneNumber: string = phonenumberfmt.format("15812312312"); // formattedPhoneNumber = "158 1231 2312"
```
......@@ -1143,9 +1204,9 @@ Obtains the home location of a phone number.
| string | Home location of the phone number.|
**Example**
```js
let phonenumberfmt = new I18n.PhoneNumberFormat("CN");
let locationName = phonenumberfmt.getLocationName("15812312345", "zh-CN"); // locationName = "Zhanjiang, Guangdong Province"
```ts
let phonenumberfmt: I18n.PhoneNumberFormat = new I18n.PhoneNumberFormat("CN");
let locationName: string = phonenumberfmt.getLocationName("15812312345", "zh-CN"); // locationName = "Zhanjiang, Guangdong Province"
```
......@@ -1193,8 +1254,8 @@ Creates an **IndexUtil** object.
| [IndexUtil](#indexutil8) | **IndexUtil** object mapping to the **locale** object.|
**Example**
```js
let indexUtil = I18n.getInstance("zh-CN");
```ts
let indexUtil: I18n.IndexUtil = I18n.getInstance("zh-CN");
```
......@@ -1216,11 +1277,11 @@ Obtains the index list for this **locale** object.
| Array&lt;string&gt; | Index list for the **locale** object.|
**Example**
```js
let indexUtil = I18n.getInstance("zh-CN");
```ts
let indexUtil: I18n.IndexUtil = I18n.getInstance("zh-CN");
// indexList = [ "...", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
// "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "..." ]
let indexList = indexUtil.getIndexList();
let indexList: Array<string> = indexUtil.getIndexList();
```
......@@ -1239,8 +1300,8 @@ Adds a **locale** object to the current index list.
| locale | string | Yes | A string containing locale information, including the language, optional script, and region.|
**Example**
```js
let indexUtil = I18n.getInstance("zh-CN");
```ts
let indexUtil: I18n.IndexUtil = I18n.getInstance("zh-CN");
indexUtil.addLocale("en-US");
```
......@@ -1266,9 +1327,9 @@ Obtains the index of a **text** object.
| string | Index of the **text** object.|
**Example**
```js
let indexUtil = I18n.getInstance("zh-CN");
let index = indexUtil.getIndex("hi"); // index = "H"
```ts
let indexUtil: I18n.IndexUtil = I18n.getInstance("zh-CN");
let index: string = indexUtil.getIndex("hi"); // index = "H"
```
......@@ -1293,8 +1354,8 @@ Obtains a [BreakIterator](#breakiterator8) object for text segmentation.
| [BreakIterator](#breakiterator8) | [BreakIterator](#breakiterator8) object used for text segmentation.|
**Example**
```js
let iterator = I18n.getLineInstance("en");
```ts
let iterator: I18n.BreakIterator = I18n.getLineInstance("en");
```
......@@ -1316,8 +1377,8 @@ Sets the text to be processed by the **BreakIterator** object.
| text | string | Yes | Text to be processed by the **BreakIterator** object.|
**Example**
```js
let iterator = I18n.getLineInstance("en");
```ts
let iterator: I18n.BreakIterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit ."); // Set a short sentence as the text to be processed by the BreakIterator object.
```
......@@ -1337,10 +1398,10 @@ Obtains the text being processed by the **BreakIterator** object.
| string | Text being processed by the **BreakIterator** object.|
**Example**
```js
let iterator = I18n.getLineInstance("en");
```ts
let iterator: I18n.BreakIterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit.");
let breakText = iterator.getLineBreakText(); // breakText = "Apple is my favorite fruit."
let breakText: string = iterator.getLineBreakText(); // breakText = "Apple is my favorite fruit."
```
......@@ -1359,10 +1420,10 @@ Obtains the position of the **BreakIterator** object in the text being processed
| number | Position of the **BreakIterator** object in the text being processed.|
**Example**
```js
let iterator = I18n.getLineInstance("en");
```ts
let iterator: I18n.BreakIterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit.");
let currentPos = iterator.current(); // currentPos = 0
let currentPos: number = iterator.current(); // currentPos = 0
```
......@@ -1381,10 +1442,10 @@ Puts the **BreakIterator** object to the first break point, which is always at t
| number | Offset to the first break point of the processed text.|
**Example**
```js
let iterator = I18n.getLineInstance("en");
```ts
let iterator: I18n.BreakIterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit.");
let firstPos = iterator.first(); // firstPos = 0
let firstPos: number = iterator.first(); // firstPos = 0
```
......@@ -1403,10 +1464,10 @@ Puts the **BreakIterator** object to the last break point, which is always the n
| number | Offset to the last break point of the processed text.|
**Example**
```js
let iterator = I18n.getLineInstance("en");
```ts
let iterator: I18n.BreakIterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit.");
let lastPos = iterator.last(); // lastPos = 27
let lastPos: number = iterator.last(); // lastPos = 27
```
......@@ -1431,10 +1492,10 @@ Moves the **BreakIterator** object backward by the corresponding number of break
| number | Position of the **BreakIterator** object in the text after it is moved by the specified number of break points. The value **-1** is returned if the position of the [BreakIterator](#breakiterator8) object is outside of the processed text after it is moved by the specified number of break points.|
**Example**
```js
let iterator = I18n.getLineInstance("en");
```ts
let iterator: I18n.BreakIterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit.");
let pos = iterator.first(); // pos = 0
let pos: number = iterator.first(); // pos = 0
pos = iterator.next(); // pos = 6
pos = iterator.next(10); // pos = -1
```
......@@ -1455,10 +1516,10 @@ Moves the **BreakIterator** object forward by one break point.
| number | Position of the **BreakIterator** object in the text after it is moved to the previous break point. The value **-1** is returned if the position of the [BreakIterator](#breakiterator8) object is outside of the processed text after it is moved by the specified number of break points.|
**Example**
```js
let iterator = I18n.getLineInstance("en");
```ts
let iterator: I18n.BreakIterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit.");
let pos = iterator.first(); // pos = 0
let pos: number = iterator.first(); // pos = 0
pos = iterator.next(3); // pos = 12
pos = iterator.previous(); // pos = 9
```
......@@ -1485,10 +1546,10 @@ Moves the **BreakIterator** to the break point following the specified position.
| number | The value **-1** is returned if the break point to which the **BreakIterator** object is moved is outside of the processed text.|
**Example**
```js
let iterator = I18n.getLineInstance("en");
```ts
let iterator: I18n.BreakIterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit.");
let pos = iterator.following(0); // pos = 6
let pos: number = iterator.following(0); // pos = 6
pos = iterator.following(100); // pos = -1
pos = iterator.current(); // pos = 27
```
......@@ -1512,13 +1573,13 @@ Checks whether the specified position of the text is a break point.
| Type | Description |
| ------- | ------------------------------- |
| boolean | Returns **true** if the position specified by the offset is a break point; returns **false** otherwise.|
| boolean | The value **true** indicates that the position specified by the offset is a break point, and the value **false** indicates the opposite.|
**Example**
```js
let iterator = I18n.getLineInstance("en");
```ts
let iterator: I18n.BreakIterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit.");
let isBoundary = iterator.isBoundary(0); // isBoundary = true;
let isBoundary: boolean = iterator.isBoundary(0); // isBoundary = true;
isBoundary = iterator.isBoundary(5); // isBoundary = false;
```
......@@ -1544,8 +1605,8 @@ Obtains the **TimeZone** object corresponding to the specified time zone ID.
| TimeZone | **TimeZone** object corresponding to the time zone ID.|
**Example**
```js
let timezone = I18n.getTimeZone();
```ts
let timezone: I18n.TimeZone = I18n.getTimeZone();
```
......@@ -1567,9 +1628,9 @@ Obtains the ID of the specified **TimeZone** object.
| string | Time zone ID corresponding to the **TimeZone** object.|
**Example**
```js
let timezone = I18n.getTimeZone();
let timezoneID = timezone.getID(); // timezoneID = "Asia/Shanghai"
```ts
let timezone: I18n.TimeZone = I18n.getTimeZone();
let timezoneID: string = timezone.getID(); // timezoneID = "Asia/Shanghai"
```
......@@ -1595,9 +1656,9 @@ Obtains the localized representation of a **TimeZone** object.
| string | Representation of the **TimeZone** object in the specified locale.|
**Example**
```js
let timezone = I18n.getTimeZone();
let timezoneName = timezone.getDisplayName("zh-CN", false); // timezoneName = "China Standard Time"
```ts
let timezone: I18n.TimeZone = I18n.getTimeZone();
let timezoneName: string = timezone.getDisplayName("zh-CN", false); // timezoneName = "China Standard Time"
```
......@@ -1616,9 +1677,9 @@ Obtains the offset between the time zone represented by a **TimeZone** object an
| number | Offset between the time zone represented by the **TimeZone** object and the UTC time zone.|
**Example**
```js
let timezone = I18n.getTimeZone();
let offset = timezone.getRawOffset(); // offset = 28800000
```ts
let timezone: I18n.TimeZone = I18n.getTimeZone();
let offset: number = timezone.getRawOffset(); // offset = 28800000
```
......@@ -1637,9 +1698,9 @@ Obtains the offset between the time zone represented by a **TimeZone** object an
| number | Offset between the time zone represented by the **TimeZone** object and the UTC time zone at a certain time point. The default value is the system time zone.|
**Example**
```js
let timezone = I18n.getTimeZone();
let offset = timezone.getOffset(1234567890); // offset = 28800000
```ts
let timezone: I18n.TimeZone = I18n.getTimeZone();
let offset: number = timezone.getOffset(1234567890); // offset = 28800000
```
......@@ -1660,7 +1721,7 @@ Obtains the list of time zone IDs supported by the system.
**Example**
```ts
// ids = ["America/Adak", "America/Anchorage", "America/Bogota", "America/Denver", "America/Los_Angeles", "America/Montevideo", "America/Santiago", "America/Sao_Paulo", "Asia/Ashgabat", "Asia/Hovd", "Asia/Jerusalem", "Asia/Magadan", "Asia/Omsk", "Asia/Shanghai", "Asia/Tokyo", "Asia/Yerevan", "Atlantic/Cape_Verde", "Australia/Lord_Howe", "Europe/Dublin", "Europe/London", "Europe/Moscow", "Pacific/Auckland", "Pacific/Easter", "Pacific/Pago-Pago"], 24 time zones supported in total
let ids = I18n.TimeZone.getAvailableIDs();
let ids: Array<string> = I18n.TimeZone.getAvailableIDs();
```
......@@ -1681,7 +1742,7 @@ Obtains the list of time zone city IDs supported by the system.
**Example**
```ts
// cityIDs = ["Auckland", "Magadan", "Lord Howe Island", "Tokyo", "Shanghai", "Hovd", "Omsk", "Ashgabat", "Yerevan", "Moscow", "Tel Aviv", "Dublin", "London", "Praia", "Montevideo", "Brasília", "Santiago", "Bogotá", "Easter Island", "Salt Lake City", "Los Angeles", "Anchorage", "Adak", "Pago Pago"], 24 time zone cities supported in total
let cityIDs = I18n.TimeZone.getAvailableZoneCityIDs();
let cityIDs: Array<string> = I18n.TimeZone.getAvailableZoneCityIDs();
```
......@@ -1708,7 +1769,7 @@ Obtains the localized representation of a time zone city in the specified locale
**Example**
```ts
let displayName = I18n.TimeZone.getCityDisplayName("Shanghai", "zh-CN"); // displayName = "Shanghai (China)"
let displayName: string = I18n.TimeZone.getCityDisplayName("Shanghai", "zh-CN"); // displayName = "Shanghai (China)"
```
......@@ -1734,7 +1795,7 @@ Obtains the **TimeZone** object corresponding to the specified time zone city ID
**Example**
```ts
let timezone = I18n.TimeZone.getTimezoneFromCity("Shanghai");
let timezone: I18n.TimeZone = I18n.TimeZone.getTimezoneFromCity("Shanghai");
```
### getTimezonesByLocation<sup>10+</sup>
......@@ -1759,10 +1820,10 @@ Creates an array of **TimeZone** objects corresponding to the specified longitud
| Array&lt;[TimeZone](#timezone)&gt; | Array of **TimeZone** objects.|
**Example**
```js
let timezoneArray = I18n.TimeZone.getTimezonesByLocation(-118.1, 34.0);
for (var i = 0; i < timezoneArray.length; i++) {
let tzId = timezoneArray[i].getID();
```ts
let timezoneArray: Array<I18n.TimeZone> = I18n.TimeZone.getTimezonesByLocation(-118.1, 34.0);
for (let i = 0; i < timezoneArray.length; i++) {
let tzId: string = timezoneArray[i].getID();
}
```
......@@ -1788,7 +1849,7 @@ Obtains a list of IDs supported by the **Transliterator** object.
```ts
// A total of 671 IDs are supported. One ID is comprised of two parts separated by a hyphen (-) in the format of source-destination. For example, in **ids = ["Han-Latin","Latin-ASCII", "Amharic-Latin/BGN","Accents-Any", ...]**, **Han-Latin** indicates conversion from Chinese to Latin, and **Amharic-Latin** indicates conversion from Amharic to Latin.
// For more information, see ISO-15924.
let ids = I18n.Transliterator.getAvailableIDs();
let ids: string[] = I18n.Transliterator.getAvailableIDs();
```
......@@ -1814,7 +1875,7 @@ Creates a **Transliterator** object.
**Example**
```ts
let transliterator = I18n.Transliterator.getInstance("Any-Latn");
let transliterator: I18n.Transliterator = I18n.Transliterator.getInstance("Any-Latn");
```
......@@ -1840,8 +1901,8 @@ Converts the input string from the source format to the target format.
**Example**
```ts
let transliterator = I18n.Transliterator.getInstance("Any-Latn");
let res = transliterator.transform("China"); // res = "zhōng guó"
let transliterator: I18n.Transliterator = I18n.Transliterator.getInstance("Any-Latn");
let res: string = transliterator.transform("China"); // res = "zhōng guó"
```
......@@ -1866,11 +1927,11 @@ Checks whether the input character string is composed of digits.
| Type | Description |
| ------- | ------------------------------------ |
| boolean | Returns **true** if the input character is a digit; returns **false** otherwise.|
| boolean | The value **true** indicates that the input character is a digit, and the value **false** indicates the opposite.|
**Example**
```js
let isdigit = I18n.Unicode.isDigit("1"); // isdigit = true
```ts
let isdigit: boolean = I18n.Unicode.isDigit("1"); // isdigit = true
```
......@@ -1892,11 +1953,11 @@ Checks whether the input character is a space.
| Type | Description |
| ------- | -------------------------------------- |
| boolean | Returns **true** if the input character is a space; returns **false** otherwise.|
| boolean | The value **true** indicates that the input character is a space, and the value **false** indicates the opposite.|
**Example**
```js
let isspacechar = I18n.Unicode.isSpaceChar("a"); // isspacechar = false
```ts
let isspacechar: boolean = I18n.Unicode.isSpaceChar("a"); // isspacechar = false
```
......@@ -1918,11 +1979,11 @@ Checks whether the input character is a white space.
| Type | Description |
| ------- | -------------------------------------- |
| boolean | Returns **true** if the input character is a white space; returns **false** otherwise.|
| boolean | The value **true** indicates that the input character is a white space, and the value **false** indicates the opposite.|
**Example**
```js
let iswhitespace = I18n.Unicode.isWhitespace("a"); // iswhitespace = false
```ts
let iswhitespace: boolean = I18n.Unicode.isWhitespace("a"); // iswhitespace = false
```
......@@ -1944,11 +2005,11 @@ Checks whether the input character is of the right to left (RTL) language.
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the input character is of the RTL language; returns **false** otherwise.|
| boolean | The value **true** indicates that the input character is of the RTL language, and the value **false** indicates the opposite.|
**Example**
```js
let isrtl = I18n.Unicode.isRTL("a"); // isrtl = false
```ts
let isrtl: boolean = I18n.Unicode.isRTL("a"); // isrtl = false
```
......@@ -1970,11 +2031,11 @@ Checks whether the input character is an ideographic character.
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the input character is an ideographic character; returns **false** otherwise.|
| boolean | The value **true** indicates that the input character is an ideographic character, and the value **false** indicates the opposite.|
**Example**
```js
let isideograph = I18n.Unicode.isIdeograph("a"); // isideograph = false
```ts
let isideograph: boolean = I18n.Unicode.isIdeograph("a"); // isideograph = false
```
......@@ -1996,11 +2057,11 @@ Checks whether the input character is a letter.
| Type | Description |
| ------- | ------------------------------------ |
| boolean | Returns **true** if the input character is a letter; returns **false** otherwise.|
| boolean | The value **true** indicates that the input character is a letter, and the value **false** indicates the opposite.|
**Example**
```js
let isletter = I18n.Unicode.isLetter("a"); // isletter = true
```ts
let isletter: boolean = I18n.Unicode.isLetter("a"); // isletter = true
```
......@@ -2022,11 +2083,11 @@ Checks whether the input character is a lowercase letter.
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the input character is a lowercase letter; returns **false** otherwise.|
| boolean | The value **true** indicates that the input character is a lowercase letter, and the value **false** indicates the opposite.|
**Example**
```js
let islowercase = I18n.Unicode.isLowerCase("a"); // islowercase = true
```ts
let islowercase: boolean = I18n.Unicode.isLowerCase("a"); // islowercase = true
```
......@@ -2048,11 +2109,11 @@ Checks whether the input character is an uppercase letter.
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the input character is an uppercase letter; returns **false** otherwise.|
| boolean | The value **true** indicates that the input character is an uppercase letter, and the value **false** indicates the opposite.|
**Example**
```js
let isuppercase = I18n.Unicode.isUpperCase("a"); // isuppercase = false
```ts
let isuppercase: boolean = I18n.Unicode.isUpperCase("a"); // isuppercase = false
```
......@@ -2113,8 +2174,8 @@ The following table lists only the general category values. For more details, se
| U_OTHER_SYMBOL | U_OTHER_SYMBOL | Other symbols.|
**Example**
```js
let type = I18n.Unicode.getType("a"); // type = "U_LOWERCASE_LETTER"
```ts
let type: string = I18n.Unicode.getType("a"); // type = "U_LOWERCASE_LETTER"
```
## I18NUtil<sup>9+</sup>
......@@ -2145,8 +2206,10 @@ Converts one measurement unit into another and formats the unit based on the spe
| string | Character string obtained after formatting based on the measurement unit specified by **toUnit**.|
**Example**
```js
let res = I18n.I18NUtil.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long"); // res = 236.588 liters
```ts
let fromUnit: I18n.UnitInfo = {unit: "cup", measureSystem: "US"};
let toUnit: I18n.UnitInfo = {unit: "liter", measureSystem: "SI"};
let res: string = I18n.I18NUtil.unitConvert(fromUnit, toUnit, 1000, "en-US", "long"); // res = 236.588 liters
```
......@@ -2171,8 +2234,8 @@ Obtains the sequence of the year, month, and day in the specified locale.
| string | Sequence of the year, month, and day in the locale.|
**Example**
```js
let order = I18n.I18NUtil.getDateOrder("zh-CN"); // order = "y-L-d"
```ts
let order: string = I18n.I18NUtil.getDateOrder("zh-CN"); // order = "y-L-d"
```
......@@ -2199,8 +2262,8 @@ Obtains a **Normalizer** object for text normalization.
| [Normalizer](#normalizer10) | **Normalizer** object for text normalization.|
**Example**
```js
let normalizer = I18n.Normalizer.getInstance(I18n.NormalizerMode.NFC);
```ts
let normalizer: I18n.Normalizer = I18n.Normalizer.getInstance(I18n.NormalizerMode.NFC);
```
......@@ -2225,9 +2288,9 @@ Normalizes text strings.
| string | Normalized text strings.|
**Example**
```js
let normalizer = I18n.Normalizer.getInstance(I18n.NormalizerMode.NFC);
let normalizedText = normalizer.normalize('\u1E9B\u0323'); // normalizedText = \u1E9B\u0323
```ts
let normalizer: I18n.Normalizer = I18n.Normalizer.getInstance(I18n.NormalizerMode.NFC);
let normalizedText: string = normalizer.normalize('\u1E9B\u0323'); // normalizedText = \u1E9B\u0323
```
......@@ -2259,8 +2322,8 @@ Creates a **SystemLocaleManager** object.
**System capability**: SystemCapability.Global.I18n
**Example**
```js
let systemLocaleManager= new I18n.SystemLocaleManager();
```ts
let systemLocaleManager: I18n.SystemLocaleManager = new I18n.SystemLocaleManager();
```
......@@ -2296,16 +2359,19 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
// Assume that the system language is zh-Hans, the system region is CN, and the system locale is zh-Hans-CN.
let systemLocaleManager = new I18n.SystemLocaleManager();
var languages = ["zh-Hans", "en-US", "pt", "ar"];
var sortOptions = {locale: "zh-Hans-CN", isUseLocalName: true, isSuggestedFirst: true};
let systemLocaleManager: I18n.SystemLocaleManager = new I18n.SystemLocaleManager();
let languages: string[] = ["zh-Hans", "en-US", "pt", "ar"];
let sortOptions: I18n.SortOptions = {locale: "zh-Hans-CN", isUseLocalName: true, isSuggestedFirst: true};
try {
// The language list after sorting is [zh-Hans, en-US, pt, ar].
let sortedLanguages = systemLocaleManager.getLanguageInfoArray(languages, sortOptions);
let sortedLanguages: Array<I18n.LocaleItem> = systemLocaleManager.getLanguageInfoArray(languages, sortOptions);
} catch(error) {
console.error(`call systemLocaleManager.getLanguageInfoArray failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -2342,16 +2408,19 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| 890001 | param value not valid |
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
// Assume that the system language is zh-Hans, the system region is CN, and the system locale is zh-Hans-CN.
let systemLocaleManager = new I18n.SystemLocaleManager();
var regions = ["CN", "US", "PT", "EG"];
var sortOptions = {locale: "zh-Hans-CN", isUseLocalName: false, isSuggestedFirst: true};
let systemLocaleManager: I18n.SystemLocaleManager = new I18n.SystemLocaleManager();
let regions: string[] = ["CN", "US", "PT", "EG"];
let sortOptions: I18n.SortOptions = {locale: "zh-Hans-CN", isUseLocalName: false, isSuggestedFirst: true};
try {
// The country/region list after sorting is [CN, EG, US, PT].
let sortedRegions = systemLocaleManager.getRegionInfoArray(regions, sortOptions);
let sortedRegions: Array<I18n.LocaleItem> = systemLocaleManager.getRegionInfoArray(regions, sortOptions);
} catch(error) {
console.error(`call systemLocaleManager.getRegionInfoArray failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -2372,15 +2441,18 @@ Obtains the array of time zone city items after sorting.
| Array&lt;[TimeZoneCityItem](#timezonecityitem10)&gt; | Array of time zone city items.|
**Example**
```js
```ts
import { BusinessError } from '@ohos.base';
try {
let timeZoneCityItemArray = I18n.SystemLocaleManager.getTimeZoneCityItemArray();
for (var i = 0; i < timeZoneCityItemArray.length; i++) {
let timeZoneCityItemArray: Array<I18n.TimeZoneCityItem> = I18n.SystemLocaleManager.getTimeZoneCityItemArray();
for (let i = 0; i < timeZoneCityItemArray.length; i++) {
console.log(timeZoneCityItemArray[i].zoneId + ", " + timeZoneCityItemArray[i].cityId + ", " + timeZoneCityItemArray[i].cityDisplayName +
", " + timeZoneCityItemArray[i].offset + "\r\n");
}
} catch(error) {
console.error(`call SystemLocaleManager.getTimeZoneCityItemArray failed, error code: ${error.code}, message: ${error.message}.`);
let err: BusinessError = error as BusinessError;
console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}
```
......@@ -2472,8 +2544,8 @@ This API is deprecated since API version 9. You are advised to use [System.getDi
| string | Localized script for the specified country.|
**Example**
```js
let countryName = I18n.getDisplayCountry("zh-CN", "en-GB", true); // countryName = true
```ts
let countryName: string = I18n.getDisplayCountry("zh-CN", "en-GB", true); // countryName = true
countryName = I18n.getDisplayCountry("zh-CN", "en-GB"); // countryName = true
```
......@@ -2503,8 +2575,8 @@ This API is deprecated since API version 9. You are advised to use [System.getDi
| string | Localized script for the specified language.|
**Example**
```js
let languageName = I18n.getDisplayLanguage("zh", "en-GB", true); // languageName = "Chinese"
```ts
let languageName: string = I18n.getDisplayLanguage("zh", "en-GB", true); // languageName = "Chinese"
languageName = I18n.getDisplayLanguage("zh", "en-GB"); // languageName = "Chinese"
```
......@@ -2526,8 +2598,8 @@ This API is deprecated since API version 9. You are advised to use [System.getSy
| string | System language ID.|
**Example**
```js
let systemLanguage = I18n.getSystemLanguage(); // Obtain the current system language.
```ts
let systemLanguage: string = I18n.getSystemLanguage(); // Obtain the current system language.
```
......@@ -2548,8 +2620,8 @@ This API is deprecated since API version 9. You are advised to use [System.getSy
| string | System region ID.|
**Example**
```js
let region = I18n.getSystemRegion(); // Obtain the current system region.
```ts
let region: string = I18n.getSystemRegion(); // Obtain the current system region.
```
......@@ -2570,8 +2642,8 @@ This API is deprecated since API version 9. You are advised to use [System.getSy
| string | System locale ID.|
**Example**
```js
let locale = I18n.getSystemLocale (); // Obtain the system locale.
```ts
let locale: string = I18n.getSystemLocale (); // Obtain the system locale.
```
......@@ -2589,11 +2661,11 @@ This API is deprecated since API version 9. You are advised to use [System.is24H
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the 24-hour clock is used; returns **false** otherwise.|
| boolean | The value **true** indicates that the 24-hour clock is used, and the value **false** indicates the opposite.|
**Example**
```js
let is24HourClock = I18n.is24HourClock();
```ts
let is24HourClock: boolean = I18n.is24HourClock();
```
......@@ -2619,12 +2691,12 @@ This API is deprecated since API version 9. You are advised to use [System.set24
| Type | Description |
| ------- | ----------------------------- |
| boolean | Returns **true** if the 24-hour clock is enabled; returns **false** otherwise.|
| boolean | The value **true** indicates that the 24-hour clock is enabled, and the value **false** indicates the opposite.|
**Example**
```js
```ts
// Set the system time to the 24-hour clock.
let success = I18n.set24HourClock(true);
let success: boolean = I18n.set24HourClock(true);
```
......@@ -2651,14 +2723,14 @@ This API is supported since API version 8 and is deprecated since API version 9.
| Type | Description |
| ------- | ----------------------------- |
| boolean | Returns **true** if the preferred language is successfully added; returns **false** otherwise.|
| boolean | The value **true** indicates that the preferred language is successfully added, and the value **false** indicates the opposite.|
**Example**
```js
```ts
// Add zh-CN to the preferred language list.
let language = 'zh-CN';
let index = 0;
let success = I18n.addPreferredLanguage(language, index);
let language: string = 'zh-CN';
let index: number = 0;
let success: boolean = I18n.addPreferredLanguage(language, index);
```
......@@ -2684,13 +2756,13 @@ This API is supported since API version 8 and is deprecated since API version 9.
| Type | Description |
| ------- | ----------------------------- |
| boolean | Returns **true** if the preferred language is deleted; returns **false** otherwise.|
| boolean | The value **true** indicates that the preferred language is deleted, and the value **false** indicates the opposite.|
**Example**
```js
```ts
// Delete the first preferred language from the preferred language list.
let index = 0;
let success = I18n.removePreferredLanguage(index);
let index: number = 0;
let success: boolean = I18n.removePreferredLanguage(index);
```
......@@ -2711,8 +2783,8 @@ This API is supported since API version 8 and is deprecated since API version 9.
| Array&lt;string&gt; | List of preferred languages.|
**Example**
```js
let preferredLanguageList = I18n.getPreferredLanguageList(); // Obtain the preferred language list.
```ts
let preferredLanguageList: Array<string> = I18n.getPreferredLanguageList(); // Obtain the preferred language list.
```
......@@ -2733,8 +2805,8 @@ This API is supported since API version 8 and is deprecated since API version 9.
| string | First language in the preferred language list.|
**Example**
```js
let firstPreferredLanguage = I18n.getFirstPreferredLanguage();
```ts
let firstPreferredLanguage: string = I18n.getFirstPreferredLanguage();
```
......@@ -2791,7 +2863,7 @@ This API is supported since API version 8 and is deprecated since API version 9.
| Type | Description |
| ------- | ------------------------------------ |
| boolean | Returns **true** if the input character is a digit; returns **false** otherwise.|
| boolean | The value **true** indicates that the input character is a digit, and the value **false** indicates the opposite.|
### isSpaceChar<sup>(deprecated)</sup>
......@@ -2814,7 +2886,7 @@ This API is supported since API version 8 and is deprecated since API version 9.
| Type | Description |
| ------- | -------------------------------------- |
| boolean | Returns **true** if the input character is a space; returns **false** otherwise.|
| boolean | The value **true** indicates that the input character is a space, and the value **false** indicates the opposite.|
### isWhitespace<sup>(deprecated)</sup>
......@@ -2837,7 +2909,7 @@ This API is supported since API version 8 and is deprecated since API version 9.
| Type | Description |
| ------- | -------------------------------------- |
| boolean | Returns **true** if the input character is a white space; returns **false** otherwise.|
| boolean | The value **true** indicates that the input character is a white space, and the value **false** indicates the opposite.|
### isRTL<sup>(deprecated)</sup>
......@@ -2860,7 +2932,7 @@ This API is supported since API version 8 and is deprecated since API version 9.
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the input character is of the RTL language; returns **false** otherwise.|
| boolean | The value **true** indicates that the input character is of the RTL language, and the value **false** indicates the opposite.|
### isIdeograph<sup>(deprecated)</sup>
......@@ -2883,7 +2955,7 @@ This API is supported since API version 8 and is deprecated since API version 9.
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the input character is an ideographic character; returns **false** otherwise.|
| boolean | The value **true** indicates that the input character is an ideographic character, and the value **false** indicates the opposite.|
### isLetter<sup>(deprecated)</sup>
......@@ -2906,7 +2978,7 @@ This API is supported since API version 8 and is deprecated since API version 9.
| Type | Description |
| ------- | ------------------------------------ |
| boolean | Returns **true** if the input character is a letter; returns **false** otherwise.|
| boolean | The value **true** indicates that the input character is a letter, and the value **false** indicates the opposite.|
### isLowerCase<sup>(deprecated)</sup>
......@@ -2929,7 +3001,7 @@ This API is supported since API version 8 and is deprecated since API version 9.
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the input character is a lowercase letter; returns **false** otherwise.|
| boolean | The value **true** indicates that the input character is a lowercase letter, and the value **false** indicates the opposite.|
### isUpperCase<sup>(deprecated)</sup>
......@@ -2952,7 +3024,7 @@ This API is supported since API version 8 and is deprecated since API version 9.
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the input character is an uppercase letter; returns **false** otherwise.|
| boolean | The value **true** indicates that the input character is an uppercase letter, and the value **false** indicates the opposite.|
### getType<sup>(deprecated)</sup>
......@@ -2975,4 +3047,4 @@ This API is supported since API version 8 and is deprecated since API version 9.
| Type | Description |
| ------ | ----------- |
| string | Type of the input character.|
| string | Category value of the input character.|
# @ohos.ai.intelligentVoice (Intelligent Voice)
The **intelligentVoice** module provides the intelligent voice enrollment and voice wakeup functions.
Its functions are implemented by:
- [IntelligentVoiceManager](#intelligentvoicemanager): intelligent voice manager class, which declares the functions provided by the module. Currently, voice enrollment and voice wakeup are supported. Before developing intelligent voice functions, call [getIntelligentVoiceManager()](#intelligentvoicegetintelligentvoicemanager) to check whether they are supported.
- [EnrollIntelligentVoiceEngine](#enrollintelligentvoiceengine): class that implements voice enrollment. You need to perform voice enrollment before using voice wakeup.
- [WakeupIntelligentVoiceEngine](#wakeupintelligentvoiceengine): class that implements voice wakeup. You need to perform voice enrollment before using voice wakeup.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> - The APIs provided by this module are system APIs.
## Modules to Import
```js
import intelligentVoice from '@ohos.ai.intelligentVoice';
```
## intelligentVoice.getIntelligentVoiceManager
getIntelligentVoiceManager(): IntelligentVoiceManager
Obtains an instance of the intelligent voice manager.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Return value**
| Type | Description |
| ----------------------------- | ------------ |
| [IntelligentVoiceManager](#intelligentvoicemanager)| Instance of the intelligent voice manager.|
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700101 | No memory. |
**Example**
```js
var intelligentVoiceManager = null;
try {
intelligentVoiceManager = intelligentVoice.getIntelligentVoiceManager();
} catch (err) {
console.error('Get IntelligentVoiceManager failed. Code:${err.code}, message:${err.message}');
}
```
## intelligentVoice.createEnrollIntelligentVoiceEngine
createEnrollIntelligentVoiceEngine(descriptor: EnrollIntelligentVoiceEngineDescriptor, callback: AsyncCallback&lt;EnrollIntelligentVoiceEngine&gt;): void
Creates an instance of the intelligent voice enrollment engine. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------- | ---- | ---------------------- |
| descriptor | [EnrollIntelligentVoiceEngineDescriptor](#enrollintelligentvoiceenginedescriptor) | Yes | Descriptor of the intelligent voice enrollment engine. |
| callback | AsyncCallback\<[EnrollIntelligentVoiceEngine](#enrollintelligentvoiceengine)\> | Yes | Callback used to return the result. |
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700101 | No memory. |
| 22700102 | Input parameter value error. |
**Example**
```js
let engineDescriptor = {
wakeupPhrase:'Xiaohua Xiaohua',
}
var enrollIntelligentVoiceEngine = null;
intelligentVoice.createEnrollIntelligentVoiceEngine(engineDescriptor, (err, data) => {
if (err) {
console.error(`Failed to create enrollIntelligentVoice engine, Code:${err.code}, message:${err.message}`);
} else {
console.info('Succeeded in creating enrollIntelligentVoice engine.');
enrollIntelligentVoiceEngine = data;
}
});
```
## intelligentVoice.createEnrollIntelligentVoiceEngine
createEnrollIntelligentVoiceEngine(descriptor: EnrollIntelligentVoiceEngineDescriptor): Promise&lt;EnrollIntelligentVoiceEngine&gt;
Creates an instance of the intelligent voice enrollment engine. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------- | ---- | ---------------------- |
| descriptor | [EnrollIntelligentVoiceEngineDescriptor](#enrollintelligentvoiceenginedescriptor) | Yes | Descriptor of the intelligent voice enrollment engine. |
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Promise\<[EnrollIntelligentVoiceEngine](#enrollintelligentvoiceengine)\> | Promise used to return the result. |
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700101 | No memory. |
| 22700102 | Input parameter value error. |
**Example**
```js
var enrollIntelligentVoiceEngine = null;
let engineDescriptor = {
wakeupPhrase:'Xiaohua Xiaohua',
}
intelligentVoice.createEnrollIntelligentVoiceEngine(engineDescriptor).then((data) => {
enrollIntelligentVoiceEngine = data;
console.info('Succeeded in creating enrollIntelligentVoice engine.');
}).catch((err) => {
console.error(`Failed to create enrollIntelligentVoice engine, Code:${err.code}, message:${err.message}`);
});
```
## intelligentVoice.createWakeupIntelligentVoiceEngine
createWakeupIntelligentVoiceEngine(descriptor: WakeupIntelligentVoiceEngineDescriptor, callback: AsyncCallback&lt;WakeupIntelligentVoiceEngine&gt;): void
Creates an instance of the intelligent voice wakeup engine. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------- | ---- | ---------------------- |
| descriptor | [WakeupIntelligentVoiceEngineDescriptor](#wakeupintelligentvoiceenginedescriptor) | Yes | Descriptor of the intelligent voice wakeup engine. |
| callback | AsyncCallback\<[WakeupIntelligentVoiceEngine](#wakeupintelligentvoiceengine)\> | Yes | Callback used to return the result. |
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700101 | No memory. |
| 22700102 | Input parameter value error. |
**Example**
```js
let engineDescriptor = {
needReconfirm: true,
wakeupPhrase:'Xiaohua Xiaohua',
}
var wakeupIntelligentVoiceEngine = null;
intelligentVoice.createWakeupIntelligentVoiceEngine(engineDescriptor, (err, data) => {
if (err) {
console.error(`Failed to create wakeupIntelligentVoice engine, Code:${err.code}, message:${err.message}`);
} else {
console.info('Succeeded in creating wakeupIntelligentVoice engine.');
wakeupIntelligentVoiceEngine = data;
}
});
```
## intelligentVoice.createWakeupIntelligentVoiceEngine
createWakeupIntelligentVoiceEngine(descriptor: WakeupIntelligentVoiceEngineDescriptor): Promise&lt;WakeupIntelligentVoiceEngine&gt;
Creates an instance of the intelligent voice wakeup engine. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------- | ---- | ---------------------- |
| descriptor | [WakeupIntelligentVoiceEngineDescriptor](#wakeupintelligentvoiceenginedescriptor) | Yes | Descriptor of the intelligent voice wakeup engine. |
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Promise\<[WakeupIntelligentVoiceEngine](#wakeupintelligentvoiceengine)> | Promise used to return the result. |
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700101 | No memory. |
| 22700102 | Input parameter value error. |
**Example**
```js
let engineDescriptor = {
needReconfirm: true,
wakeupPhrase:'Xiaohua Xiaohua',
}
var wakeupIntelligentVoiceEngine = null;
intelligentVoice.createWakeupIntelligentVoiceEngine(engineDescriptor).then((data) => {
wakeupIntelligentVoiceEngine = data;
console.info('Succeeded in creating wakeupIntelligentVoice engine.');
}).catch((err) => {
console.error('Failed to create wakeupIntelligentVoice engine, Code:${err.code}, message:${err.message});
});
```
## IntelligentVoiceManager
Class that implements intelligent voice management. Before use, you need to call [getIntelligentVoiceManager()](#intelligentvoicegetintelligentvoicemanager) to obtain an **IntelligentVoiceManager** object.
### getCapabilityInfo
getCapabilityInfo(): Array&lt;IntelligentVoiceEngineType&gt;
Obtains the list of supported intelligent voice engine types.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Array\<[IntelligentVoiceEngineType](#intelligentvoiceenginetype)\> | Array of supported intelligent voice engine types. |
**Example**
```js
let info = intelligentVoiceManager.getCapabilityInfo();
```
### on('serviceChange')
on(type: 'serviceChange', callback: Callback&lt;ServiceChangeType&gt;): void
Subscribes to service change events. A callback is invoked when the status of the intelligent voice service changes.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| type | string | Yes | Event type. This field has a fixed value of **serviceChange**.|
| callback | Callback\<[ServiceChangeType](#servicechangetype)\> | Yes | Callback for the service status change.|
**Example**
```js
intelligentVoiceManager.on('serviceChange', (serviceChangeType) => {});
```
### off('serviceChange')
off(type: 'serviceChange', callback?: Callback\<ServiceChangeType\>): void
Unsubscribes from service change events.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| type | string | Yes | Event type. This field has a fixed value of **serviceChange**.|
| callback | Callback\<[ServiceChangeType](#servicechangetype)\> | No | Callback for processing of the service status change event. If this parameter is specified, only the specified callback will be unsubscribed. Otherwise, all callbacks will be unsubscribed. |
**Example**
```js
intelligentVoiceManager.off('serviceChange');
```
## ServiceChangeType
Enumerates service status change types.
**System capability**: SystemCapability.AI.IntelligentVoice.Core
| Name | Value | Description |
| ------------------------- | ---- | ------------ |
| SERVICE_UNAVAILABLE | 0 | The service is unavailable. |
## IntelligentVoiceEngineType
Enumerates intelligent voice engine types.
**System capability**: SystemCapability.AI.IntelligentVoice.Core
| Name | Value | Description |
| ------------------------- | ---- | ------------ |
| ENROLL_ENGINE_TYPE | 0 | Voice enrollment engine. |
| WAKEUP_ENGINE_TYPE | 1 | Voice wakeup engine. |
| UPDATE_ENGINE_TYPE | 2 | Silent update engine. |
## EnrollIntelligentVoiceEngineDescriptor
Defines the descriptor of an intelligent voice enrollment engine.
**System capability**: SystemCapability.AI.IntelligentVoice.Core
| Name | Type | Mandatory | Description |
| ------ | ----------------------------- | -------------- | ---------- |
| wakeupPhrase | string | Yes | Wakeup phrase.|
## WakeupIntelligentVoiceEngineDescriptor
Defines the descriptor of an intelligent voice wakeup engine.
**System capability**: SystemCapability.AI.IntelligentVoice.Core
| Name | Type | Mandatory | Description |
| ------ | ----------------------------- | -------------- | ---------- |
| needReconfirm | boolean | Yes | Whether re-confirmation of the wakeup result is needed. The value **true** indicates that re-confirmation is needed, and the value **false** indicates the opposite.|
| wakeupPhrase | string | Yes | Wakeup phrase.|
## EnrollEngineConfig
Defines the enrollment engine configuration.
**System capability**: SystemCapability.AI.IntelligentVoice.Core
| Name | Type | Mandatory | Description |
| ------ | ----------------------------- | -------------- | ---------- |
| language | string | Yes | Language supported by the enrollment engine. Only Chinese is supported currently, and the value is **zh**.|
| region | string | Yes | Country/region supported by the enrollment engine. Only China is supported currently, and the value is **CN**.|
## SensibilityType
Enumerates wakeup sensibility types.
A sensibility type maps to a wakeup threshold. A higher sensibility indicates a lower threshold and a higher wakeup probability.
**System capability**: SystemCapability.AI.IntelligentVoice.Core
| Name | Value | Description |
| ------------------------- | ---- | ------------ |
| LOW_SENSIBILITY | 1 | Low sensibility. |
| MIDDLE_SENSIBILITY | 2 | Medium sensibility. |
| HIGH_SENSIBILITY | 3 | High sensibility. |
## WakeupHapInfo
Defines the HAP information for an wakeup application.
**System capability**: SystemCapability.AI.IntelligentVoice.Core
| Name | Type | Mandatory | Description |
| ------ | ----------------------------- | -------------- | ---------- |
| bundleName | string | Yes | Bundle name of the wakeup application.|
| abilityName | string | Yes | Ability name of the wakeup application.|
## WakeupIntelligentVoiceEventType
Enumerates types of intelligent voice wakeup events.
**System capability**: SystemCapability.AI.IntelligentVoice.Core
| Name | Value | Description |
| ------------------------- | ---- | ------------ |
| INTELLIGENT_VOICE_EVENT_WAKEUP_NONE | 0 | No wakeup. |
| INTELLIGENT_VOICE_EVENT_RECOGNIZE_COMPLETE | 1 | Wakeup recognition completed. |
## IntelligentVoiceErrorCode
Enumerates error codes of intelligent voice wakeup.
**System capability**: SystemCapability.AI.IntelligentVoice.Core
| Name | Value | Description |
| ------------------------- | ---- | ------------ |
| INTELLIGENT_VOICE_NO_MEMORY | 22700101 | Insufficient memory. |
| INTELLIGENT_VOICE_INVALID_PARAM | 22700102 | Invalid parameter. |
| INTELLIGENT_VOICE_INIT_FAILED | 22700103 | Enrollment failed. |
| INTELLIGENT_VOICE_COMMIT_ENROLL_FAILED | 22700104 | Enrollment commit failed. |
## EnrollResult
Enumerates enrollment results.
**System capability**: SystemCapability.AI.IntelligentVoice.Core
| Name | Value | Description |
| ------------------------- | ---- | ------------ |
| SUCCESS | 0 | Enrollment succeeded. |
| VPR_TRAIN_FAILED | -1 | Voiceprint training failed. |
| WAKEUP_PHRASE_NOT_MATCH | -2 | Wakeup phrase mismatched. |
| TOO_NOISY | -3 | Environment too noisy. |
| TOO_LOUD | -4 | Voice too loud. |
| INTERVAL_LARGE | -5 | Interval between wakeup phrases too long. |
| DIFFERENT_PERSON | -6 | Wakeup phrases enrolled by different persons. |
| UNKNOWN_ERROR | -100 | Unknown error. |
## EnrollCallbackInfo
Defines the enrollment callback information.
**System capability**: SystemCapability.AI.IntelligentVoice.Core
| Name | Type | Mandatory | Description |
| ------ | ----------------------------- | -------------- | ---------- |
| result | [EnrollResult](#enrollresult) | Yes | Enrollment result.|
| context | string | Yes | Context of the enrollment event.|
## WakeupIntelligentVoiceEngineCallbackInfo
Defines the callback information for the intelligent voice wakeup engine.
**System capability**: SystemCapability.AI.IntelligentVoice.Core
| Name | Type | Mandatory | Description |
| ------ | ----------------------------- | -------------- | ---------- |
| eventId | [WakeupIntelligentVoiceEventType](#wakeupintelligentvoiceeventtype) | Yes | Event type of the intelligent voice wakeup engine.|
| isSuccess | boolean | Yes | Wakeup result. The value **true** indicates that the wakeup is successful, and the value **false** indicates the opposite.|
| context | string | Yes | Context of the wakeup event.|
## EnrollIntelligentVoiceEngine
Class that implements the intelligent voice enrollment engine. Before use, you need to call [createEnrollIntelligentVoiceEngine()](#intelligentvoicecreateenrollintelligentvoiceengine) to obtain an instance of the intelligent voice enrollment engine.
### getSupportedRegions
getSupportedRegions(callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void
Obtains the list of supported countries/regions. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback used to return the result, which is an array of supported countries/regions. Only China is supported currently, and the value is **CN**.|
**Example**
```js
let regions = null;
enrollIntelligentVoiceEngine.getSupportedRegions((err, data) => {
if (err) {
console.error(`Failed to get supported regions, Code:${err.code}, message:${err.message}`);
} else {
regions = data;
console.info('Succeeded in getting supported regions, regions:${regions}.');
}
});
```
### getSupportedRegions
getSupportedRegions(): Promise&lt;Array&lt;string&gt;&gt;
Obtains the list of supported countries/regions. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the result, which is an array of supported countries/regions. Only China is supported currently, and the value is **CN**. |
**Example**
```js
let regions = null;
enrollIntelligentVoiceEngine.getSupportedRegions().then((data) => {
regions = data;
console.info('Succeeded in getting supported regions, regions:${regions}.');
}).catch((err) => {
console.error(`Failed to get supported regions, Code:${err.code}, message:${err.message}`);
});
```
### init
init(config: EnrollEngineConfig, callback: AsyncCallback&lt;void&gt;): void
Initializes the intelligent voice enrollment engine. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| config | [EnrollEngineConfig](#enrollengineconfig) | Yes | Configuration of the intelligent voice enrollment engine.|
| callback |AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700102 | Input parameter value error. |
| 22700103 | Init failed. |
**Example**
```js
let config = {
language: "zh",
area: "CN",
}
enrollIntelligentVoiceEngine.init(config, (err) => {
if (err) {
console.error(`Failed to initialize enrollIntelligentVoice engine. Code:${err.code}, message:${err.message}`);
} else {
console.info('Succeeded in initialzing enrollIntelligentVoice engine.');
}
});
```
### init
init(config: EnrollEngineConfig): Promise&lt;void&gt;
Initializes the intelligent voice enrollment engine. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| config | [EnrollEngineConfig](#enrollengineconfig) | Yes | Configuration of the intelligent voice enrollment engine.|
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value. |
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700102 | Input parameter value error. |
| 22700103 | Init failed. |
**Example**
```js
let config = {
language: "zh",
area: "CN",
}
enrollIntelligentVoiceEngine.init(config).then(() => {
console.info('Succeeded in initializing enrollIntelligentVoice engine.');
}).catch((err) => {
console.error(`Failed to initialize enrollIntelligentVoice engine. Code:${err.code}, message:${err.message}`);
});
```
### enrollForResult
enrollForResult(isLast: boolean, callback: AsyncCallback&lt;EnrollCallbackInfo&gt;): void
Obtains the enrollment result. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| isLast | boolean | Yes | Whether this is the last enrollment. The value **value** indicates the last enrollment, and the value **false** indicates the opposite.|
| callback | AsyncCallback&lt;[EnrollCallbackInfo](#enrollcallbackinfo)&gt; | Yes | Callback used to return the result.|
**Example**
```js
let isLast = true;
let callbackInfo = null;
enrollIntelligentVoiceEngine.enrollForResult(isLast, (err, data) => {
if (err) {
console.error(`Failed to enroll for result, Code:${err.code}, message:${err.message}`);
} else {
callbackInfo = data;
console.info('Succeeded in enrolling for result, info:${callbackInfo}.');
}
});
```
### enrollForResult
enrollForResult(isLast: boolean): Promise&lt;EnrollCallbackInfo&gt;
Obtains the enrollment result. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| isLast | boolean | Yes | Whether this is the last enrollment. The value **value** indicates the last enrollment, and the value **false** indicates the opposite.|
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Promise&lt;[EnrollCallbackInfo](#enrollcallbackinfo)&gt; | Promise used to return the result. |
**Example**
```js
let isLast = true;
let callbackInfo = null;
enrollIntelligentVoiceEngine.enrollForResult(isLast).then((data) => {
callbackInfo = data;
console.info('Succeeded in enrolling for result, info:${callbackInfo}.');
}).catch((err) => {
console.error(`Failed to enroll for result, Code:${err.code}, message:${err.message}`);
});
```
### stop
stop(callback: AsyncCallback&lt;void&gt;): void
Stops the enrollment. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example**
```js
enrollIntelligentVoiceEngine.stop((err) => {
if (err) {
console.error(`Failed to stop enrollIntelligentVoice engine, Code:${err.code}, message:${err.message}`);
} else {
console.info('Succeeded in stopping enrollIntelligentVoice engine.');
}
});
```
### stop
stop(): Promise&lt;void&gt;
Stops the enrollment. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value. |
**Example**
```js
enrollIntelligentVoiceEngine.stop().then(() => {
console.info('Succeeded in stopping enrollIntelligentVoice engine.');
}).catch((err) => {
console.error(`Failed to stop enrollIntelligentVoice engine, Code:${err.code}, message:${err.message}`);
});
```
### commit
commit(callback: AsyncCallback&lt;void&gt;): void
Commits the enrollment. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700104 | Commit enroll failed. |
**Example**
```js
enrollIntelligentVoiceEngine.commit((err) => {
if (err) {
console.error(`Failed to commit enroll, Code:${err.code}, message:${err.message}`);
} else {
console.info('Succeeded in committing enroll.');
}
});
```
### commit
commit(): Promise&lt;void&gt;
Commits the enrollment. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value. |
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700104 | Commit enroll failed. |
**Example**
```js
enrollIntelligentVoiceEngine.commit().then(() => {
console.info('Succeeded in committing enroll.');
}).catch((err) => {
console.error(`Failed to commit enroll, Code:${err.code}, message:${err.message}`);
});
```
### setWakeupHapInfo
setWakeupHapInfo(info: WakeupHapInfo, callback: AsyncCallback\<void>): void
Sets the HAP information for the wakeup application. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| info | [WakeupHapInfo](#wakeuphapinfo) | Yes | HAP information for the wakeup application.|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700102 | Input parameter value error. |
**Example**
```js
let info = {
bundleName: "com.wakeup",
abilityName: "WakeUpExtAbility",
}
enrollIntelligentVoiceEngine.setWakeupHapInfo(info, (err) => {
if (err) {
console.error('Failed to set wakeup hap info, Code:${err.code}, message:${err.message}');
} else {
console.info('Succeeded in setting wakeup hap info.');
}
});
```
### setWakeupHapInfo
setWakeupHapInfo(info: WakeupHapInfo): Promise\<void\>
Sets the HAP information for the wakeup application. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value. |
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700102 | Input parameter value error. |
**Example**
```js
let info = {
bundleName: "com.wakeup",
abilityName: "WakeUpExtAbility",
}
enrollIntelligentVoiceEngine.setWakeupHapInfo(info).then(() => {
console.info('Succeeded in setting wakeup hap info.');
}).catch((err) => {
console.error('Failed to set wakeup hap info, Code:${err.code},
});
```
### setSensibility
setSensibility(sensibility: SensibilityType, callback: AsyncCallback\<void\>): void
Sets the wakeup sensibility. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| sensibility | [SensibilityType](#sensibilitytype) | Yes | Sensibility type.|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700102 | Input parameter value error. |
**Example**
```js
enrollIntelligentVoiceEngine.setSensibility(intelligentVoice.SensibilityType.LOW_SENSIBILITY, (err) => {
if (err) {
console.error(`Failed to set sensibility, Code:${err.code}, message:${err.message}`);
} else {
console.info('Succeeded in setting sensibility.');
}
});
```
### setSensibility
setSensibility(sensibility: SensibilityType): Promise\<void\>
Sets the wakeup sensibility. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| sensibility | [SensibilityType](#sensibilitytype) | Yes | Sensibility type.|
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value. |
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700102 | Input parameter value error. |
**Example**
```js
enrollIntelligentVoiceEngine.setSensibility(intelligentVoice.SensibilityType.LOW_SENSIBILITY).then(() => {
console.info('Succeeded in setting sensibility.');
}).catch((err) => {
console.error(`Failed to set sensibility, Code:${err.code}, message:${err.message}`);
});
```
### setParameter
setParameter(key: string, value: string, callback: AsyncCallback\<void\>): void
Sets specified intelligent voice parameters. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| key | string | Yes | Key.|
| value | string | Yes | Value.|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700102 | Input parameter value error. |
**Example**
```js
enrollIntelligentVoiceEngine.setParameter('scene', '0', (err) => {
if (err) {
console.error(`Failed to set parameter, Code:${err.code}, message:${err.message}`);
} else {
console.info('Succeeded in setting parameter');
}
});
```
### setParameter
setParameter(key: string, value: string): Promise\<void\>
Sets specified intelligent voice parameters. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| key | string | Yes | Key.|
| value | string | Yes | Value.|
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value. |
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700102 | Input parameter value error. |
**Example**
```js
enrollIntelligentVoiceEngine.setParameter('scene', '0').then(() => {
console.info('Succeeded in setting parameter');
}).catch((err) => {
console.error(`Failed to set parameter, Code:${err.code}, message:${err.message}`);
});
```
### getParameter
getParameter(key: string, callback: AsyncCallback\<string\>): void
Obtains specified intelligent voice parameters. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| key | string | Yes | Key.|
| callback | AsyncCallback\<string\> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700102 | Input parameter value error. |
**Example**
```js
enrollIntelligentVoiceEngine.getParameter('key', (err,data) => {
if (err) {
console.error(`Failed to get parameter, Code:${err.code}, message:${err.message}`);
} else {
let param = data;
console.info('Succeeded in getting parameter, param:${param}');
}
});
```
### getParameter
getParameter(key: string): Promise\<string\>
Obtains specified intelligent voice parameters. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| key | string | Yes | Key.|
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Promise\<string\> | Promise used to return the result. |
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700102 | Input parameter value error. |
**Example**
```js
let param = null;
enrollIntelligentVoiceEngine.getParameter('key').then((data) => {
param = data;
console.info('Succeeded in getting parameter, param:${param}');
}).catch((err) => {
console.error(`Failed to get parameter, Code:${err.code}, message:${err.message}`);
});
```
### release
release(callback: AsyncCallback&lt;void&gt;): void
Releases the intelligent voice enrollment engine. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Example**
```js
enrollIntelligentVoiceEngine.release((err) => {
if (err) {
console.error('Failed to release enrollIntelligentVoice engine, Code:${err.code}, message:${err.message}');
} else {
console.info('Succeeded in releasing enrollIntelligentVoice engine.');
}
});
```
### release
release(): Promise&lt;void&gt;
Releases the intelligent voice enrollment engine. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value. |
**Example**
```js
enrollIntelligentVoiceEngine.release().then(() => {
console.info('Succeeded in releasing enrollIntelligentVoice engine.');
}).catch((err) => {
console.error('Failed to release enrollIntelligentVoice engine, Code:${err.code}, message:${err.message}');
});
```
## WakeupIntelligentVoiceEngine
Class that implements the intelligent voice wakeup engine. Before use, you need to call [createWakeupIntelligentVoiceEngine()](#intelligentvoicecreatewakeupintelligentvoiceengine) to obtain an instance of the intelligent voice wakeup engine.
### getSupportedRegions
getSupportedRegions(callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void
Obtains the list of supported countries/regions. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback used to return the result, which is an array of supported countries/regions. Only China is supported currently, and the value is **CN**.|
**Example**
```js
let regions = null;
wakeupIntelligentVoiceEngine.getSupportedRegions((err, data) => {
if (err) {
console.error(`Failed to get supported regions, Code:${err.code}, message:${err.message}`);
} else {
regions = data;
console.info('Succeeded in getting supported regions, regions:${regions}.');
}
});
```
### getSupportedRegions
getSupportedRegions(): Promise&lt;Array&lt;string&gt;&gt;
Obtains the list of supported countries/regions. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the result, which is an array of supported countries/regions. Only China is supported currently, and the value is **CN**. |
**Example**
```js
let regions = null;
wakeupIntelligentVoiceEngine.getSupportedRegions().then((data) => {
regions = data;
console.info('Succeeded in getting supported regions, regions:${regions}.');
}).catch((err) => {
console.error(`Failed to get supported regions, Code:${err.code}, message:${err.message}`);
});
```
### setWakeupHapInfo
setWakeupHapInfo(info: WakeupHapInfo, callback: AsyncCallback\<void\>): void
Sets the HAP information for the wakeup application. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| info | [WakeupHapInfo](#wakeuphapinfo) | Yes | HAP information for the wakeup application.|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700102 | Input parameter value error. |
**Example**
```js
let info = {
bundleName: "com.wakeup",
abilityName: "WakeUpExtAbility",
}
wakeupIntelligentVoiceEngine.setWakeupHapInfo(info, (err) => {
if (err) {
console.error('Failed to set wakeup hap info, Code:${err.code}, message:${err.message}');
} else {
console.info('Succeeded in setting wakeup hap info.');
}
});
```
### setWakeupHapInfo
setWakeupHapInfo(info: WakeupHapInfo): Promise\<void\>
Sets the HAP information for the wakeup application. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| info | [WakeupHapInfo](#wakeuphapinfo) | Yes | HAP information for the wakeup application.|
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value. |
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700102 | Input parameter value error. |
**Example**
```js
let info = {
bundleName: "com.wakeup",
abilityName: "WakeUpExtAbility",
}
wakeupIntelligentVoiceEngine.setWakeupHapInfo(info).then(() => {
console.info('Succeeded in setting wakeup hap info.');
}).catch((err) => {
console.error('Failed to set wakeup hap info, Code:${err.code}, message:${err.message}');
});
```
### setSensibility
setSensibility(sensibility: SensibilityType, callback: AsyncCallback\<void\>): void
Sets the wakeup sensibility. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| sensibility | [SensibilityType](#sensibilitytype) | Yes | Sensibility type.|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700102 | Input parameter value error. |
**Example**
```js
wakeupIntelligentVoiceEngine.setSensibility(intelligentVoice.SensibilityType.LOW_SENSIBILITY, (err) => {
if (err) {
console.error(`Failed to set sensibility, Code:${err.code}, message:${err.message}`);
} else {
console.info('Succeeded in setting sensibility.');
}
});
```
### setSensibility
setSensibility(sensibility: SensibilityType): Promise\<void\>
Sets the wakeup sensibility. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| sensibility | [SensibilityType](#sensibilitytype) | Yes | Sensibility type.|
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value. |
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700102 | Input parameter value error. |
**Example**
```js
wakeupIntelligentVoiceEngine.setSensibility(intelligentVoice.SensibilityType.LOW_SENSIBILITY).then(() => {
console.info('Succeeded in setting sensibility.');
}).catch((err) => {
console.error(`Failed to set sensibility, Code:${err.code}, message:${err.message}`);
});
```
### setParameter
setParameter(key: string, value: string, callback: AsyncCallback\<void\>): void
Sets specified intelligent voice parameters. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| key | string | Yes | Key.|
| value | string | Yes | Value.|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700102 | Input parameter value error. |
**Example**
```js
wakeupIntelligentVoiceEngine.setParameter('scene', '0', (err) => {
if (err) {
console.error(`Failed to set parameter, Code:${err.code}, message:${err.message}`);
} else {
console.info('Succeeded in setting parameter');
}
});
```
### setParameter
setParameter(key: string, value: string): Promise\<void\>
Sets specified intelligent voice parameters. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| key | string | Yes | Key.|
| value | string | Yes | Value.|
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value. |
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700102 | Input parameter value error. |
**Example**
```js
wakeupIntelligentVoiceEngine.setParameter('scene', '0').then(() => {
console.info('Succeeded in setting parameter');
}).catch((err) => {
console.error(`Failed to set parameter, Code:${err.code}, message:${err.message}`);
});
```
### getParameter
getParameter(key: string, callback: AsyncCallback\<string\>): void
Obtains specified intelligent voice parameters. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| key | string | Yes | Key.|
| callback | AsyncCallback\<string\> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700102 | Input parameter value error. |
**Example**
```js
wakeupIntelligentVoiceEngine.getParameter('key', (err, data) => {
if (err) {
console.error(`Failed to get parameter, Code:${err.code}, message:${err.message}`);
} else {
let param = data;
console.info('Succeeded in getting parameter, param:${param}');
}
});
```
### getParameter
getParameter(key: string): Promise\<string\>
Obtains specified intelligent voice parameters. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| key | string | Yes | Key.|
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Promise\<string\> | Promise used to return the result. |
**Error codes**
For details about the error codes, see [Intelligent Voice Error Codes](../errorcodes/errorcode-intelligentVoice.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 22700102 | Input parameter value error. |
**Example**
```js
let param;
wakeupIntelligentVoiceEngine.getParameter('key').then((data) => {
param = data;
console.info('Succeeded in getting parameter, param:${param}');
}).catch((err) => {
console.error(`Failed to get parameter, Code:${err.code}, message:${err.message}`);
});
```
### release
release(callback: AsyncCallback\<void\>): void
Releases the intelligent voice wakeup engine. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Example**
```js
wakeupIntelligentVoiceEngine.release((err) => {
if (err) {
console.error('Failed to release wakeupIntelligentVoice engine, Code:${err.code}, message:${err.message}');
} else {
console.info('Succeeded in releasing wakeupIntelligentVoice engine.');
}
});
```
### release
release(): Promise\<void\>
Releases the intelligent voice wakeup engine. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Return value**
| Type | Description |
| ----------------------------------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value. |
**Example**
```js
wakeupIntelligentVoiceEngine.release().then(() => {
console.info('Succeeded in releasing wakeupIntelligentVoice engine.');
}).catch((err) => {
console.error('Failed to release wakeupIntelligentVoice engine, Code:${err.code}, message:${err.message}');
});
```
### on
on(type: 'wakeupIntelligentVoiceEvent', callback: Callback\<WakeupIntelligentVoiceEngineCallbackInfo\>): void
Subscribes to wakeup events.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| type | string | Yes | Event type. This field has a fixed value of **wakeupIntelligentVoiceEvent**.|
| callback | Callback\<[WakeupIntelligentVoiceEngineCallbackInfo](#wakeupintelligentvoiceenginecallbackinfo)\> | Yes | Processing of the wakeup event.|
**Example**
```js
wakeupIntelligentVoiceEngine.on('wakeupIntelligentVoiceEvent', (callback) => {
console.info(`wakeup intelligentvoice event`);
for (let prop in callback) {
console.info(`intelligentvoice prop: ${prop}`);
}
});
```
### off
off(type: 'wakeupIntelligentVoiceEvent', callback?: Callback\<WakeupIntelligentVoiceEngineCallbackInfo\>): void;
Unsubscribes from wakeup events.
**Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE
**System capability**: SystemCapability.AI.IntelligentVoice.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| type |string | Yes | Event type. This field has a fixed value of **wakeupIntelligentVoiceEvent**.|
| callback | Callback\<[WakeupIntelligentVoiceEngineCallbackInfo](#wakeupintelligentvoiceenginecallbackinfo)\> | No | Callback for processing of the wakeup event. If this parameter is specified, only the specified callback will be unsubscribed. Otherwise, all callbacks will be unsubscribed. |
**Example**
```js
wakeupIntelligentVoiceEngine.off('wakeupIntelligentVoiceEvent');
```
......@@ -408,7 +408,7 @@ syscontext.resourceManager.getRawFileContent(inputName).then(async (buffer) => {
let mindSporeLiteModel = await mindSporeLite.loadModelFromFile(model_file);
const modelInputs = mindSporeLiteModel.getInputs();
modelInputs[0].setData(inputBuffer.buffer);
result.predict(modelInputs, (result) => {
mindSporeLiteModel.predict(modelInputs, (result) => {
let output = new Float32Array(result[0].getData());
for (let i = 0; i < output.length; i++) {
console.log(output[i].toString());
......@@ -448,7 +448,7 @@ syscontext.resourceManager.getRawFileContent(inputName).then(async (buffer) => {
let mindSporeLiteModel = await mindSporeLite.loadModelFromFile(model_file);
const modelInputs = mindSporeLiteModel.getInputs();
modelInputs[0].setData(inputBuffer.buffer);
result.predict(modelInputs).then((result) => {
mindSporeLiteModel.predict(modelInputs).then((result) => {
let output = new Float32Array(result[0].getData());
for (let i = 0; i < output.length; i++) {
console.log(output[i].toString());
......@@ -549,7 +549,7 @@ syscontext.resourceManager.getRawFileContent(inputName).then(async (buffer) => {
let mindSporeLiteModel = await mindSporeLite.loadModelFromFile(model_file);
const modelInputs = mindSporeLiteModel.getInputs();
modelInputs[0].setData(inputBuffer.buffer);
result.predict(modelInputs).then((result) => {
mindSporeLiteModel.predict(modelInputs).then((result) => {
let output = new Float32Array(result[0].getData());
for (let i = 0; i < output.length; i++) {
console.log(output[i].toString());
......@@ -579,7 +579,7 @@ import resourceManager from '@ohos.resourceManager'
let inputName = 'input_data.bin';
let syscontext = globalThis.context;
syscontext.resourceManager.getRawFileContent(inputName).then(async (buffer) => {
inputBuffer = buffer;
let inputBuffer = buffer;
let model_file = '/path/to/xxx.ms';
let mindSporeLiteModel = await mindSporeLite.loadModelFromFile(model_file);
const modelInputs = mindSporeLiteModel.getInputs();
......
......@@ -346,7 +346,7 @@ connection.getDefaultHttpProxy((error, data) => {
getDefaultHttpProxy(): Promise\<HttpProxy>;
Obtains the default proxy configuration of the network.
Obtains the default HTTP proxy configuration of the network.
If the global proxy is set, the global HTTP proxy configuration is returned. If [setAppNet](#connectionsetappnet) is used to bind the application to the network specified by [NetHandle](#nethandle), the HTTP proxy configuration of this network is returned. In other cases, the HTTP proxy configuration of the default network is returned.
This API uses a promise to return the result.
......@@ -438,6 +438,34 @@ connection.getAppNet().then((data) => {
})
```
## connection.getAppNetSync<sup>10+</sup>
getAppNetSync(): NetHandle
Obtains information about the network bound to an application. This API returns the result synchronously.
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| --------- | ---------------------------------- |
| [NetHandle](#nethandle8) | Handle of the data network bound to the application.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 401 | Parameter error. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let netHandle = connection.getAppNetSync();
```
## connection.SetAppNet<sup>9+</sup>
setAppNet(netHandle: NetHandle, callback: AsyncCallback\<void>): void
......@@ -587,6 +615,37 @@ connection.getAllNets().then(function (data) {
});
```
## connection.getAllNetsSync<sup>10+</sup>
getAllNetsSync(): Array&lt;NetHandle&gt;
Obtains the list of all connected networks. This API returns the result synchronously.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| --------- | ---------------------------------- |
| Array&lt;[NetHandle](#nethandle8)&gt; | List of all activated data networks.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let netHandle = connection.getAllNetsSync();
```
## connection.getConnectionProperties<sup>8+</sup>
getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<ConnectionProperties>): void
......@@ -667,6 +726,45 @@ connection.getDefaultNet().then(function (netHandle) {
})
```
## connection.getConnectionPropertiesSync<sup>10+</sup>
getConnectionPropertiesSync(netHandle: NetHandle): ConnectionProperties
Obtains network connection information based on the specified **netHandle**.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ----------------------- | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle8) | Yes | Handle of the data network.|
**Return value**
| Type | Description |
| ------------------------------------------------------- | --------------------------------- |
| [ConnectionProperties](#connectionproperties8) | Network connection information.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let netHandle = connection.getDefaultNetsSync();
let connectionproperties = connection.getConnectionPropertiesSync(netHandle);
```
## connection.getNetCapabilities<sup>8+</sup>
getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilities>): void
......@@ -747,6 +845,45 @@ connection.getDefaultNet().then(function (netHandle) {
})
```
## connection.getNetCapabilitiesSync<sup>10+</sup>
getNetCapabilitiesSync(netHandle: NetHandle): NetCapabilities
Obtains capability information of the network corresponding to the **netHandle**. This API returns the result synchronously.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ----------------------- | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle8) | Yes | Handle of the data network.|
**Return value**
| Type | Description |
| --------------------------------------------- | --------------------------------- |
| [NetCapabilities](#netcapabilities8) | Network capability information.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let netHandle = connection.getDefaultNetsSync();
let getNetCapabilitiesSync = connection.getNetCapabilitiesSync(netHandle);
```
## connection.isDefaultNetMetered<sup>9+</sup>
isDefaultNetMetered(callback: AsyncCallback\<boolean>): void
......@@ -814,6 +951,37 @@ connection.isDefaultNetMetered().then(function (data) {
})
```
## connection.isDefaultNetMeteredSync<sup>10+</sup>
isDefaultNetMeteredSync(): boolean
Checks whether the data traffic usage on the current network is metered. This API returns the result synchronously.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| ----------------- | ----------------------------------------------- |
| boolean | The value **true** indicates the data traffic usage is metered.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let isMetered = connection.isDefaultNetMeteredSync();
```
## connection.hasDefaultNet<sup>8+</sup>
hasDefaultNet(callback: AsyncCallback\<boolean>): void
......@@ -881,6 +1049,37 @@ connection.hasDefaultNet().then(function (data) {
})
```
## connection.hasDefaultNetSync<sup>10+</sup>
hasDefaultNetSync(): boolean
Checks whether the default data network is activated. This API returns the result synchronously.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| ----------------- | ----------------------------------------------- |
| boolean | The value **true** indicates the default data network is activated.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let isDefaultNet = connection.hasDefaultNetSync();
```
## connection.enableAirplaneMode<sup>8+</sup>
enableAirplaneMode(callback: AsyncCallback\<void>): void
......@@ -1349,7 +1548,7 @@ Registers a listener for **netAvailable** events.
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed to **netAvailable**.<br>**netAvailable**: event indicating that the data network is available.|
| type | string | Yes | Event type. This field has a fixed value of **netAvailable**.<br>**netAvailable**: event indicating that the data network is available.|
| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the network handle.|
**Example**
......@@ -1388,7 +1587,7 @@ Registers a listener for **netBlockStatusChange** events. This API uses an async
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed to **netBlockStatusChange**.<br>**netBlockStatusChange**: event indicating a change in the network blocking status.|
| type | string | Yes | Event type. This field has a fixed value of **netBlockStatusChange**.<br>**netBlockStatusChange**: event indicating a change in the network blocking status.|
| callback | Callback&lt;{&nbsp;netHandle:&nbsp;[NetHandle](#nethandle),&nbsp;blocked:&nbsp;boolean&nbsp;}&gt; | Yes | Callback used to return the network handle (**netHandle**) and network status (**blocked**).|
**Example**
......@@ -1415,7 +1614,7 @@ netCon.unregister(function (error) {
### on('netCapabilitiesChange')<sup>8+</sup>
on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void
on(type: 'netCapabilitiesChange', callback: Callback\<NetCapabilityInfo>): void
Registers a listener for **netCapabilitiesChange** events.
......@@ -1427,8 +1626,8 @@ Registers a listener for **netCapabilitiesChange** events.
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed to **netCapabilitiesChange**.<br>**netCapabilitiesChange**: event indicating that the network capabilities have changed.|
| callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).|
| type | string | Yes | Event type. This field has a fixed value of **netCapabilitiesChange**.<br>**netCapabilitiesChange**: event indicating that the network capabilities have changed.|
| callback | Callback<[NetCapabilityInfo](#netcapabilityinfo)> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).|
**Example**
......@@ -1467,7 +1666,7 @@ Registers a listener for **netConnectionPropertiesChange** events.
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed to **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.|
| type | string | Yes | Event type. This field has a fixed value of **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.|
| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the network handle (**netHandle**) and connection information (**connectionProperties**).|
**Example**
......@@ -1506,7 +1705,7 @@ Registers a listener for **netLost** events.
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed to **netLost**.<br>netLost: event indicating that the network is interrupted or normally disconnected.|
| type | string | Yes | Event type. This field has a fixed value of **netLost**.<br>netLost: event indicating that the network is interrupted or normally disconnected.|
| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the network handle (**netHandle**).|
**Example**
......@@ -1545,7 +1744,7 @@ Registers a listener for **netUnavailable** events.
| Name | Type | Mandatory| Description |
| -------- | --------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed to **netUnavailable**.<br>**netUnavailable**: event indicating that the network is unavailable.|
| type | string | Yes | Event type. This field has a fixed value of **netUnavailable**.<br>**netUnavailable**: event indicating that the network is unavailable.|
| callback | Callback\<void> | Yes | Callback used to return the result, which is empty.|
**Example**
......@@ -1950,6 +2149,17 @@ Provides an instance that bears data network capabilities.
| netCapabilities | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. |
| bearerPrivateIdentifier | string | No | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).|
## NetCapabilityInfo<sup>10+</sup>
Provides an instance that bears data network capabilities.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory | Description |
| ----------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network. |
| netCap | [NetCapabilities](#netcapabilities) | No | Network transmission capabilities and bearer types of the data network.|
## NetCapabilities<sup>8+</sup>
Defines the network capability set.
......
......@@ -63,7 +63,7 @@ let localServiceInfo = {
}]
}
mdns.addLocalService(context, localServiceInfo, function (error, data) {
mdns.addLocalService(context, localServiceInfo, (error: BusinessError, data: Data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
......@@ -72,14 +72,39 @@ mdns.addLocalService(context, localServiceInfo, function (error, data) {
Stage model:
```ts
// Construct a singleton object.
export class GlobalContext {
private constructor() {}
private static instance: GlobalContext;
private _objects = new Map<string, Object>();
public static getContext(): GlobalContext {
if (!GlobalContext.instance) {
GlobalContext.instance = new GlobalContext();
}
return GlobalContext.instance;
}
getObject(value: string): Object | undefined {
return this._objects.get(value);
}
setObject(key: string, objectClass: Object): void {
this._objects.set(key, objectClass);
}
}
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
import { GlobalContext } from '../GlobalContext';
class EntryAbility extends UIAbility {
value:number = 0;
onWindowStageCreate(windowStage){
globalThis.context = this.context;
GlobalContext.getContext().setObject("value", this.value);
}
}
let context = globalThis.context;
let context = GlobalContext.getContext().getObject("value");
let localServiceInfo = {
serviceType: "_print._tcp",
......@@ -94,7 +119,7 @@ let localServiceInfo = {
}]
}
mdns.addLocalService(context, localServiceInfo, function (error, data) {
mdns.addLocalService(context, localServiceInfo, (error: BusinessError, data: Data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
......@@ -157,7 +182,7 @@ let localServiceInfo = {
}]
}
mdns.addLocalService(context, localServiceInfo).then(function (data) {
mdns.addLocalService(context, localServiceInfo).then((data: Data) => {
console.log(JSON.stringify(data));
});
```
......@@ -167,12 +192,15 @@ Stage model:
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
// Construct a singleton object by referring to addLocalService.
import { GlobalContext } from '../GlobalContext';
class EntryAbility extends UIAbility {
value:number = 0;
onWindowStageCreate(windowStage){
globalThis.context = this.context;
GlobalContext.getContext().setObject("value", this.value);
}
}
let context = globalThis.context;
let context = GlobalContext.getContext().getObject("value");
let localServiceInfo = {
serviceType: "_print._tcp",
......@@ -187,7 +215,7 @@ let localServiceInfo = {
}]
}
mdns.addLocalService(context, localServiceInfo).then(function (data) {
mdns.addLocalService(context, localServiceInfo).then((data: Data) => {
console.log(JSON.stringify(data));
});
```
......@@ -244,7 +272,7 @@ let localServiceInfo = {
}]
}
mdns.removeLocalService(context, localServiceInfo, function (error, data) {
mdns.removeLocalService(context, localServiceInfo, (error: BusinessError, data: Data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
......@@ -255,12 +283,15 @@ Stage model:
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
// Construct a singleton object by referring to addLocalService.
import { GlobalContext } from '../GlobalContext';
class EntryAbility extends UIAbility {
value:number = 0;
onWindowStageCreate(windowStage){
globalThis.context = this.context;
GlobalContext.getContext().setObject("value", this.value);
}
}
let context = globalThis.context;
let context = GlobalContext.getContext().getObject("value");
let localServiceInfo = {
serviceType: "_print._tcp",
......@@ -275,7 +306,7 @@ let localServiceInfo = {
}]
}
mdns.removeLocalService(context, localServiceInfo, function (error, data) {
mdns.removeLocalService(context, localServiceInfo, (error: BusinessError, data: Data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
......@@ -338,7 +369,7 @@ let localServiceInfo = {
}]
}
mdns.removeLocalService(context, localServiceInfo).then(function (data) {
mdns.removeLocalService(context, localServiceInfo).then((data: Data) => {
console.log(JSON.stringify(data));
});
```
......@@ -348,12 +379,15 @@ Stage model:
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
// Construct a singleton object by referring to addLocalService.
import { GlobalContext } from '../GlobalContext';
class EntryAbility extends UIAbility {
value:number = 0;
onWindowStageCreate(windowStage){
globalThis.context = this.context;
GlobalContext.getContext().setObject("value", this.value);
}
}
let context = globalThis.context;
let context = GlobalContext.getContext().getObject("value");
let localServiceInfo = {
serviceType: "_print._tcp",
......@@ -368,7 +402,7 @@ let localServiceInfo = {
}]
}
mdns.removeLocalService(context, localServiceInfo).then(function (data) {
mdns.removeLocalService(context, localServiceInfo).then((data: Data) => {
console.log(JSON.stringify(data));
});
```
......@@ -418,12 +452,15 @@ Stage model:
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
// Construct a singleton object by referring to addLocalService.
import { GlobalContext } from '../GlobalContext';
class EntryAbility extends UIAbility {
value:number = 0;
onWindowStageCreate(windowStage){
globalThis.context = this.context;
GlobalContext.getContext().setObject("value", this.value);
}
}
let context = globalThis.context;
let context = GlobalContext.getContext().getObject("value");
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
......@@ -481,7 +518,7 @@ let localServiceInfo = {
}]
}
mdns.resolveLocalService(context, localServiceInfo, function (error, data) {
mdns.resolveLocalService(context, localServiceInfo, (error: BusinessError, data: Data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
......@@ -492,12 +529,15 @@ Stage model:
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
// Construct a singleton object by referring to addLocalService.
import { GlobalContext } from '../GlobalContext';
class EntryAbility extends UIAbility {
value:number = 0;
onWindowStageCreate(windowStage){
globalThis.context = this.context;
GlobalContext.getContext().setObject("value", this.value);
}
}
let context = globalThis.context;
let context = GlobalContext.getContext().getObject("value");
let localServiceInfo = {
serviceType: "_print._tcp",
......@@ -512,7 +552,7 @@ let localServiceInfo = {
}]
}
mdns.resolveLocalService(context, localServiceInfo, function (error, data) {
mdns.resolveLocalService(context, localServiceInfo, (error: BusinessError, data: Data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
......@@ -575,7 +615,7 @@ let localServiceInfo = {
}]
}
mdns.resolveLocalService(context, localServiceInfo).then(function (data) {
mdns.resolveLocalService(context, localServiceInfo).then((data: Data) => {
console.log(JSON.stringify(data));
});
```
......@@ -585,12 +625,15 @@ Stage model:
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
// Construct a singleton object by referring to addLocalService.
import { GlobalContext } from '../GlobalContext';
class EntryAbility extends UIAbility {
value:number = 0;
onWindowStageCreate(windowStage){
globalThis.context = this.context;
GlobalContext.getContext().setObject("value", this.value);
}
}
let context = globalThis.context;
let context = GlobalContext.getContext().getObject("value");
let localServiceInfo = {
serviceType: "_print._tcp",
......@@ -605,7 +648,7 @@ let localServiceInfo = {
}]
}
mdns.resolveLocalService(context, localServiceInfo).then(function (data) {
mdns.resolveLocalService(context, localServiceInfo).then((data: Data) => {
console.log(JSON.stringify(data));
});
```
......@@ -639,12 +682,15 @@ Stage model:
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
// Construct a singleton object by referring to addLocalService.
import { GlobalContext } from '../GlobalContext';
class EntryAbility extends UIAbility {
value:number = 0;
onWindowStageCreate(windowStage){
globalThis.context = this.context;
GlobalContext.getContext().setObject("value", this.value);
}
}
let context = globalThis.context;
let context = GlobalContext.getContext().getObject("value");
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS();
......@@ -676,12 +722,15 @@ Stage model:
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
// Construct a singleton object by referring to addLocalService.
import { GlobalContext } from '../GlobalContext';
class EntryAbility extends UIAbility {
value:number = 0;
onWindowStageCreate(windowStage){
globalThis.context = this.context;
GlobalContext.getContext().setObject("value", this.value);
}
}
let context = globalThis.context;
let context = GlobalContext.getContext().getObject("value");
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.stopSearchingMDNS();
......@@ -706,18 +755,53 @@ Enables listening for **discoveryStart** events.
```js
// See mdns.createDiscoveryService.
let context = globalThis.context;
let context = GlobalContext.getContext().getObject("value");
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS();
discoveryService.on('discoveryStart', (data) => {
discoveryService.on('discoveryStart', (data: Data) => {
console.log(JSON.stringify(data));
});
discoveryService.stopSearchingMDNS();
```
### off('discoveryStart')<sup>10+</sup>
off(type: 'discoveryStart', callback?: Callback<{ serviceInfo: LocalServiceInfo, errorCode?: MdnsError }>): void
Disables listening for **discoveryStart** events.
**System capability**: SystemCapability.Communication.NetManager.MDNS
**Parameters**
| Name | Type | Mandatory| Description |
|-------------|--------------|-----------|-----------------------------------------------------|
| type | string | Yes |Event type. This field has a fixed value of **discoveryStart**.<br>**discoveryStart**: event of starting discovery of mDNS services on the LAN.|
| callback | Callback<{serviceInfo: [LocalServiceInfo](#localserviceinfo), errorCode?: [MdnsError](#mdnserror)}> | No | Callback used to return the mDNS service and error information. |
**Example**
```js
// See mdns.createDiscoveryService.
let context = GlobalContext.getContext().getObject("value");
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS();
discoveryService.on('discoveryStart', (data: Data) => {
console.log(JSON.stringify(data));
});
discoveryService.stopSearchingMDNS();
discoveryService.off('discoveryStart', (data: Data) => {
console.log(JSON.stringify(data));
});
```
### on('discoveryStop')<sup>10+</sup>
on(type: 'discoveryStop', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void
......@@ -737,18 +821,53 @@ Enables listening for **discoveryStop** events.
```js
// See mdns.createDiscoveryService.
let context = globalThis.context;
let context = GlobalContext.getContext().getObject("value");
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS();
discoveryService.on('discoveryStop', (data) => {
discoveryService.on('discoveryStop', (data: Data) => {
console.log(JSON.stringify(data));
});
discoveryService.stopSearchingMDNS();
```
### off('discoveryStop')<sup>10+</sup>
off(type: 'discoveryStop', callback?: Callback<{ serviceInfo: LocalServiceInfo, errorCode?: MdnsError }>): void
Disables listening for **discoveryStop** events.
**System capability**: SystemCapability.Communication.NetManager.MDNS
**Parameters**
| Name | Type | Mandatory| Description |
|-------------|--------------|-----------|-----------------------------------------------------|
| type | string | Yes |Event type. This field has a fixed value of **discoveryStop**.<br>**discoveryStop**: event of stopping discovery of mDNS services on the LAN.|
| callback | Callback<{serviceInfo: [LocalServiceInfo](#localserviceinfo), errorCode?: [MdnsError](#mdnserror)}> | No | Callback used to return the mDNS service and error information. |
**Example**
```js
// See mdns.createDiscoveryService.
let context = GlobalContext.getContext().getObject("value");
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS();
discoveryService.on('discoveryStop', (data: Data) => {
console.log(JSON.stringify(data));
});
discoveryService.stopSearchingMDNS();
discoveryService.off('discoveryStop', (data: Data) => {
console.log(JSON.stringify(data));
});
```
### on('serviceFound')<sup>10+</sup>
on(type: 'serviceFound', callback: Callback\<LocalServiceInfo>): void
......@@ -768,16 +887,51 @@ Enables listening for **serviceFound** events.
```js
// See mdns.createDiscoveryService.
let context = globalThis.context;
let context = GlobalContext.getContext().getObject("value");
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS();
discoveryService.on('serviceFound', (data: Data) => {
console.log(JSON.stringify(data));
});
discoveryService.stopSearchingMDNS();
```
### off('serviceFound')<sup>10+</sup>
off(type: 'serviceFound', callback?: Callback\<LocalServiceInfo>): void
Disables listening for **serviceFound** events.
**System capability**: SystemCapability.Communication.NetManager.MDNS
**Parameters**
| Name | Type | Mandatory| Description |
|-------------|--------------|-----------|-----------------------------------------------------|
| type | string | Yes |Event type. This field has a fixed value of **serviceFound**.<br>**serviceFound**: event indicating an mDNS service is found.|
| callback | Callback<[LocalServiceInfo](#localserviceinfo)> | No | mDNS service information. |
**Example**
```js
// See mdns.createDiscoveryService.
let context = GlobalContext.getContext().getObject("value");
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS();
discoveryService.on('serviceFound', (data) => {
discoveryService.on('serviceFound', (data: Data) => {
console.log(JSON.stringify(data));
});
discoveryService.stopSearchingMDNS();
discoveryService.off('serviceFound', (data: Data) => {
console.log(JSON.stringify(data));
});
```
### on('serviceLost')<sup>10+</sup>
......@@ -799,16 +953,51 @@ Enables listening for **serviceLost** events.
```js
// See mdns.createDiscoveryService.
let context = globalThis.context;
let context = GlobalContext.getContext().getObject("value");
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS();
discoveryService.on('serviceLost', (data: Data) => {
console.log(JSON.stringify(data));
});
discoveryService.stopSearchingMDNS();
```
### off('serviceLost')<sup>10+</sup>
off(type: 'serviceLost', callback?: Callback\<LocalServiceInfo>): void
Disables listening for **serviceLost** events.
**System capability**: SystemCapability.Communication.NetManager.MDNS
**Parameters**
| Name | Type | Mandatory| Description |
|-------------|--------------|-----------|-----------------------------------------------------|
| type | string | Yes |Event type. This field has a fixed value of **serviceLost**.<br>serviceLost: event indicating that an mDNS service is removed.|
| callback | Callback<[LocalServiceInfo](#localserviceinfo)> | No | mDNS service information. |
**Example**
```js
// See mdns.createDiscoveryService.
let context = GlobalContext.getContext().getObject("value");
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS();
discoveryService.on('serviceLost', (data) => {
discoveryService.on('serviceLost', (data: Data) => {
console.log(JSON.stringify(data));
});
discoveryService.stopSearchingMDNS();
discoveryService.off('serviceLost', (data: Data) => {
console.log(JSON.stringify(data));
});
```
## LocalServiceInfo<sup>10+</sup>
......
......@@ -106,7 +106,10 @@ Obtains the **ResourceManager** object of this application. This API uses a prom
**Example**
```js
resourceManager.getResourceManager().then(mgr => {
import resourceManager from '@ohos.resourceManager';
import { BusinessError } from '@ohos.base';
resourceManager.getResourceManager().then((mgr: resourceManager.ResourceManager) => {
mgr.getStringValue(0x1000000, (error, value) => {
if (error != null) {
console.log("error is " + error);
......@@ -114,7 +117,7 @@ Obtains the **ResourceManager** object of this application. This API uses a prom
let str = value;
}
});
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("error is " + error);
});
```
......@@ -145,8 +148,11 @@ Obtains the **ResourceManager** object of an application based on the specified
**Example**
```js
resourceManager.getResourceManager("com.example.myapplication").then(mgr => {
}).catch(error => {
import resourceManager from '@ohos.resourceManager';
import { BusinessError } from '@ohos.base';
resourceManager.getResourceManager("com.example.myapplication").then((mgr: resourceManager.ResourceManager) => {
}).catch((error: BusinessError) => {
});
```
......@@ -175,12 +181,13 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```js
import resourceManager from '@ohos.resourceManager';
import { BusinessError } from '@ohos.base';
try {
let systemResourceManager = resourceManager.getSystemResourceManager();
systemResourceManager.getStringValue($r('sys.string.ohos_lab_vibrate').id).then(value => {
systemResourceManager.getStringValue($r('sys.string.ohos_lab_vibrate').id).then((value: string) => {
let str = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("systemResourceManager getStringValue promise error is " + error);
});
} catch (error) {
......@@ -414,7 +421,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.string.test').id
......@@ -462,7 +471,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.string.test').id
......@@ -626,10 +637,12 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getStringValue($r('app.string.test').id).then(value => {
this.context.resourceManager.getStringValue($r('app.string.test').id).then((value: string) => {
let str = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getStringValue promise error is " + error);
});
} catch (error) {
......@@ -666,7 +679,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.string.test').id
......@@ -718,15 +733,18 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
import { BusinessError } from '@ohos.base';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.string.test').id
};
try {
this.context.resourceManager.getStringValue(resource).then(value => {
this.context.resourceManager.getStringValue(resource).then((value: string) => {
let str = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getStringValue promise error is " + error);
});
} catch (error) {
......@@ -806,10 +824,12 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getStringByName("test").then(value => {
this.context.resourceManager.getStringByName("test").then((value: string) => {
let str = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getStringByName promise error is " + error);
});
} catch (error) {
......@@ -890,7 +910,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.strarray.test').id
......@@ -902,6 +924,45 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
}
```
### getStringArrayByNameSync<sup>10+</sup>
getStringArrayByNameSync(resName: string): Array&lt;string&gt;
Obtains the string array corresponding to the specified resource name. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| --------------------- | ----------- |
| Array&lt;string&gt; | String array corresponding to the specified resource name.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getStringArrayByNameSync("test");
} catch (error) {
console.error(`getStringArrayByNameSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getStringArrayValue<sup>9+</sup>
getStringArrayValue(resId: number, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void
......@@ -974,10 +1035,12 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id).then(value => {
this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id).then((value: Array<string>) => {
let strArray = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getStringArrayValue promise error is " + error);
});
} catch (error) {
......@@ -1014,7 +1077,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.strarray.test').id
......@@ -1066,15 +1131,18 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
import { BusinessError } from '@ohos.base';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.strarray.test').id
};
try {
this.context.resourceManager.getStringArrayValue(resource).then(value => {
this.context.resourceManager.getStringArrayValue(resource).then((value: Array<string>) => {
let strArray = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getStringArray promise error is " + error);
});
} catch (error) {
......@@ -1154,10 +1222,12 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getStringArrayByName("test").then(value => {
this.context.resourceManager.getStringArrayByName("test").then((value: Array<string>) => {
let strArray = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getStringArrayByName promise error is " + error);
});
} catch (error) {
......@@ -1240,7 +1310,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.plural.test').id
......@@ -1252,6 +1324,46 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
}
```
### getPluralStringByNameSync<sup>10+</sup>
getPluralStringByNameSync(resName: string, num: number): string
Obtains the singular-plural string corresponding to the specified resource name based on the specified number. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resName | string | Yes | Resource name.|
| num | number | Yes | Number. |
**Return value**
| Type | Description |
| --------------------- | ----------- |
| string | Singular-plural string corresponding to the specified resource name.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getPluralStringByNameSync("test", 1);
} catch (error) {
console.error(`getPluralStringByNameSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getPluralStringValue<sup>9+</sup>
getPluralStringValue(resId: number, num: number, callback: AsyncCallback&lt;string&gt;): void
......@@ -1326,10 +1438,12 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1).then(value => {
this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1).then((value: string) => {
let str = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getPluralStringValue promise error is " + error);
});
} catch (error) {
......@@ -1367,7 +1481,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.plural.test').id
......@@ -1420,15 +1536,18 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
import { BusinessError } from '@ohos.base';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.plural.test').id
};
try {
this.context.resourceManager.getPluralStringValue(resource, 1).then(value => {
this.context.resourceManager.getPluralStringValue(resource, 1).then((value: string) => {
let str = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getPluralStringValue promise error is " + error);
});
} catch (error) {
......@@ -1510,10 +1629,12 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getPluralStringByName("test", 1).then(value => {
this.context.resourceManager.getPluralStringByName("test", 1).then((value: string) => {
let str = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getPluralStringByName promise error is " + error);
});
} catch (error) {
......@@ -1525,7 +1646,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
getMediaContentSync(resId: number, density?: number): Uint8Array
Obtains the content of the media file (with the default or specified screen density) corresponding to the specified resource ID. This API returns the result synchronously.
Obtains the media file content (with the default or specified screen density) corresponding to the specified resource ID. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -1540,7 +1661,7 @@ Obtains the content of the media file (with the default or specified screen dens
| Type | Description |
| -------- | ----------- |
| Uint8Array | Content of the media file corresponding to the specified resource ID.|
| Uint8Array | Media file content corresponding to the specified resource ID.|
**Error codes**
......@@ -1570,7 +1691,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
getMediaContentSync(resource: Resource, density?: number): Uint8Array
Obtains the content of the media file (with the default or specified screen density) corresponding to the specified resource object. This API returns the result synchronously.
Obtains the media file content (with the default or specified screen density) corresponding to the specified resource object. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -1587,7 +1708,7 @@ Obtains the content of the media file (with the default or specified screen dens
| Type | Description |
| --------------------- | ----------- |
| Uint8Array | Content of the media file corresponding to the specified resource object|
| Uint8Array | Media file content corresponding to the specified resource object|
**Error codes**
......@@ -1600,7 +1721,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
......@@ -1618,11 +1741,56 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
}
```
### getMediaByNameSync<sup>10+</sup>
getMediaByNameSync(resName: string, density?: number): Uint8Array
Obtains the media file content (with the default or specified screen density) corresponding to the specified resource name. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resName | string | Yes | Resource name.|
| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.|
**Return value**
| Type | Description |
| --------------------- | ----------- |
| Uint8Array | Media file content corresponding to the resource name.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
**Example**
```ts
try {
this.context.resourceManager.getMediaByNameSync("test"); // Default screen density
} catch (error) {
console.error(`getMediaByNameSync failed, error code: ${error.code}, message: ${error.message}.`);
}
try {
this.context.resourceManager.getMediaByNameSync("test", 120); // Specified screen density
} catch (error) {
console.error(`getMediaByNameSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContent<sup>9+</sup>
getMediaContent(resId: number, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
Obtains the media file content corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -1661,7 +1829,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
getMediaContent(resId: number, density: number, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the content of the media file (with the specified screen density) corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
Obtains the media file content (with the specified screen density) corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -1701,7 +1869,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
getMediaContent(resId: number): Promise&lt;Uint8Array&gt;
Obtains the content of the media file corresponding to the specified resource ID. This API uses a promise to return the result.
Obtains the media file content corresponding to the specified resource ID. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -1728,10 +1896,12 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getMediaContent($r('app.media.test').id).then(value => {
this.context.resourceManager.getMediaContent($r('app.media.test').id).then((value: Uint8Array) => {
let media = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getMediaContent promise error is " + error);
});
} catch (error) {
......@@ -1743,7 +1913,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
getMediaContent(resId: number, density: number): Promise&lt;Uint8Array&gt;
Obtains the content of the media file (with the specified screen density) corresponding to the specified resource ID. This API uses a promise to return the result.
Obtains the media file content (with the specified screen density) corresponding to the specified resource ID. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -1771,10 +1941,12 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getMediaContent($r('app.media.test').id, 120).then(value => {
this.context.resourceManager.getMediaContent($r('app.media.test').id, 120).then((value: Uint8Array) => {
let media = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
......@@ -1786,7 +1958,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
getMediaContent(resource: Resource, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the content of the media file corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
Obtains the media file content corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -1810,7 +1982,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
......@@ -1832,7 +2006,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
getMediaContent(resource: Resource, density: number, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the content of the media file (with the specified screen density) corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
Obtains the media file content (with the specified screen density) corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -1857,7 +2031,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
......@@ -1879,7 +2055,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
getMediaContent(resource: Resource): Promise&lt;Uint8Array&gt;
Obtains the content of the media file corresponding to the specified resource object. This API uses a promise to return the result.
Obtains the media file content corresponding to the specified resource object. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -1908,15 +2084,18 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
import { BusinessError } from '@ohos.base';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
};
try {
this.context.resourceManager.getMediaContent(resource).then(value => {
this.context.resourceManager.getMediaContent(resource).then((value: Uint8Array) => {
let media = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getMediaContent promise error is " + error);
});
} catch (error) {
......@@ -1928,7 +2107,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
getMediaContent(resource: Resource, density: number): Promise&lt;Uint8Array&gt;
Obtains the content of the media file (with the specified screen density) corresponding to the specified resource object. This API uses a promise to return the result.
Obtains the media file content (with the specified screen density) corresponding to the specified resource object. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -1958,15 +2137,18 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
import { BusinessError } from '@ohos.base';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
};
try {
this.context.resourceManager.getMediaContent(resource, 120).then(value => {
this.context.resourceManager.getMediaContent(resource, 120).then((value: Uint8Array) => {
let media = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
......@@ -1978,7 +2160,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
getMediaByName(resName: string, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
Obtains the media file content corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -2017,7 +2199,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
getMediaByName(resName: string, density: number, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the content of the media file (with the specified screen density) corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
Obtains the media file content (with the specified screen density) corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -2057,7 +2239,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
getMediaByName(resName: string): Promise&lt;Uint8Array&gt;
Obtains the content of the media file corresponding to the specified resource name. This API uses a promise to return the result.
Obtains the media file content corresponding to the specified resource name. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -2084,10 +2266,12 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getMediaByName("test").then(value => {
this.context.resourceManager.getMediaByName("test").then((value: Uint8Array) => {
let media = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getMediaByName promise error is " + error);
});
} catch (error) {
......@@ -2099,7 +2283,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
getMediaByName(resName: string, density: number): Promise&lt;Uint8Array&gt;
Obtains the content of the media file (with the specified screen density) corresponding to the specified resource name. This API uses a promise to return the result.
Obtains the media file content (with the specified screen density) corresponding to the specified resource name. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -2127,10 +2311,12 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getMediaByName("test", 120).then(value => {
this.context.resourceManager.getMediaByName("test", 120).then((value: Uint8Array) => {
let media = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
......@@ -2217,7 +2403,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
......@@ -2235,6 +2423,51 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
}
```
### getMediaBase64ByNameSync<sup>10+</sup>
getMediaBase64ByNameSync(resName: string, density?: number): string
Obtains the Base64 code of the image (with the default or specified screen density) corresponding to the specified resource name.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resName | string | Yes | Resource name.|
| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.|
**Return value**
| Type | Description |
| --------------------- | ----------- |
| string | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
**Example**
```ts
try {
this.context.resourceManager.getMediaBase64ByNameSync("test"); // Default screen density
} catch (error) {
console.error(`getMediaBase64ByNameSync failed, error code: ${error.code}, message: ${error.message}.`);
}
try {
this.context.resourceManager.getMediaBase64ByNameSync("test", 120); // Specified screen density
} catch (error) {
console.error(`getMediaBase64ByNameSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContentBase64<sup>9+</sup>
getMediaContentBase64(resId: number, callback: AsyncCallback&lt;string&gt;): void
......@@ -2345,10 +2578,12 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getMediaContentBase64($r('app.media.test').id).then(value => {
this.context.resourceManager.getMediaContentBase64($r('app.media.test').id).then((value: string) => {
let media = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getMediaContentBase64 promise error is " + error);
});
} catch (error) {
......@@ -2388,10 +2623,12 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120).then(value => {
this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120).then((value: string) => {
let media = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
......@@ -2427,7 +2664,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
......@@ -2474,7 +2713,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
......@@ -2525,15 +2766,18 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
import { BusinessError } from '@ohos.base';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
};
try {
this.context.resourceManager.getMediaContentBase64(resource).then(value => {
this.context.resourceManager.getMediaContentBase64(resource).then((value: string) => {
let media = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getMediaContentBase64 promise error is " + error);
});
} catch (error) {
......@@ -2575,15 +2819,18 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
import { BusinessError } from '@ohos.base';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
};
try {
this.context.resourceManager.getMediaContentBase64(resource, 120).then(value => {
this.context.resourceManager.getMediaContentBase64(resource, 120).then((value: string) => {
let media = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
......@@ -2701,10 +2948,12 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getMediaBase64ByName("test").then(value => {
this.context.resourceManager.getMediaBase64ByName("test").then((value: string) => {
let media = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getMediaBase64ByName promise error is " + error);
});
} catch (error) {
......@@ -2744,10 +2993,12 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getMediaBase64ByName("test", 120).then(value => {
this.context.resourceManager.getMediaBase64ByName("test", 120).then((value: string) => {
let media = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
......@@ -2833,7 +3084,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.icon').id
......@@ -2966,7 +3219,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.boolean.boolean_test').id
......@@ -3096,7 +3351,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.integer.integer_test').id
......@@ -3226,7 +3483,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.color.test').id
......@@ -3349,10 +3608,12 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getColor($r('app.color.test').id).then(value => {
this.context.resourceManager.getColor($r('app.color.test').id).then((value: number) => {
let str = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getColor promise error is " + error);
});
} catch (error) {
......@@ -3389,7 +3650,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.color.test').id
......@@ -3441,15 +3704,18 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
import resourceManager from '@ohos.resourceManager';
import { BusinessError } from '@ohos.base';
let resource: resourceManager.Resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.color.test').id
};
try {
this.context.resourceManager.getColor(resource).then(value => {
this.context.resourceManager.getColor(resource).then((value: number) => {
let str = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getColor promise error is " + error);
});
} catch (error) {
......@@ -3529,10 +3795,12 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getColorByName("test").then(value => {
this.context.resourceManager.getColorByName("test").then((value: number) => {
let string = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getColorByName promise error is " + error);
});
} catch (error) {
......@@ -3603,7 +3871,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
try {
this.context.resourceManager.getRawFileContent("test.xml", (error, value) => {
this.context.resourceManager.getRawFileContent("test.txt", (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
......@@ -3645,10 +3913,12 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getRawFileContent("test.xml").then(value => {
this.context.resourceManager.getRawFileContent("test.txt").then((value: Uint8Array) => {
let rawFile = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getRawFileContent promise error is " + error);
});
} catch (error) {
......@@ -3761,10 +4031,12 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try { // Passing "" means to obtain the list of files in the root directory of the raw file.
this.context.resourceManager.getRawFileList("").then(value => {
this.context.resourceManager.getRawFileList("").then((value: Array<string>) => {
let rawFile = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.error(`promise getRawFileList failed, error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
......@@ -3835,7 +4107,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
try {
this.context.resourceManager.getRawFd("test.xml", (error, value) => {
this.context.resourceManager.getRawFd("test.txt", (error, value) => {
if (error != null) {
console.log(`callback getRawFd failed error code: ${error.code}, message: ${error.message}.`);
} else {
......@@ -3879,12 +4151,14 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getRawFd("test.xml").then(value => {
this.context.resourceManager.getRawFd("test.txt").then((value: resourceManager.RawFileDescriptor) => {
let fd = value.fd;
let offset = value.offset;
let length = value.length;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log(`promise getRawFd error error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
......@@ -3949,7 +4223,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
try {
this.context.resourceManager.closeRawFd("test.xml", (error, value) => {
this.context.resourceManager.closeRawFd("test.txt", (error, value) => {
if (error != null) {
console.log("error is " + error);
}
......@@ -3990,16 +4264,37 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
try {
this.context.resourceManager.closeRawFd("test.xml").then(value => {
let result = value;
}).catch(error => {
console.log("closeRawFd promise error is " + error);
});
this.context.resourceManager.closeRawFd("test.txt");
} catch (error) {
console.error(`promise closeRawFd failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getConfigurationSync
getConfigurationSync(): Configuration
Obtains the device configuration. This API return the results synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Return value**
| Type | Description |
| ---------------------------------------- | ---------------- |
| Promise&lt;[Configuration](#configuration)&gt; | Promise used to return the result.|
**Example**
```ts
try {
let value = this.context.resourceManager.getConfigurationSync();
let direction = value.direction;
let locale = value.locale;
} catch (error) {
console.error("getConfigurationSync error is " + error);
}
```
### getConfiguration
getConfiguration(callback: AsyncCallback&lt;Configuration&gt;): void
......@@ -4046,11 +4341,13 @@ Obtains the device configuration. This API uses a promise to return the result.
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getConfiguration().then(value => {
this.context.resourceManager.getConfiguration().then((value: resourceManager.Configuration) => {
let direction = value.direction;
let locale = value.locale;
}).catch(error => {
}).catch((error: BusinessError) => {
console.error("getConfiguration promise error is " + error);
});
} catch (error) {
......@@ -4058,6 +4355,31 @@ Obtains the device configuration. This API uses a promise to return the result.
}
```
### getDeviceCapabilitySync
getDeviceCapabilitySync(): DeviceCapability
Obtains the device capability. This API return the results synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------- |
| DeviceCapability | Promise used to return the result.|
**Example**
```ts
try {
let value = this.context.resourceManager.getDeviceCapabilitySync();
let screenDensity = value.screenDensity;
let deviceType = value.deviceType;
} catch (error) {
console.error("getDeviceCapabilitySync error is " + error);
}
```
### getDeviceCapability
getDeviceCapability(callback: AsyncCallback&lt;DeviceCapability&gt;): void
......@@ -4104,11 +4426,13 @@ Obtains the device capability. This API uses a promise to return the result.
**Example**
```ts
import { BusinessError } from '@ohos.base';
try {
this.context.resourceManager.getDeviceCapability().then(value => {
this.context.resourceManager.getDeviceCapability().then((value: resourceManager.DeviceCapability) => {
let screenDensity = value.screenDensity;
let deviceType = value.deviceType;
}).catch(error => {
}).catch((error: BusinessError) => {
console.error("getDeviceCapability promise error is " + error);
});
} catch (error) {
......@@ -4191,7 +4515,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
```ts
let path = getContext().bundleCodeDir + "/library1-default-signed.hsp";
try {
this.resmgr.removeResource(path);
this.context.resourceManager.removeResource(path);
} catch (error) {
console.error(`removeResource failed, error code: ${error.code}, message: ${error.message}.`);
}
......@@ -4252,10 +4576,12 @@ This API is deprecated since API version 9. You are advised to use [getStringVal
**Example**
```ts
import { BusinessError } from '@ohos.base';
resourceManager.getResourceManager((error, mgr) => {
mgr.getString($r('app.string.test').id).then(value => {
mgr.getString($r('app.string.test').id).then((value: string) => {
let str = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getstring promise error is " + error);
});
});
......@@ -4317,10 +4643,12 @@ This API is deprecated since API version 9. You are advised to use [getStringArr
**Example**
```ts
import { BusinessError } from '@ohos.base';
resourceManager.getResourceManager((error, mgr) => {
mgr.getStringArray($r('app.strarray.test').id).then(value => {
mgr.getStringArray($r('app.strarray.test').id).then((value: Array<string>) => {
let strArray = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getStringArray promise error is " + error);
});
});
......@@ -4331,7 +4659,7 @@ This API is deprecated since API version 9. You are advised to use [getStringArr
getMedia(resId: number, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
Obtains the media file content corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent9) instead.
......@@ -4362,7 +4690,7 @@ This API is deprecated since API version 9. You are advised to use [getMediaCont
getMedia(resId: number): Promise&lt;Uint8Array&gt;
Obtains the content of the media file corresponding to the specified resource ID. This API uses a promise to return the result.
Obtains the media file content corresponding to the specified resource ID. This API uses a promise to return the result.
This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent9-1) instead.
......@@ -4382,10 +4710,12 @@ This API is deprecated since API version 9. You are advised to use [getMediaCont
**Example**
```ts
import { BusinessError } from '@ohos.base';
resourceManager.getResourceManager((error, mgr) => {
mgr.getMedia($r('app.media.test').id).then(value => {
mgr.getMedia($r('app.media.test').id).then((value: Uint8Array) => {
let media = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getMedia promise error is " + error);
});
});
......@@ -4447,10 +4777,12 @@ This API is deprecated since API version 9. You are advised to use [getMediaCont
**Example**
```ts
import { BusinessError } from '@ohos.base';
resourceManager.getResourceManager((error, mgr) => {
mgr.getMediaBase64($r('app.media.test').id).then(value => {
mgr.getMediaBase64($r('app.media.test').id).then((value: string) => {
let media = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getMediaBase64 promise error is " + error);
});
});
......@@ -4482,10 +4814,12 @@ This API is deprecated since API version 9. You are advised to use [getPluralStr
**Example**
```ts
import { BusinessError } from '@ohos.base';
resourceManager.getResourceManager((error, mgr) => {
mgr.getPluralString($r("app.plural.test").id, 1).then(value => {
mgr.getPluralString($r("app.plural.test").id, 1).then((value: string) => {
let str = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getPluralString promise error is " + error);
});
});
......@@ -4544,7 +4878,7 @@ This API is deprecated since API version 9. You are advised to use [getRawFileCo
**Example**
```ts
resourceManager.getResourceManager((error, mgr) => {
mgr.getRawFile("test.xml", (error, value) => {
mgr.getRawFile("test.txt", (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
......@@ -4579,10 +4913,12 @@ This API is deprecated since API version 9. You are advised to use [getRawFileCo
**Example**
```ts
import { BusinessError } from '@ohos.base';
resourceManager.getResourceManager((error, mgr) => {
mgr.getRawFile("test.xml").then(value => {
mgr.getRawFile("test.txt").then((value: Uint8Array) => {
let rawFile = value;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getRawFile promise error is " + error);
});
});
......@@ -4609,7 +4945,7 @@ This API is deprecated since API version 9. You are advised to use [getRawFd](#g
**Example**
```ts
resourceManager.getResourceManager((error, mgr) => {
mgr.getRawFileDescriptor("test.xml", (error, value) => {
mgr.getRawFileDescriptor("test.txt", (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
......@@ -4645,12 +4981,14 @@ This API is deprecated since API version 9. You are advised to use [getRawFd](#g
**Example**
```ts
import { BusinessError } from '@ohos.base';
resourceManager.getResourceManager((error, mgr) => {
mgr.getRawFileDescriptor("test.xml").then(value => {
mgr.getRawFileDescriptor("test.txt").then((value: resourceManager.RawFileDescriptor) => {
let fd = value.fd;
let offset = value.offset;
let length = value.length;
}).catch(error => {
}).catch((error: BusinessError) => {
console.log("getRawFileDescriptor promise error is " + error);
});
});
......@@ -4676,7 +5014,7 @@ This API is deprecated since API version 9. You are advised to use [closeRawFd](
**Example**
```ts
resourceManager.getResourceManager((error, mgr) => {
mgr.closeRawFileDescriptor("test.xml", (error, value) => {
mgr.closeRawFileDescriptor("test.txt", (error, value) => {
if (error != null) {
console.log("error is " + error);
}
......@@ -4709,10 +5047,6 @@ This API is deprecated since API version 9. You are advised to use [closeRawFd](
**Example**
```ts
resourceManager.getResourceManager((error, mgr) => {
mgr.closeRawFileDescriptor("test.xml").then(value => {
let result = value;
}).catch(error => {
console.log("closeRawFileDescriptor promise error is " + error);
});
mgr.closeRawFileDescriptor("test.txt");
});
```
# # @ohos.net.socket (Socket Connection)
# @ohos.net.socket (Socket Connection)
The **socket** module implements data transfer over TCP, UDP, Web, and TLS socket connections.
......@@ -2515,7 +2515,7 @@ tcpServer.on('connect', function(client) {
### off('close')<sup>10+</sup>
on(type: 'close', callback: Callback\<void\>): void
off(type: 'close', callback?: Callback\<void\>): void
Unsubscribes from **close** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result.
......@@ -5708,7 +5708,7 @@ tlsServer.on('connect', function(client) {
### off('close')<sup>10+</sup>
on(type: 'close', callback: Callback\<void\>): void
off(type: 'close', callback?: Callback\<void\>): void
Unsubscribes from **close** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result.
......
# @ohos.update (Update)
The **update** module applies to updates throughout the entire system, including built-in resources and preset applications, but not third-party applications.
The **update** module implements update of the entire system, including built-in resources and preset applications, but not third-party applications.
There are two types of updates: SD card update and over the air (OTA) update.
Two upate modes, namely, SD card update and OTA (over the air) update.
- The SD card update depends on the update packages and SD cards.
- The OTA update depends on the server deployed by the device manufacturer for managing update packages. The OTA server IP address is passed by the caller. The request interface is fixed and developed by the device manufacturer.
> **NOTE**
......@@ -31,7 +32,7 @@ Obtains an **OnlineUpdater** object.
| Name | Type | Mandatory | Description |
| ----------- | --------------------------- | ---- | ------ |
| upgradeInfo | [UpgradeInfo](#upgradeinfo) | Yes | **UpgradeInfo** object.|
| upgradeInfo | [UpgradeInfo](#upgradeinfo) | Yes | **OnlineUpdater** object information.|
**Return value**
......@@ -45,13 +46,13 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
try {
const upgradeInfo = {
const upgradeInfo: update.UpgradeInfo = {
upgradeApp: "com.ohos.ota.updateclient",
businessType: {
vendor: update.BusinessVendor.PUBLIC,
......@@ -59,9 +60,9 @@ try {
}
};
let updater = update.getOnlineUpdater(upgradeInfo);
} catch(error) {
} catch(error) {
console.error(`Fail to get updater error: ${error}`);
}
}
```
## update.getRestorer
......@@ -85,7 +86,7 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
......@@ -117,7 +118,7 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
......@@ -139,7 +140,7 @@ Checks whether a new version is available. This API uses an asynchronous callbac
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -153,14 +154,14 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
updater.checkNewVersion((err, result) => {
updater.checkNewVersion((err: BusinessError, result: update.CheckResult) => {
console.log(`checkNewVersion isExistNewVersion ${result?.isExistNewVersion}`);
});
});
```
### checkNewVersion
......@@ -171,7 +172,7 @@ Checks whether a new version is available. This API uses a promise to return the
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Return value**
......@@ -185,18 +186,20 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
updater.checkNewVersion().then(result => {
updater.checkNewVersion()
.then((result: update.CheckResult) => {
console.log(`checkNewVersion isExistNewVersion: ${result.isExistNewVersion}`);
// Version digest information
console.log(`checkNewVersion versionDigestInfo: ${result.newVersionInfo.versionDigestInfo.versionDigest}`);
}).catch(err => {
})
.catch((err: BusinessError)=>{
console.log(`checkNewVersion promise error ${JSON.stringify(err)}`);
});
})
```
### getNewVersionInfo
......@@ -207,7 +210,7 @@ Obtains information about the new version. This API uses an asynchronous callbac
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -221,12 +224,12 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
updater.getNewVersionInfo((err, info) => {
updater.getNewVersionInfo((err: BusinessError, info: update.NewVersionInfo) => {
console.log(`info displayVersion = ${info?.versionComponents[0].displayVersion}`);
console.log(`info innerVersion = ${info?.versionComponents[0].innerVersion}`);
});
......@@ -240,7 +243,7 @@ Obtains information about the new version. This API uses a promise to return the
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Return value**
......@@ -254,15 +257,15 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
updater.getNewVersionInfo().then(info => {
updater.getNewVersionInfo().then((info: update.NewVersionInfo) => {
console.log(`info displayVersion = ${info.versionComponents[0].displayVersion}`);
console.log(`info innerVersion = ${info.versionComponents[0].innerVersion}`);
}).catch(err => {
}).catch((err: BusinessError) => {
console.log(`getNewVersionInfo promise error ${JSON.stringify(err)}`);
});
```
......@@ -275,7 +278,7 @@ Obtains the description file of the new version. This API uses an asynchronous c
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -291,25 +294,26 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
// Version digest information
const versionDigestInfo = {
const versionDigestInfo: update.VersionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result
};
// Options of the description file
const descriptionOptions = {
const descriptionOptions: update.DescriptionOptions = {
format: update.DescriptionFormat.STANDARD, // Standard format
language: "zh-cn" // Chinese
};
updater.getNewVersionDescription(versionDigestInfo, descriptionOptions, (err, info) => {
console.log(`getNewVersionDescription info ${JSON.stringify(info)}`);
console.log(`getNewVersionDescription err ${JSON.stringify(err)}`);
updater.getNewVersionDescription(versionDigestInfo, descriptionOptions).then((info: Array<update.ComponentDescription>)=> {
console.log(`getNewVersionDescription promise info ${JSON.stringify(info)}`);
}).catch((err: BusinessError) => {
console.log(`getNewVersionDescription promise error ${JSON.stringify(err)}`);
});
```
......@@ -321,7 +325,7 @@ Obtains the description file of the new version. This API uses a promise to retu
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -342,25 +346,25 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
// Version digest information
const versionDigestInfo = {
const versionDigestInfo: update.VersionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result
};
// Options of the description file
const descriptionOptions = {
const descriptionOptions: update.DescriptionOptions = {
format: update.DescriptionFormat.STANDARD, // Standard format
language: "zh-cn" // Chinese
};
updater.getNewVersionDescription(versionDigestInfo, descriptionOptions).then(info => {
updater.getNewVersionDescription(versionDigestInfo, descriptionOptions).then((info: Array<update.ComponentDescription>)=> {
console.log(`getNewVersionDescription promise info ${JSON.stringify(info)}`);
}).catch(err => {
}).catch((err: BusinessError) => {
console.log(`getNewVersionDescription promise error ${JSON.stringify(err)}`);
});
```
......@@ -373,7 +377,7 @@ Obtains information about the current version. This API uses an asynchronous cal
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -387,12 +391,12 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
updater.getCurrentVersionInfo((err, info) => {
updater.getCurrentVersionInfo((err: BusinessError, info: update.CurrentVersionInfo) => {
console.log(`info osVersion = ${info?.osVersion}`);
console.log(`info deviceName = ${info?.deviceName}`);
console.log(`info displayVersion = ${info?.versionComponents[0].displayVersion}`);
......@@ -407,7 +411,7 @@ Obtains information about the current version. This API uses a promise to return
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Return value**
......@@ -421,16 +425,16 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
updater.getCurrentVersionInfo().then(info => {
updater.getCurrentVersionInfo().then((info: update.CurrentVersionInfo) => {
console.log(`info osVersion = ${info.osVersion}`);
console.log(`info deviceName = ${info.deviceName}`);
console.log(`info displayVersion = ${info.versionComponents[0].displayVersion}`);
}).catch(err => {
}).catch((err: BusinessError) => {
console.log(`getCurrentVersionInfo promise error ${JSON.stringify(err)}`);
});
```
......@@ -443,7 +447,7 @@ Obtains the description file of the current version. This API uses an asynchrono
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -458,13 +462,13 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
// Options of the description file
const descriptionOptions = {
const descriptionOptions: update.DescriptionOptions = {
format: update.DescriptionFormat.STANDARD, // Standard format
language: "zh-cn" // Chinese
};
......@@ -483,7 +487,7 @@ Obtains the description file of the current version. This API uses a promise to
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -503,20 +507,19 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
// Options of the description file
const descriptionOptions = {
const descriptionOptions: update.DescriptionOptions = {
format: update.DescriptionFormat.STANDARD, // Standard format
language: "zh-cn" // Chinese
};
updater.getCurrentVersionDescription(descriptionOptions).then(info => {
updater.getCurrentVersionDescription(descriptionOptions).then((info: Array<update.ComponentDescription>) => {
console.log(`getCurrentVersionDescription promise info ${JSON.stringify(info)}`);
}).catch(err => {
}).catch((err: BusinessError) => {
console.log(`getCurrentVersionDescription promise error ${JSON.stringify(err)}`);
});
```
......@@ -529,7 +532,7 @@ Obtains information about the update task. This API uses an asynchronous callbac
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -543,12 +546,12 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
updater.getTaskInfo((err, info) => {
updater.getTaskInfo((err: BusinessError, info: update.TaskInfo) => {
console.log(`getTaskInfo isexistTask= ${info?.existTask}`);
});
```
......@@ -561,7 +564,7 @@ Obtains information about the update task. This API uses a promise to return the
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Return value**
......@@ -575,14 +578,14 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
updater.getTaskInfo().then(info => {
updater.getTaskInfo().then((info: update.TaskInfo) => {
console.log(`getTaskInfo isexistTask= ${info.existTask}`);
}).catch(err => {
}).catch((err: BusinessError) => {
console.log(`getTaskInfo promise error ${JSON.stringify(err)}`);
});
```
......@@ -595,7 +598,7 @@ Downloads the new version. This API uses an asynchronous callback to return the
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -611,22 +614,22 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
// Version digest information
const versionDigestInfo = {
const versionDigestInfo: update.VersionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result
};
// Download options
const downloadOptions = {
const downloadOptions: update.DownloadOptions = {
allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network
order: update.Order.DOWNLOAD // Download
};
updater.download(versionDigestInfo, downloadOptions, (err) => {
updater.download(versionDigestInfo, downloadOptions, (err: BusinessError) => {
console.log(`download error ${JSON.stringify(err)}`);
});
```
......@@ -639,7 +642,7 @@ Downloads the new version. This API uses a promise to return the result.
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -660,24 +663,24 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
// Version digest information
const versionDigestInfo = {
const versionDigestInfo: update.VersionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result
};
// Download options
const downloadOptions = {
const downloadOptions: update.DownloadOptions = {
allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network
order: update.Order.DOWNLOAD // Download
};
updater.download(versionDigestInfo, downloadOptions).then(() => {
console.log(`download start`);
}).catch(err => {
}).catch((err: BusinessError) => {
console.log(`download error ${JSON.stringify(err)}`);
});
```
......@@ -690,7 +693,7 @@ Resumes download of the new version. This API uses an asynchronous callback to r
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -706,21 +709,21 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
// Version digest information
const versionDigestInfo = {
const versionDigestInfo : update.VersionDigestInfo= {
versionDigest: "versionDigest" // Version digest information in the check result
};
// Options for resuming download
const resumeDownloadOptions = {
const resumeDownloadOptions : update.ResumeDownloadOptions= {
allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network
};
updater.resumeDownload(versionDigestInfo, resumeDownloadOptions, (err) => {
updater.resumeDownload(versionDigestInfo, resumeDownloadOptions, (err: BusinessError) => {
console.log(`resumeDownload error ${JSON.stringify(err)}`);
});
```
......@@ -733,7 +736,7 @@ Resumes download of the new version. This API uses a promise to return the resul
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -754,23 +757,23 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
// Version digest information
const versionDigestInfo = {
const versionDigestInfo: update.VersionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result
};
// Options for resuming download
const resumeDownloadOptions = {
const resumeDownloadOptions: update.ResumeDownloadOptions = {
allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network
};
updater.resumeDownload(versionDigestInfo, resumeDownloadOptions).then(value => {
updater.resumeDownload(versionDigestInfo, resumeDownloadOptions).then(() => {
console.log(`resumeDownload start`);
}).catch(err => {
}).catch((err: BusinessError) => {
console.log(`resumeDownload error ${JSON.stringify(err)}`);
});
```
......@@ -783,7 +786,7 @@ Pauses download of the new version. This API uses an asynchronous callback to re
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -799,21 +802,21 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
// Version digest information
const versionDigestInfo = {
const versionDigestInfo: update.VersionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result
};
// Options for pausing download
const pauseDownloadOptions = {
const pauseDownloadOptions: update.PauseDownloadOptions = {
isAllowAutoResume: true // Whether to allow automatic resuming of download
};
updater.pauseDownload(versionDigestInfo, pauseDownloadOptions, (err) => {
updater.pauseDownload(versionDigestInfo, pauseDownloadOptions, (err: BusinessError) => {
console.log(`pauseDownload error ${JSON.stringify(err)}`);
});
```
......@@ -826,7 +829,7 @@ Resumes download of the new version. This API uses a promise to return the resul
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -847,23 +850,23 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
// Version digest information
const versionDigestInfo = {
const versionDigestInfo: update.VersionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result
};
// Options for pausing download
const pauseDownloadOptions = {
const pauseDownloadOptions: update.PauseDownloadOptions = {
isAllowAutoResume: true // Whether to allow automatic resuming of download
};
updater.pauseDownload(versionDigestInfo, pauseDownloadOptions).then(value => {
updater.pauseDownload(versionDigestInfo, pauseDownloadOptions).then(() => {
console.log(`pauseDownload`);
}).catch(err => {
}).catch((err: BusinessError) => {
console.log(`pauseDownload error ${JSON.stringify(err)}`);
});
```
......@@ -876,7 +879,7 @@ Updates the version. This API uses an asynchronous callback to return the result
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -892,21 +895,21 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
// Version digest information
const versionDigestInfo = {
const versionDigestInfo: update.VersionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result
};
// Installation options
const upgradeOptions = {
const upgradeOptions: update.UpgradeOptions = {
order: update.Order.INSTALL // Installation command
};
updater.upgrade(versionDigestInfo, upgradeOptions, (err) => {
updater.upgrade(versionDigestInfo, upgradeOptions, (err: BusinessError) => {
console.log(`upgrade error ${JSON.stringify(err)}`);
});
```
......@@ -919,7 +922,7 @@ Updates the version. This API uses a promise to return the result.
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -940,23 +943,23 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
// Version digest information
const versionDigestInfo = {
const versionDigestInfo: update.VersionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result
};
// Installation options
const upgradeOptions = {
const upgradeOptions: update.UpgradeOptions = {
order: update.Order.INSTALL // Installation command
};
updater.upgrade(versionDigestInfo, upgradeOptions).then(() => {
console.log(`upgrade start`);
}).catch(err => {
}).catch((err: BusinessError) => {
console.log(`upgrade error ${JSON.stringify(err)}`);
});
```
......@@ -969,7 +972,7 @@ Clears errors. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -985,21 +988,21 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
// Version digest information
const versionDigestInfo = {
const versionDigestInfo: update.VersionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result
};
// Options for clearing errors
const clearOptions = {
const clearOptions: update.ClearOptions = {
status: update.UpgradeStatus.UPGRADE_FAIL,
};
updater.clearError(versionDigestInfo, clearOptions, (err) => {
updater.clearError(versionDigestInfo, clearOptions, (err: BusinessError) => {
console.log(`clearError error ${JSON.stringify(err)}`);
});
```
......@@ -1012,7 +1015,7 @@ Clears errors. This API uses a promise to return the result.
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -1033,23 +1036,23 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
// Version digest information
const versionDigestInfo = {
const versionDigestInfo: update.VersionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result
};
// Options for clearing errors
const clearOptions = {
const clearOptions: update.ClearOptions = {
status: update.UpgradeStatus.UPGRADE_FAIL,
};
updater.clearError(versionDigestInfo, clearOptions).then(() => {
console.log(`clearError success`);
}).catch(err => {
}).catch((err: BusinessError) => {
console.log(`clearError error ${JSON.stringify(err)}`);
});
```
......@@ -1062,7 +1065,7 @@ Obtains the update policy. This API uses an asynchronous callback to return the
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -1076,12 +1079,12 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
updater.getUpgradePolicy((err, policy) => {
updater.getUpgradePolicy(err: BusinessError, policy: update.UpgradePolicy) => {
console.log(`policy downloadStrategy = ${policy?.downloadStrategy}`);
console.log(`policy autoUpgradeStrategy = ${policy?.autoUpgradeStrategy}`);
});
......@@ -1095,7 +1098,7 @@ Obtains the update policy. This API uses a promise to return the result.
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Return value**
......@@ -1109,15 +1112,15 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
updater.getUpgradePolicy().then(policy => {
updater.getUpgradePolicy().then((policy: update.UpgradePolicy) => {
console.log(`policy downloadStrategy = ${policy.downloadStrategy}`);
console.log(`policy autoUpgradeStrategy = ${policy.autoUpgradeStrategy}`);
}).catch(err => {
}).catch((err: BusinessError) => {
console.log(`getUpgradePolicy promise error ${JSON.stringify(err)}`);
});
```
......@@ -1130,7 +1133,7 @@ Sets the update policy. This API uses an asynchronous callback to return the res
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -1145,17 +1148,17 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
const policy = {
const policy: update.UpgradePolicy = {
downloadStrategy: false,
autoUpgradeStrategy: false,
autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes
autoUpgradePeriods: [ { start: 120, end: 240 }] // Automatic update period, in minutes
};
updater.setUpgradePolicy(policy, (err) => {
updater.setUpgradePolicy(policy, (err: BusinessError) => {
console.log(`setUpgradePolicy result: ${err}`);
});
```
......@@ -1168,7 +1171,7 @@ Sets the update policy. This API uses a promise to return the result.
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -1180,7 +1183,7 @@ Sets the update policy. This API uses a promise to return the result.
| Type | Description |
| -------------- | ------------------- |
| Promise\<void> | Promise used to return the result.|
| Promise\<void> | Promise that returns no value.|
**Error codes**
......@@ -1188,19 +1191,19 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
const policy = {
const policy: update.UpgradePolicy = {
downloadStrategy: false,
autoUpgradeStrategy: false,
autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes
autoUpgradePeriods: [ { start: 120, end: 240 }] // Automatic update period, in minutes
};
updater.setUpgradePolicy(policy).then(() => {
console.log(`setUpgradePolicy success`);
}).catch(err => {
}).catch((err: BusinessError) => {
console.log(`setUpgradePolicy promise error ${JSON.stringify(err)}`);
});
```
......@@ -1213,7 +1216,7 @@ Terminates the update. This API uses an asynchronous callback to return the resu
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -1227,12 +1230,12 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
updater.terminateUpgrade((err) => {
updater.terminateUpgrade((err: BusinessError) => {
console.log(`terminateUpgrade error ${JSON.stringify(err)}`);
});
```
......@@ -1245,7 +1248,7 @@ Terminates the update. This API uses a promise to return the result.
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Return value**
......@@ -1259,14 +1262,14 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
updater.terminateUpgrade().then(() => {
console.log(`terminateUpgrade success`);
}).catch(err => {
}).catch((err: BusinessError) => {
console.log(`terminateUpgrade error ${JSON.stringify(err)}`);
});
```
......@@ -1292,17 +1295,17 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
const eventClassifyInfo = {
const eventClassifyInfo: update.EventClassifyInfo = {
eventClassify: update.EventClassify.TASK, // Listening for update events
extraInfo: ""
};
updater.on(eventClassifyInfo, (eventInfo) => {
updater.on(eventClassifyInfo, (eventInfo: update.EventInfo) => {
console.log("updater on " + JSON.stringify(eventInfo));
});
```
......@@ -1327,17 +1330,17 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
const eventClassifyInfo = {
const eventClassifyInfo: update.EventClassifyInfo = {
eventClassify: update.EventClassify.TASK, // Listening for update events
extraInfo: ""
};
updater.off(eventClassifyInfo, (eventInfo) => {
updater.off(eventClassifyInfo, (eventInfo: update.EventInfo) => {
console.log("updater off " + JSON.stringify(eventInfo));
});
```
......@@ -1352,7 +1355,7 @@ Restores the scale to its factory settings. This API uses an asynchronous callba
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.FACTORY_RESET (a system permission)
**Required permission**: ohos.permission.FACTORY_RESET
**Parameters**
......@@ -1366,7 +1369,7 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
......@@ -1384,7 +1387,7 @@ Restores the scale to its factory settings. This API uses a promise to return th
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.FACTORY_RESET (a system permission)
**Required permission**: ohos.permission.FACTORY_RESET
**Return value**
......@@ -1398,14 +1401,14 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
restorer.factoryReset().then(() => {
console.log(`factoryReset success`);
}).catch(err => {
}).catch((err: BusinessError) => {
console.log(`factoryReset error ${JSON.stringify(err)}`);
});
```
......@@ -1420,7 +1423,7 @@ Verifies the update package. This API uses an asynchronous callback to return th
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -1436,12 +1439,12 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
const upgradeFile = {
const upgradeFile: update.UpgradeFile = {
fileType: update.ComponentType.OTA, // OTA package
filePath: "path" // Path of the local update package
};
......@@ -1459,7 +1462,7 @@ Verifies the update package. This API uses a promise to return the result.
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -1480,18 +1483,18 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
const upgradeFile = {
const upgradeFile: update.UpgradeFile = {
fileType: update.ComponentType.OTA, // OTA package
filePath: "path" // Path of the local update package
};
localUpdater.verifyUpgradePackage(upgradeFile, "cerstFilePath").then(() => {
console.log(`verifyUpgradePackage success`);
}).catch(err => {
}).catch((err: BusinessError) => {
console.log(`verifyUpgradePackage error ${JSON.stringify(err)}`);
});
```
......@@ -1503,7 +1506,7 @@ Installs the update package. This API uses an asynchronous callback to return th
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Parameters**
......@@ -1518,12 +1521,12 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
const upgradeFiles = [{
const upgradeFiles: Array<update.UpgradeFile> = [{
fileType: update.ComponentType.OTA, // OTA package
filePath: "path" // Path of the local update package
}];
......@@ -1541,7 +1544,7 @@ Installs the update package. This API uses a promise to return the result.
**System capability**: SystemCapability.Update.UpdateService
**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission)
**Required permission**: ohos.permission.UPDATE_SYSTEM
**Return value**
......@@ -1555,18 +1558,18 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
const upgradeFiles = [{
const upgradeFiles: Array<update.UpgradeFile> = [{
fileType: update.ComponentType.OTA, // OTA package
filePath: "path" // Path of the local update package
}];
localUpdater.applyNewVersion(upgradeFiles).then(() => {
console.log(`applyNewVersion success`);
}).catch(err => {
}).catch((err: BusinessError) => {
console.log(`applyNewVersion error ${JSON.stringify(err)}`);
});
```
......@@ -1591,19 +1594,19 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
const eventClassifyInfo = {
const eventClassifyInfo: update.EventClassifyInfo = {
eventClassify: update.EventClassify.TASK, // Listening for update events
extraInfo: ""
};
function onTaskUpdate(eventInfo) {
let onTaskUpdate: update.UpgradeTaskCallback = (eventInfo: update.EventInfo) => {
console.log(`on eventInfo id `, eventInfo.eventId);
}
};
localUpdater.on(eventClassifyInfo, onTaskUpdate);
```
......@@ -1628,19 +1631,19 @@ For details about the error codes, see [Update Error Codes](../errorcodes/errorc
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
| 11500104 | IPC error. |
**Example**
```ts
const eventClassifyInfo = {
const eventClassifyInfo: update.EventClassifyInfo = {
eventClassify: update.EventClassify.TASK, // Listening for update events
extraInfo: ""
};
function onTaskUpdate(eventInfo) {
let onTaskUpdate: update.UpgradeTaskCallback = (eventInfo: update.EventInfo) => {
console.log(`on eventInfo id `, eventInfo.eventId);
}
};
localUpdater.off(eventClassifyInfo, onTaskUpdate);
```
......@@ -1664,8 +1667,8 @@ Enumerates update service types.
| Name | Type | Mandatory | Description |
| ------- | ----------------------------------- | ---- | ---- |
| vendor | [BusinessVendor](#businessvendor) | Yes | Application vendor. |
| subType | [BusinessSubType](#businesssubtype) | Yes | Update service type. |
| vendor | [BusinessVendor](#businessvendor) | Yes | Supplier or vendor. |
| subType | [BusinessSubType](#businesssubtype) | Yes | Represents an update type. |
## CheckResult
......@@ -1675,7 +1678,7 @@ Represents the package check result.
| Name | Type | Mandatory | Description |
| ----------------- | --------------------------------- | ---- | ------ |
| isExistNewVersion | bool | Yes | Whether a new version is available.|
| isExistNewVersion | boolean | Yes | Whether a new version is available.<br>The value **true** indicates that a new version is available, and the value **false** indicates the opposite.|
| newVersionInfo | [NewVersionInfo](#newversioninfo) | No | Information about the new version. |
## NewVersionInfo
......@@ -1712,7 +1715,7 @@ Represents a version component.
| upgradeAction | [UpgradeAction](#upgradeaction) | Yes | Update mode. |
| displayVersion | string | Yes | Display version number. |
| innerVersion | string | Yes | Internal version number. |
| size | number | Yes | Update package size. |
| size | number | Yes | Size of the update package, in bytes. |
| effectiveMode | [EffectiveMode](#effectivemode) | Yes | Effective mode. |
| descriptionInfo | [DescriptionInfo](#descriptioninfo) | Yes | Information about the version description file.|
......@@ -1790,7 +1793,7 @@ Represents options for pausing download.
| Name | Type| Mandatory | Description |
| ----------------- | ---- | ---- | -------- |
| isAllowAutoResume | bool | Yes | Whether to allow automatic resuming of download.|
| isAllowAutoResume | boolean | Yes | Whether to allow automatic resuming of download.<br>The value **true** indicates that automatic resuming is allowed, and the value **false** indicates the opposite.|
## UpgradeOptions
......@@ -1820,8 +1823,8 @@ Represents an update policy.
| Name | Type | Mandatory | Description |
| ------------------- | --------------------------------------- | ---- | ------- |
| downloadStrategy | bool | Yes | Automatic download policy. |
| autoUpgradeStrategy | bool | Yes | Automatic update policy. |
| downloadStrategy | boolean | Yes | Automatic download policy.<br>The value **true** indicates that automatic download is supported, and the value **false** indicates the opposite.|
| autoUpgradeStrategy | boolean | Yes | Automatic update policy.<br>The value **true** indicates that automatic update is supported, and the value **false** indicates the opposite.|
| autoUpgradePeriods | Array\<[UpgradePeriod](#upgradeperiod)> | Yes | Automatic update period.|
## UpgradePeriod
......@@ -1843,7 +1846,7 @@ Task information.
| Name | Type | Mandatory | Description |
| --------- | --------------------- | ---- | ------ |
| existTask | bool | Yes | Whether a task exists.|
| existTask | boolean | Yes | Whether a task exists.<br>The value **true** indicates that the task exists, and the value **false** indicates the opposite.|
| taskBody | [TaskBody](#taskinfo) | Yes | Task data. |
## EventInfo
......
......@@ -146,7 +146,7 @@ console.log(bool);
requestRight(deviceName: string): Promise&lt;boolean&gt;
Requests the temporary permission for the application to access a USB device. This API uses a promise to return the result.
Requests the temporary permission for the application to access a USB device. This API uses a promise to return the result. System applications are granted the device access permission by default, and you do not need to apply for the permission separately.
**System capability**: SystemCapability.USB.USBManager
......
......@@ -161,7 +161,7 @@ console.log(`${bool}`);
requestRight(deviceName: string): Promise&lt;boolean&gt;
Requests the temporary permission for the application to access a USB device. This API uses a promise to return the result.
Requests the temporary device access permission for the application. This API uses a promise to return the result. System applications are granted the device access permission by default, and you do not need to apply for the permission separately.
**System capability**: SystemCapability.USB.USBManager
......@@ -190,7 +190,7 @@ usb.requestRight(devicesName).then((ret) => {
removeRight(deviceName: string): boolean
Removes the permission for the application to access a USB device.
Removes the device access permission for the application. System applications are granted the device access permission by default, and calling this API will not revoke the permission.
**System capability**: SystemCapability.USB.USBManager
......@@ -219,7 +219,7 @@ if (usb.removeRight(devicesName)) {
addRight(bundleName: string, deviceName: string): boolean
Adds the permission for the application to access a USB device.
Adds the device access permission for the application. System applications are granted the device access permission by default, and calling this API will not revoke the permission.
[requestRight](#usbrequestright) triggers a dialog box to request for user authorization, whereas **addRight** adds the access permission directly without displaying a dialog box.
......
......@@ -538,7 +538,7 @@ ws.off('message');
### on('close')<sup>6+</sup>
on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): void
on(type: 'close', callback: AsyncCallback\<CloseResult\>): void
Enables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
......@@ -549,7 +549,7 @@ Enables listening for the **close** events of a WebSocket connection. This API u
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------- | ---- | ------------------------------ |
| type | string | Yes | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.|
| callback | AsyncCallback\<{ code: number, reason: string }\> | Yes | Callback used to return the result.<br>**close** indicates the close error code and **reason** indicates the error code description.|
| callback | AsyncCallback\<CloseResult\> | Yes | Callback used to return the result.<br>**close** indicates the close error code and **reason** indicates the error code description.|
**Example**
......@@ -562,7 +562,7 @@ ws.on('close', (err, value) => {
### off('close')<sup>6+</sup>
off(type: 'close', callback?: AsyncCallback\<{ code: number, reason: string }\>): void
off(type: 'close', callback?: AsyncCallback\<CloseResult\>): void
Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
......@@ -576,7 +576,7 @@ Disables listening for the **close** events of a WebSocket connection. This API
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------- | ---- | ------------------------------ |
| type | string | Yes | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.|
| callback | AsyncCallback\<{ code: number, reason: string }\> | No | Callback used to return the result.<br>**close** indicates the close error code and **reason** indicates the error code description.|
| callback | AsyncCallback\<CloseResult\> | No | Callback used to return the result.<br>**close** and **reason** indicate the error code and error cause for closing the connection, respectively.|
**Example**
......@@ -655,6 +655,17 @@ Defines the optional parameters carried in the request for closing a WebSocket c
| code | number | No | Error code. Set this parameter based on the actual situation. The default value is **1000**.|
| reason | string | No | Error cause. Set this parameter based on the actual situation. The default value is an empty string ("").|
## CloseResult<sup>10+</sup>
Represents the result obtained from the **close** event reported when the WebSocket connection is closed.
**System capability**: SystemCapability.Communication.NetStack
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| code | number | Yes | Error code for closing the connection.|
| reason | string | Yes | Error cause for closing the connection.|
## Result Codes for Closing a WebSocket Connection
You can customize the result codes sent to the server. The result codes in the following table are for reference only.
......
......@@ -5,6 +5,8 @@
- [Ability Error Codes](errorcode-ability.md)
- [Distributed Scheduler Error Codes](errorcode-DistributedSchedule.md)
- [Form Error Codes](errorcode-form.md)
- AI
- [Intelligent Voice Error Codes](errorcode-intelligentVoice.md)
- Bundle Management
- [Bundle Error Codes](errorcode-bundle.md)
- [zlib Error Codes](errorcode-zlib.md)
......
# Intelligent Voice Error Codes
> **NOTE**
>
> This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](errorcode-universal.md).
## 22700101 Insufficient Memory
**Error Message**
No memory.
**Error Description**
This error code is reported if a memory allocation failure or null pointer occurs when an API is called.
**Possible Causes**
1. The system does not have sufficient memory for mapping.
2. Invalid instances are not destroyed in time to release the memory.
**Solution**
1. Stop the current operation or suspend other applications to free up memory.
2. Clear invalid instances to free up memory, and then create new instances as needed. If the problem persists, stop related operations.
## 22700102 Invalid Parameter
**Error Message**
Input parameter value error.
**Error Description**
This error code is reported if a certain parameter passed in the API is invalid.
**Possible Cause**
The parameter is invalid. For example, the parameter value is not within the range supported.
**Solution**
Pass the correct parameters in the API.
## 22700103 Initialization Failed
**Error Message**
Init failed.
**Error Description**
This error code is reported if an error occurs while the enrollment engine is initialized.
**Possible Cause**
1. Repeated initialization.
2. Lack of resources for initialization of the enrollment engine.
**Solution**
1. Avoid performing initialization repeatedly.
2. Ensure that the resources required for initialization, such as acoustic model files, are ready.
## 22700104 Enrollment Commit Failure
**Error Message**
Commit enroll failed.
**Error Description**
This error code is reported if an error occurs after the [commit()](../apis/js-apis-intelligentVoice.md#commit) API of the enrollment engine is called.
**Possible Cause**
The specified number of enrollment procedures are not completed.
**Solution**
Commit the enrollment after the specified number of enrollment procedures are completed.
......@@ -1091,7 +1091,7 @@
- [@ohos.charger (Charging Type)](reference/apis/js-apis-charger.md)
- [@ohos.cooperate (Screen Hopping)](reference/apis/js-apis-devicestatus-cooperate.md)
- [@ohos.deviceAttest (Device Attestation)](reference/apis/js-apis-deviceAttest.md)
- [@ohos.deviceStatus.dragInteraction (Drag)](reference/apis/js-apis-devicestatus-draginteraction.md)
- [@ohos.deviceStatus.dragInteraction (Drag Interaction)](reference/apis/js-apis-devicestatus-draginteraction.md)
- [@ohos.deviceInfo (Device Information)](reference/apis/js-apis-device-info.md)
- [@ohos.distributedDeviceManager (Device Management) (Recommended)](reference/apis/js-apis-distributedDeviceManager.md)
- [@ohos.distributedHardware.deviceManager (Device Management) (To Be Deprecated Soon)](reference/apis/js-apis-device-manager.md)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册