提交 038e348e 编写于 作者: Y yamila

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

Signed-off-by: Nyamila <tianyu55@huawei.com>
# EnterpriseAdminExtensionAbility Development # EnterpriseAdminExtensionAbility Development
## Introduction ## Introduction to EnterpriseAdminExtensionAbility
**EnterpriseAdminExtensionAbility** is essential to a mobile device management (MDM) application. When developing an MDM application for an enterprise, you must inherit the **EnterpriseAdminExtensionAbility** class and have the MDM service logic implemented in an **EnterpriseAdminExtensionAbility** instance. The **EnterpriseAdminExtensionAbility** class provides callbacks for the enable, disable, install, and uninstall events of a device administrator application, implementing notification of system administrator status changes. EnterpriseAdminExtensionAbility is a mandatory component for Mobile Device Management (MDM) applications. When developing MDM applications for enterprises, you need to inherit EnterpriseAdminExtensionAbility and implement MDM service logic in the EnterpriseAdminExtensionAbility instance. EnterpriseAdminExtensionAbility implements notifications of system management status changes and defines the callbacks for when a device administrator application is enabled or disabled or an application is installed or uninstalled.
## Constraints ## Constraints
- ***Function constraints*** - **Function constraints**
The APIs provided can be used only by device administrator applications. EnterpriseAdminExtensionAbility is applicable only to enterprise administrator applications.
## Scenarios: Listening for the Enable, Disable, Install, and Uninstall Events of a Device Administrator Application ## Observing Activation/Deactivation of a Device Administrator Application and Installation/Removal of an Application
### Overview ### Overview
**onAdminEnabled**: called when the enterprise administrator or employee deploys an MDM application and enables the DeviceAdmin permission for the application. The MDM application can set the initialization policy in the **onAdminEnabled** callback. **onAdminEnabled**: When an enterprise administrator or employee deploys an MDM application and activates the device administrator application, this callback is invoked to notify the MDM application that the DeviceAdmin permission is activated. The initialization policy of the MDM application can set in **onAdminEnabled**.
**onAdminDisabled**: called when the system or employee disables the DeviceAdmin permission to notify the enterprise administrator that the device is no longer managed. **onAdminDisabled**: When the device administrator application is deactivated, the callback is invoked to notify the MDM application that the DeviceAdmin permission is deactivated.
**onBundleAdded**: called to notify the enterprise administrator that the specified MDM application is installed on the device. In enterprise application administration settings, after the enterprise administrator subscribes to application installation and uninstallation events, the MDM application reports the events through the callbacks. **onBundleAdded**: The enterprise administrator can subscribe to application installation and uninstallation events. When an application is installed on an enterprise device, the MDM application reports the event in this callback to notify the enterprise administrator.
**onBundleRemoved**: called to notify the enterprise administrator that the specified MDM application is uninstalled on the device. **onBundleRemoved**: When an application is removed from an enterprise device, the MDM application reports the event in this callback to notify the enterprise administrator.
### Available APIs ### Available APIs
| Class | API | Description | | Class | API | Description |
| :------------------------------ | ----------------------------------------- | ---------------------------- | | :------------------------------ | ----------------------------------------- | ---------------------------- |
| EnterpriseAdminExtensionAbility | onAdminDisabled(): void | Called when the device administrator application is enabled.| | EnterpriseAdminExtensionAbility | onAdminDisabled(): void | Called when a device administrator application is deactivated.|
| EnterpriseAdminExtensionAbility | onBundleAdded(bundleName: string): void | Called when the MDM application is installed. | | EnterpriseAdminExtensionAbility | onBundleAdded(bundleName: string): void | Called when an application is installed on a device. |
| EnterpriseAdminExtensionAbility | onAdminEnabled(): void | Called when the device administrator application is disabled. | | EnterpriseAdminExtensionAbility | onAdminEnabled(): void | Called when a device administrator application is activated. |
| EnterpriseAdminExtensionAbility | onBundleRemoved(bundleName: string): void | Called when the MDM application is uninstalled. | | EnterpriseAdminExtensionAbility | onBundleRemoved(bundleName: string): void | Called when an application is removed from a device. |
### How to Develop ### How to Develop
To implement **EnterpriseAdminExtensionAbility**, enable the device administrator application and create an **ExtensionAbility** instance from the code directory of the device administrator application. The procedure is as follows: To implement EnterpriseAdminExtensionAbility, you need to activate the device administrator application and create **ExtensionAbility** in the code directory of the device administrator application. The procedure is as follows:
1. In the **ets** directory of the target module, right-click and choose **New > Directory** to create a directory named **EnterpriseExtAbility**. 1. In the **ets** directory of the target module, right-click and choose **New > Directory** to create a directory named **EnterpriseExtAbility**.
2. Right-click the **EnterpriseExtAbility** directory and choose **New > TypeScript File** to create a file named **EnterpriseExtAbility.ts**. 2. Right-click the **EnterpriseExtAbility** directory, and choose **New > TypeScript File** to create a file named **EnterpriseExtAbility.ts**.
3. Open the **EnterpriseExtAbility.ts** file and import the **EnterpriseAdminExtensionAbility** module. Customize a class that inherits from **EnterpriseAdminExtensionAbility** and add the required callbacks, such as **onAdminEnabled()** and **onAdminDisabled()**, through which the enterprise administrator can receive notification when the device administrator application is enabled or disabled. 3. Open the **EnterpriseExtAbility.ts** file and import the **EnterpriseAdminExtensionAbility** module. Inherit the **EnterpriseAdminExtensionAbility** module to the custom class and add application notification callbacks, such as **onAdminEnabled()** and **onAdminDisabled()**. When the device administrator application is activated or deactivated, the device administrator can receive notifications.
```ts ```ts
import EnterpriseAdminExtensionAbility from '@ohos.enterprise.EnterpriseAdminExtensionAbility'; import EnterpriseAdminExtensionAbility from '@ohos.enterprise.EnterpriseAdminExtensionAbility';
export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility { export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility {
onAdminEnabled() { onAdminEnabled() {
console.info("onAdminEnabled"); console.info("onAdminEnabled");
} }
onAdminDisabled() { onAdminDisabled() {
console.info("onAdminDisabled"); console.info("onAdminDisabled");
} }
...@@ -56,14 +56,14 @@ To implement **EnterpriseAdminExtensionAbility**, enable the device administrato ...@@ -56,14 +56,14 @@ To implement **EnterpriseAdminExtensionAbility**, enable the device administrato
onBundleAdded(bundleName: string) { onBundleAdded(bundleName: string) {
console.info("EnterpriseAdminAbility onBundleAdded bundleName:" + bundleName) console.info("EnterpriseAdminAbility onBundleAdded bundleName:" + bundleName)
} }
onBundleRemoved(bundleName: string) { onBundleRemoved(bundleName: string) {
console.info("EnterpriseAdminAbility onBundleRemoved bundleName" + bundleName) console.info("EnterpriseAdminAbility onBundleRemoved bundleName" + bundleName)
} }
}; };
``` ```
4. Register **ServiceExtensionAbility** in the [module.json5](../quick-start/module-configuration-file.md) file of the target module. Among the parameters, set **type** to **enterpriseAdmin** and **srcEntrance** to the code path of the current ExtensionAbility. 4. Register **ServiceExtensionAbility** in the [**module.json5**](../quick-start/module-configuration-file.md) file corresponding to the project module. Set **type** to **enterpriseAdmin** and **srcEntrance** to the path of the ExtensionAbility code.
```ts ```ts
"extensionAbilities": [ "extensionAbilities": [
...@@ -78,7 +78,7 @@ To implement **EnterpriseAdminExtensionAbility**, enable the device administrato ...@@ -78,7 +78,7 @@ To implement **EnterpriseAdminExtensionAbility**, enable the device administrato
## Example ## Example
Use the **subscribeManagedEvent** and **unsubscribeManagedEvent** APIs in the **@ohos.enterprise.adminManager** module to subscribe to and unsubscribe from the application installation and uninstallation event, respectively. After the subscription is successful, the MDM application notifies the enterprise administrator when it is installed or uninstalled on the device. Use **subscribeManagedEvent()** and **unsubscribeManagedEvent()** in the **@ohos.enterprise.adminManager** module to subscribe to application installation and removal events. When an application is installed or removed, the MDM application is notified of the event. Then, the MDM application reports the event in the callback to notify the enterprise administrator.
```ts ```ts
@State managedEvents: Array<adminManager.ManagedEvent> = [0,1] @State managedEvents: Array<adminManager.ManagedEvent> = [0,1]
...@@ -108,4 +108,3 @@ Use the **subscribeManagedEvent** and **unsubscribeManagedEvent** APIs in the ** ...@@ -108,4 +108,3 @@ Use the **subscribeManagedEvent** and **unsubscribeManagedEvent** APIs in the **
} }
``` ```
# HTTP Data Request # HTTP Data Request
## Use Cases ## When to Use
An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
...@@ -14,40 +14,49 @@ For details about how to apply for permissions, see [Access Control Development] ...@@ -14,40 +14,49 @@ For details about how to apply for permissions, see [Access Control Development]
The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md). The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md).
| API | Description | | API | Description |
| ----------------------------------------- | --------------------------------------------------------- | | ----------------------------------------- | ----------------------------------- |
| createHttp() | Creates an HTTP request. | | createHttp() | Creates an HTTP request. |
| request() | Initiates an HTTP request to a given URL. | | request() | Initiates an HTTP request to a given URL. |
| destroy() | Destroys an HTTP request. | | request2()<sup>10+</sup> | Initiates an HTTP network request based on the URL and returns a streaming response.|
| destroy() | Destroys an HTTP request. |
| on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. | | on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. |
| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events. | | off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events.|
| once\('headersReceive'\)<sup>8+</sup> | Registers a one-time observer for HTTP Response Header events.|
| on\('dataReceive'\)<sup>10+</sup> | Registers an observer for events indicating receiving of HTTP streaming responses. |
| off\('dataReceive'\)<sup>10+</sup> | Unregisters the observer for events indicating receiving of HTTP streaming responses. |
| on\('dataEnd'\)<sup>10+</sup> | Registers an observer for events indicating completion of receiving HTTP streaming responses. |
| off\('dataEnd'\)<sup>10+</sup> | Unregisters the observer for events indicating completion of receiving HTTP streaming responses.|
| on\('dataProgress'\)<sup>10+</sup> | Registers an observer for events indicating progress of receiving HTTP streaming responses. |
| off\('dataProgress'\)<sup>10+</sup> | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.|
## How to Develop ## How to Develop
1. Import the required HTTP module. 1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Create an **HttpRequest** object. 2. Call **createHttp()** to create an **HttpRequest** object.
3. (Optional) Listen for HTTP Response Header events. 3. Call **httpRequest.on()** to subscribe to HTTP response header events. This API returns a response earlier than the request. You can subscribe to HTTP response header events based on service requirements.
4. Initiate an HTTP request to a given URL. 4. Call **httpRequest.request()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
5. (Optional) Process the HTTP Response Header event and the return result of the HTTP request. 5. Parse the returned result based on service requirements.
6. Call **off()** to unsubscribe from HTTP response header events.
7. Call **httpRequest.destroy()** to release resources after the request is processed.
```js ```js
// Import the http namespace.
import http from '@ohos.net.http'; import http from '@ohos.net.http';
// Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused. // Each httpRequest corresponds to an HTTP request task and cannot be reused.
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
// This API is used to listen for the HTTP Response Header event, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP Response Header events.
// Subscribe to the HTTP response header, which is returned earlier than HttpRequest. You can subscribe to HTTP Response Header events based on service requirements. // on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+
httpRequest.on('headersReceive', (header) => { httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header)); console.info('header: ' + JSON.stringify(header));
}); });
httpRequest.request( httpRequest.request(
// Set the URL of the HTTP request. You need to define the URL. Set the parameters of the request in extraData. // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL", "EXAMPLE_URL",
{ {
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add the header field based on service requirements. // You can add header fields based on service requirements.
header: { header: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
...@@ -55,21 +64,33 @@ httpRequest.request( ...@@ -55,21 +64,33 @@ httpRequest.request(
extraData: { extraData: {
"data": "data to send", "data": "data to send",
}, },
connectTimeout: 60000, // Optional. The default value is 60000, in ms. expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
usingCache: true, // Optional. The default value is true.
priority: 1, // Optional. The default value is 1.
connectTimeout: 60000 // Optional. The default value is 60000, in ms.
readTimeout: 60000, // Optional. The default value is 60000, in ms. readTimeout: 60000, // Optional. The default value is 60000, in ms.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10.
}, (err, data) => { }, (err, data) => {
if (!err) { if (!err) {
// data.result contains the HTTP response. Parse the response based on service requirements. // data.result carries the HTTP response. Parse the response based on service requirements.
console.info('Result:' + data.result); console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + data.responseCode); console.info('code:' + JSON.stringify(data.responseCode));
// data.header contains the HTTP response header. Parse the content based on service requirements. // data.header carries the HTTP response header. Parse the content based on service requirements.
console.info('header:' + JSON.stringify(data.header)); console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+ console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
} else { } else {
console.info('error:' + JSON.stringify(err)); console.info('error:' + JSON.stringify(err));
// Call the destroy() method to destroy the request if it is no longer needed. // Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy(); httpRequest.destroy();
} }
} }
); );
``` ```
## Samples
The following sample is provided to help you better understand how to develop the HTTP data request feature:
- [`HTTP`: Data Request (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http)
- [HTTP Communication (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH)
...@@ -49,6 +49,7 @@ TLS Socket connection functions are mainly provided by the **tls_socket** module ...@@ -49,6 +49,7 @@ TLS Socket connection functions are mainly provided by the **tls_socket** module
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
| constructTLSSocketInstance() | Creates a **TLSSocket** object.|
| bind() | Binds the IP address and port number.| | bind() | Binds the IP address and port number.|
| close(type:&nbsp;'error') | Closes a Socket connection.| | close(type:&nbsp;'error') | Closes a Socket connection.|
| connect() | Sets up a connection to the specified IP address and port number.| | connect() | Sets up a connection to the specified IP address and port number.|
...@@ -189,7 +190,7 @@ TLS Socket connection process on the client: ...@@ -189,7 +190,7 @@ TLS Socket connection process on the client:
let tlsTwoWay = socket.constructTLSSocketInstance(); let tlsTwoWay = socket.constructTLSSocketInstance();
// Subscribe to TLS Socket connection events. // Subscribe to TLS Socket connection events.
tcp.on('message', value => { tlsTwoWay.on('message', value => {
console.log("on message") console.log("on message")
let buffer = value.message let buffer = value.message
let dataView = new DataView(buffer) let dataView = new DataView(buffer)
...@@ -199,10 +200,10 @@ TLS Socket connection process on the client: ...@@ -199,10 +200,10 @@ TLS Socket connection process on the client:
} }
console.log("on connect received:" + str) console.log("on connect received:" + str)
}); });
tcp.on('connect', () => { tlsTwoWay.on('connect', () => {
console.log("on connect") console.log("on connect")
}); });
tcp.on('close', () => { tlsTwoWay.on('close', () => {
console.log("on close") console.log("on close")
}); });
...@@ -245,23 +246,23 @@ TLS Socket connection process on the client: ...@@ -245,23 +246,23 @@ TLS Socket connection process on the client:
console.log(data); console.log(data);
}); });
// Enable the TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events. // Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
tls.close((err) => { tlsTwoWay.close((err) => {
if (err) { if (err) {
console.log("close callback error = " + err); console.log("close callback error = " + err);
} else { } else {
console.log("close success"); console.log("close success");
} }
tls.off('message'); tlsTwoWay.off('message');
tls.off('connect'); tlsTwoWay.off('connect');
tls.off('close'); tlsTwoWay.off('close');
}); });
// Create a TLS Socket connection (for one-way authentication). // Create a TLS Socket connection (for one-way authentication).
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
// Subscribe to TLS Socket connection events. // Subscribe to TLS Socket connection events.
tcp.on('message', value => { tlsTwoWay.on('message', value => {
console.log("on message") console.log("on message")
let buffer = value.message let buffer = value.message
let dataView = new DataView(buffer) let dataView = new DataView(buffer)
...@@ -271,10 +272,10 @@ TLS Socket connection process on the client: ...@@ -271,10 +272,10 @@ TLS Socket connection process on the client:
} }
console.log("on connect received:" + str) console.log("on connect received:" + str)
}); });
tcp.on('connect', () => { tlsTwoWay.on('connect', () => {
console.log("on connect") console.log("on connect")
}); });
tcp.on('close', () => { tlsTwoWay.on('close', () => {
console.log("on close") console.log("on close")
}); });
...@@ -306,16 +307,16 @@ TLS Socket connection process on the client: ...@@ -306,16 +307,16 @@ TLS Socket connection process on the client:
console.log(data); console.log(data);
}); });
// Enable the TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events. // Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
tls.close((err) => { tlsTwoWay.close((err) => {
if (err) { if (err) {
console.log("close callback error = " + err); console.log("close callback error = " + err);
} else { } else {
console.log("close success"); console.log("close success");
} }
tls.off('message'); tlsTwoWay.off('message');
tls.off('connect'); tlsTwoWay.off('connect');
tls.off('close'); tlsTwoWay.off('close');
}); });
``` ```
......
...@@ -53,10 +53,10 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform ...@@ -53,10 +53,10 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform
// Configure the parameters based on the audio file format. // Configure the parameters based on the audio file format.
SLDataFormat_PCM format_pcm = { SLDataFormat_PCM format_pcm = {
SL_DATAFORMAT_PCM, SL_DATAFORMAT_PCM, // Input audio format.
OHOS::AudioStandard::AudioChannel::MONO, 1, // Mono channel.
OHOS::AudioStandard::AudioSamplingRate::SAMPLE_RATE_44100, SL_SAMPLINGRATE_44_1, // Sampling rate, 44100 Hz.
OHOS::AudioStandard::AudioSampleFormat::SAMPLE_S16LE, SL_PCMSAMPLEFORMAT_FIXED_16, // Audio sampling format, a signed 16-bit integer in little-endian format.
0, 0,
0, 0,
0 0
......
# Quick Start # Quick Start
- Getting Started - Getting Started
- [Before You Start](start-overview.md) - [Before You Start](start-overview.md)
- [Getting Started with ArkTS in Stage Model](start-with-ets-stage.md) - [Getting Started with ArkTS in Stage Model](start-with-ets-stage.md)
...@@ -17,6 +18,16 @@ ...@@ -17,6 +18,16 @@
- [Multi-HAP Usage Rules](multi-hap-rules.md) - [Multi-HAP Usage Rules](multi-hap-rules.md)
- [Multi-HAP Operation Mechanism and Data Communication Modes](multi-hap-principles.md) - [Multi-HAP Operation Mechanism and Data Communication Modes](multi-hap-principles.md)
- [Application Installation and Uninstallation Process](application-package-install-uninstall.md) - [Application Installation and Uninstallation Process](application-package-install-uninstall.md)
- [Application Package Update Process](application-package-update.md)
- Shared Package
- [Shared Package Overview](shared-guide.md)
- [HAR](har-package.md)
- HSP
- [In-Application HSP Development](in-app-hsp.md)
- [Inter-Application HSP Development (for System Applications Only)](cross-app-hsp.md)
- Quick Fix
- [Quick Fix Overview](quickfix-principles.md)
- [CLI-based Quick Fix Development](quickfix-debug.md)
- Application Configuration Files in Stage Model - Application Configuration Files in Stage Model
- [Application Configuration File Overview (Stage Model)](application-configuration-file-overview-stage.md) - [Application Configuration File Overview (Stage Model)](application-configuration-file-overview-stage.md)
- [app.json5 Configuration File](app-configuration-file.md) - [app.json5 Configuration File](app-configuration-file.md)
......
# Application Package Structure in Stage Model # Application Package Structure in Stage Model
To develop an application based on the [stage model](application-configuration-file-overview-stage.md), it is essential to understand the structure of the application package created after the application is built and packaged. To develop an application based on the [stage model](application-configuration-file-overview-stage.md), it will be helpful if you have a basic understanding of the structure of the application package created after the application is built and packaged, as well as the related basic concepts.
- In development, an application contains one or more modules. You can [create modules](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3) in the application project in [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio/). As a basic functional unit of an OpenHarmony application/service, a module contains source code, resource files, third-party libraries, and application/service configuration files, and can be built and run independently. Modules can be classified as Ability or Library. A module of the Ability type is built into a Harmony Ability Package (HAP) file in .hap format, and a module of the Library type is built into a [Harmony Ability Resources (HAR) file](har-structure.md) in .tgz format. - In development, an application contains one or more modules. You can [create modules](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3) in the application project in [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio/). As a basic functional unit of an OpenHarmony application/service, a module contains source code, resource files, third-party libraries, and application/service configuration files, and can be built and run independently. Modules can be classified as Ability or Library. A module of the Ability type is built into a Harmony Ability Package (HAP) file, and a module of the Library type is built into a [Harmony Archive (HAR)](har-package.md) file or a [Harmony Shared Package (HSP)](shared-guide.md).
A module can contain one or more [UIAbility](../application-models/uiability-overview.md) components, as shown in the figure below. A module can contain one or more [UIAbility](../application-models/uiability-overview.md) components, as shown in the figure below.
**Figure 1** Relationship between modules and UIAbility components **Figure 1** Relationship between modules and UIAbility components
![ability-and-module](figures/ability-and-module.png) ![ability-and-module](figures/ability-and-module.png)
Unless otherwise specified, the modules described in this document refer to the modules of the Ability type. Unless otherwise specified, the modules described in this document refer to the modules of the Ability type.
- As aforementioned, you can build an application into one or more HAP files. The HAP file is the basic unit for installing an application. It provides code, resources, third-party libraries, and a configuration file. HAP files can be classified as Entry or Feature. - As aforementioned, you can build an application into one or more HAP files. The HAP file is the basic unit for installing an application. It provides code, resources, third-party libraries, and a configuration file. HAP files can be classified as Entry or Feature.
- HAP of the entry type: main module of the application, whose **type** field is set to **"entry"** in the [module.json5](module-configuration-file.md) file. In an application, each type of device supports only one HAP of the entry type, which is typically used to implement the application's entry screen, entry icon, or headline feature. - HAP of the entry type: main module of the application, whose **type** field is set to **"entry"** in the [module.json5](module-configuration-file.md) file. In an application, each type of device supports only one HAP of the entry type, which is typically used to implement the application's entry screen, entry icon, or headline feature.
...@@ -27,6 +27,6 @@ To develop an application based on the [stage model](application-configuration-f ...@@ -27,6 +27,6 @@ To develop an application based on the [stage model](application-configuration-f
- The **module.json** file is the configuration file indispensable in a HAP file. It consists of **module.json5** and **app.json5** in the project configuration. While DevEco Studio provides default configuration, you must modify the configuration as needed. For details about the configuration fields, see [Application Configuration Files in Stage Model](application-configuration-file-overview-stage.md). - The **module.json** file is the configuration file indispensable in a HAP file. It consists of **module.json5** and **app.json5** in the project configuration. While DevEco Studio provides default configuration, you must modify the configuration as needed. For details about the configuration fields, see [Application Configuration Files in Stage Model](application-configuration-file-overview-stage.md).
- The **pack.info** file describes the HAP attributes in the bundle, for example, **bundleName** and **versionCode** in **app** and **name**, **type**, and **abilities** in **module**. The file is automatically generated when DevEco Studio generates the bundle. - The **pack.info** file describes the HAP attributes in the bundle, for example, **bundleName** and **versionCode** in **app** and **name**, **type**, and **abilities** in **module**. The file is automatically generated when DevEco Studio generates the bundle.
**Figure 2** Application package structure in stage model **Figure 2** Application package structure in stage model
![app-pack-stage](figures/app-pack-stage.png) ![app-pack-stage](figures/app-pack-stage.png)
\ No newline at end of file
# Inter-Application HSP Development
An inter-application Harmony Shared Package (HSP) is a file used for code and resource sharing between the host application and other applications.
The host application of an inter-application HSP is a special form of application, which consists of only one HSP. Instead of running independently on a device, the host application runs by being referenced by dependencies of common application modules. When a common application is running, it can invoke capabilities provided by the inter-application HSP dynamically as needed.
## Precautions
1. The code of an inter-application HSP runs in the application process. When invoking the code, implement an exception capture and fault tolerance mechanism to avoid stability issues caused by malfunctioning of the inter-application HSP.
2. An application can depend on multiple inter-application HSP files at the same time.
3. The inter-application HSP may slow down the startup of the application that depends on it. To avoid significant increase in the startup delay, limit the number of inter-application HSP dependencies within 16.
4. Third-party developers can only use the system-provided inter-application HSP files.
## Inter-Application HSP Usage
An inter-application HSP works by combining the following parts:
[HAR](har-package.md): contains only objects and methods to be exported and therefore comes in a small size. By integrating the HAR into your application project, you can call the objects and methods therein to implement features.
HSP: contains the actual implementation code, including the JS/TS code, C++ libraries, resources, and configuration files. It is either released to the application market or integrated into the system version.
### Integrating the HAR in an Inter-Application HSP
Define the interfaces to be exported in the **index.d.ets** file in the HAR, which is the entry to the declaration file exported by the inter-application HSP. The path of the **index.d.ets** file is as follows:
```
src
├── main
| └── module.json5
├── index.d.ets
└── package.json
```
Below is an example of the **index.d.ets** file content:
```ts
@Component
export declare struct UIComponent {
build():void;
}
export declare function hello(): string;
export declare function foo1(): string;
export declare function foo2(): string;
export declare function nativeHello(): string;
```
In the example, **UIComponent** is an ArkUI component, **hello()**, **foo1()**, and **foo2()** are TS methods, and **nativeHello()** is an native method. Specific implementation is as follows:
#### ArkUI Components
The following is an implementation example of ArkUI components in the HSP:
```ts
// lib/src/main/ets/ui/MyUIComponent.ets
@Component
export struct UIComponent {
@State message: string = 'Hello World'
build() {
Column() {
Text(this.message)
.fontSize(32)
.padding(8)
.fontColor(0xffffff)
.backgroundColor(0x0000ff)
}.padding(8).width('100%')
}
}
```
#### **TS Methods**
The following is an implementation example of TS methods in the HSP:
```ts
export function hello(name: string): string {
return "hello + " + name;
}
export function foo1() {
return "foo1";
}
export function foo2() {
return "foo2";
}
```
#### **Native Methods**
The following is an implementation example of native methods in the HSP:
```C++
#include "napi/native_api.h"
#include <js_native_api.h>
#include <js_native_api_types.h>
#include <string>
const std::string libname = "liba";
const std::string version = "v10001";
static napi_value Hello(napi_env env, napi_callback_info info) {
napi_value ret;
std::string msg = libname + ":native hello, " + version;
napi_create_string_utf8(env, msg.c_str(), msg.length(), &ret);
return ret;
}
EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports) {
napi_property_descriptor desc[] = {
{"nativeHello", nullptr, Hello, nullptr, nullptr, nullptr, napi_default, nullptr}};
napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
return exports;
}
EXTERN_C_END
static napi_module demoModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "liba",
.nm_priv = ((void *)0),
.reserved = {0},
};
extern "C" __attribute__((constructor)) void RegisterLibaModule(void) {
napi_module_register(&demoModule);
}
```
### Using the Capabilities Exported from the HAR
To start with, [configure dependency](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434#section89674298391) on the HAR. The dependency information will then be generated in the **module.json** file of the corresponding module, as shown in the following:
```json
"dependencies": [
{
"bundleName": "com.share.liba",
"moduleName": "liba",
"versionCode": 10001
}
]
```
In the preceding information, **bundleName**, **moduleName**, and **versionCode** indicate the bundle name, module name, and version number of the inter-application HSP, respectively.
#### Referencing ArkUI Components in the HAR
After configuring the dependency on the HAR, you can reference ArkUI components exported from the HAR by using **import**. The sample code is as follows:
``` ts
import { UIComponent } from 'liba'
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
// Reference the ArkUI component in the HAR.
UIComponent()
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
```
#### Referencing TS Classes and Methods in the HAR
To reference the TS classes and methods exported from the HAR, use **import** as follows:
``` ts
import { foo1 } from 'liba'
import { foo2 } from 'liba'
@Component
struct Index {
build() {
Row() {
Column() {
Button('Button')
.onClick(()=>{
// Reference the TS methods in the HAR.
foo1();
foo2();
})
}
.width('100%')
}
.height('100%')
}
}
```
#### Referencing Native Methods in the HAR
To reference the native methods exported from the HAR, use **import** as follows:
``` ts
import { nativeHello } from 'liba'
@Component
struct Index {
build() {
Row() {
Column() {
Button('Button')
.onClick(()=>{
// Reference the native method in the HAR.
nativeHello();
})
}
.width('100%')
}
.height('100%')
}
}
```
## Inter-Application HSP Distribution
Inter-application HSPs are not completely integrated into an application. They are distributed by being preset in the system version or installed with an application on the device. To be specific:
1. Some frequently-used inter-application HSPs are preset in the system version.
2. When a user downloads an application from the application market, if the application market detects that the application depends on one or more inter-application HSPs and any of these HSPs are not installed on the target device, it will download the application as well as the missing HSPs for the user. In this way, the application can use the features shared through the HSPs properly.
### Inter-Application HSP Debugging Mode
You can debug an inter-application HSP after it is distributed to a device. If the aforementioned distribution methods are not applicable, you can distribute the HSP by running **bm** commands. The procedure is as follows:
> **NOTE**
>
> Do not reverse steps 2 and 3. Otherwise, your application will fail to be installed due to a lack of the required inter-application HSP. For more information about the **bm** commands, see [Bundle Management](../../readme/bundle-management.md).
1. Obtain the inter-application HSP installation package.
2. Run the following **bm** command to install the inter-application HSP.
```
bm install -s sharebundle.hsp
```
3. Run the following **bm** command to install the HAP file of your application.
```
bm install -p feature.hap
```
4. Start your application and start debugging.
# HAR
A Harmony Archive (HAR) is a static shared package that can contain code, C++ libraries, resources, and configuration files. It enables modules and projects to share code related to ArkUI components, resources, and more. Unlike a Harmony Ability Package (HAP), a HAR cannot be independently installed on a device. Instead, it can be referenced only as the dependency of an application module.
## Creating a HAR Module
You can kickstart your HAR module development with the module template of the **Library** type in DevEco Studio. By default, obfuscation is disabled for the HAR module. To enable this feature, set **artifactType** in the **build-profile.json5** file of the HAR module to **obfuscation** as follows:
```json
{
"apiType": "stageMode",
"buildOption": {
"artifactType": "obfuscation"
}
}
```
The value options of **artifactType** are as follows, and the default value is **original**:
- **original**: Code is not obfuscated.
- **obfuscation**: Code is obfuscated using Uglify.
When obfuscation is enabled, DevEco Studio compiles, obfuscates, and compresses code during HAR building, thereby protecting your code assets.
> **NOTE**
>
> If **artifactType** is set to **obfuscation**, **apiType** must be set to **stageMode**, because obfuscation is available only in the stage model.
## Precautions for HAR Development
- The HAR does not support the declaration of **abilities** and **extensionAbilities** in its configuration file.
- The HAR does not support the declaration of pages in its configuration file.
- The HAR does not support **worker** configuration under **buildOption** in the **build-profile.json5** file.
- The HAR of the FA model and that of the stage model cannot be referenced by each other.
- The HAR of the stage model cannot reference content in the **AppScope** folder. This is because the content in the **AppScope** folder is not packaged into the HAR during compilation and building.
## Exporting ArkUI Components, APIs, and Resources of the HAR
The **index.ets** file acts as the entry of the HAR export declaration file and is where the HAR exports APIs. This file is automatically generated by DevEco Studio by default. You can specify another file as the entry declaration file in the **main** field in the **package.json** file of the module. The code snippet is as follows:
```json
{
"main": "index.ets"
}
```
### Exporting ArkUI Components
Use **export** to export the ArkUI components. The code snippet is as follows:
```js
// library/src/main/ets/components/MainPage/MainPage.ets
@Component
export struct MainPage {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
```
In the **index.ets** file, declare the APIs that the HAR exposes to external systems. The code snippet is as follows:
```js
// library/index.ets
export { MainPage } from './src/main/ets/components/MainPage/MainPage'
```
### Exporting TS Classes and Methods
Use **export** to export TS classes and methods. Multiple TS classes and methods can be exported at the same time. The code snippet is as follows:
```js
// library/src/main/ts/test.ets
export class Log {
static info(msg) {
console.info(msg);
}
}
export function func() {
return "har func";
}
export function func2() {
return "har func2";
}
```
In the **index.ets** file, declare the APIs that the HAR exposes to external systems. The code snippet is as follows:
```js
// library/index.ets
export { Log } from './src/main/ts/test'
export { func } from './src/main/ts/test'
export { func2 } from './src/main/ts/test'
```
### Resources
Resources are packed into the HAR when it is being compiled and packaged. During compilation and building of a HAP, DevEco Studio collects resource files from the HAP module and its dependent modules. If the resource files of different modules have the same name, DevEco Studio overwrites the resource files based on the following priorities (in descending order):
- AppScope (supported only by the stage model of API version 9)
- Modules in the HAP file
- If resource conflicts occur between dependent HAR modules, they are overwritten based on the dependency sequence. (The module that is higher in the dependency sequence list has higher priority.)
## Referencing ArkUI Components, APIs, and Resources in the HAR
To start with, [configure dependency](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434#section89674298391) on the HAR.
### Reference ArkUI Components in the HAR
After configuring the dependency on the HAR, you can reference ArkUI components exported from the HAR by using **import**. The sample code is as follows:
```js
// entry/src/main/ets/pages/index.ets
import { MainPage } from "@ohos/library"
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
// Reference the ArkUI component in the HAR.
MainPage()
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
```
### Referencing TS Classes and Methods in the HAR
To reference the TS classes and methods exported from the HAR, use **import** as follows:
```js
// entry/src/main/ets/pages/index.ets
import { Log } from "@ohos/library"
import { func } from "@ohos/library"
@Entry
@Component
struct Index {
build() {
Row() {
Column() {
Button('Button')
.onClick(()=>{
// Reference TS classes and methods in the HAR.
Log.info("har msg");
func();
})
}
.width('100%')
}
.height('100%')
}
}
```
### Referencing Resources in the HAR
Use **$r** to reference resources in the HAR. For example, add the **name: hello_har** string (defined in the **string.json** file) and **icon_har.png** image to the **src/main/resources** directory of the HAR module, and then reference the string and image in the entry module. The code snippet is as follows:
```js
// entry/src/main/ets/pages/index.ets
@Entry
@Component
struct Index {
build() {
Row() {
Column() {
// Reference the string in the HAR.
Text($r("app.string.hello_har"))
.fontSize(50)
.fontWeight(FontWeight.Bold)
// Reference the image in the HAR.
Image($r("app.media.icon_har"))
}
.width('100%')
}
.height('100%')
}
}
```
# In-Application HSP Development
An in-application Harmony Shared Package (HSP) is a file used for code and resource sharing within an application (called the host application) and can only be invoked by a HAP or HSP of the same application.
The in-application HSP is released with the Application Package (App Pack) of the host application and has the same bundle name and lifecycle as the host application.
## Developing an In-Application HSP
You can kickstart your HSP development with the HSP template in DevEco Studio. In this example, an HSP module named **library** is created. The basic project directory structure is as follows:
```
library
├── src
│ └── main
│ ├── ets
│ │ ├── pages
│ │ └── index.ets
│ ├── resources
│ └── module.json5
└── package.json
```
In the **module.json5** file, set **type** to **shared** for the HSP.
```json
{
"type": "shared"
}
```
The HSP provides capabilities for external systems by exporting APIs in the entry file. Specify the entry file in **main** in the **package.json** file. For example:
```json
{
"main": "./src/main/ets/index.ets"
}
```
### Exporting TS Classes and Methods
Use **export** to export TS classes and methods. The sample code is as follows:
```ts
// library/src/main/ets/utils/test.ts
export class Log {
static info(msg) {
console.info(msg);
}
}
export function add(a: number, b: number) {
return a + b;
}
export function minus(a: number, b: number) {
return a - b;
}
```
In the entry file **index.ets**, declare the APIs to be exposed.
```ts
// library/src/main/ets/index.ets
export { Log, add, minus } from './utils/test'
```
### Exporting ArkUI Components
Use **export** to export ArkUI components. The sample code is as follows:
```ts
// library/src/main/ets/components/MyTitleBar.ets
@Component
export struct MyTitleBar {
build() {
Row() {
Text($r('app.string.library_title'))
.fontColor($r('app.color.white'))
.fontSize(25)
.margin({left:15})
}
.width('100%')
.height(50)
.padding({left:15})
.backgroundColor('#0D9FFB')
}
}
```
In the entry file **index.ets**, declare the APIs to be exposed.
```ts
// library/src/main/ets/index.ets
export { MyTitleBar } from './components/MyTitleBar'
```
#### About Using Resources in the HSP
To reference resources in the **resources** directory of the current HSP module, use **$r** or **$rawfile**.
If a relative path is used, the resources in the HSP caller are referenced instead. For example,
if **Image("common/example.png")** is used in the HSP module, the **\<Image>** component will reference the resource **entry/src/main/ets/common/example.png** in the HSP caller (which is **entry** in this example).
### Exporting Native Methods
The HSP can contain .so files compiled in C++. The HSP indirectly exports the native method in the .so file. In this example, the **multi** method in the **libnative.so** file is exported.
```ts
// ibrary/src/main/ets/utils/nativeTest.ts
import native from "libnative.so"
export function nativeMulti(a: number, b: number) {
return native.multi(a, b);
}
```
In the entry file **index.ets**, declare the APIs to be exposed.
```ts
// library/src/main/ets/index.ets
export { nativeMulti } from './utils/nativeTest'
```
## Using the In-Application HSP
To use APIs in the HSP, first configure the dependency on the HSP in the **package.json** file of the module that needs to call the APIs (called the invoking module). If the HSP and the invoking module are in the same project, the APIs can be referenced locally. The sample code is as follows:
```json
// entry/src/main/module.json5
"dependencies": {
"library": "file:../library"
}
```
You can now call the external APIs of the HSP in the same way as calling the APIs in the HAR.
In this example, the external APIs are the following ones exported from **library**:
```ts
// library/src/main/ets/index.ets
export { Log, add, minus } from './utils/test'
export { MyTitleBar } from './components/MyTitleBar'
export { nativeMulti } from './utils/nativeTest'
```
The APIs can be used as follows in the code of the invoking module:
```ts
// entry/src/main/ets/pages/index.ets
import { Log, add, MyTitleBar, nativeMulti } from "library"
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
MyTitleBar()
Text(this.message)
.fontSize(30)
.fontWeight(FontWeight.Bold)
Button('add(1, 2)')
.onClick(()=>{
Log.info("add button click!");
this.message = "result: " + add(1, 2);
})
Button('nativeMulti(3, 4)')
.onClick(()=>{
Log.info("nativeMulti button click!");
this.message = "result: " + nativeMulti(3, 4);
})
}
.width('100%')
}
.height('100%')
}
}
```
...@@ -487,11 +487,12 @@ Example of the **extensionAbilities** structure: ...@@ -487,11 +487,12 @@ Example of the **extensionAbilities** structure:
## requestPermissions ## requestPermissions
The **requestPermissions** tage represents a set of permissions that the application needs to request from the system for running correctly. The **requestPermissions** tag represents a set of permissions that the application needs to request from the system for running correctly.
> **NOTE** > **NOTE**
> >
> The permission settings configured in the **requestPermissions** tag apply to the entire application. > - The permission settings configured in the **requestPermissions** tag apply to the entire application.
> - If your application needs to subscribe to an event published by itself and the permissions required for accessing the application are set in the **permissions** tag under **extensionAbilities**, then the application must register the related permissions in the **requestPermissions** tag to receive the event.
**Table 8** requestPermissions **Table 8** requestPermissions
......
# Shared Package Overview
OpenHarmony provides two types of shared packages: [Harmony Achive (HAR)](har-package.md) static shared package and Harmony Shared Package (HSP) dynamic shared package.
Both the HAR and HSP are used to share code and resources and can contain code, C++ libraries, resources, and configuration files. The biggest differences between them are as follows: The code and resources in the HAR are compiled with the invoking module, and if there are multiple invoking modules, the build product contains multiple copies of the same code and resources; the code and resources in the HSP can be compiled independently, and the build product contains only one copy of the code and resources.
**Figure 1** HAR and HSP in the App Pack
![in-app-hsp-har](figures/in-app-hsp-har.png)
The HSP is designed to solve the following issues with the HAR:
- When multiple HAPs reference the same HAR, the size of the App Pack swells.
- When multiple HAPs reference the same HAR, some state variables in the HAR cannot be shared.
Restrictions on the HSP:
- The HSP and its invoking modules must be in the stage model.
- The HSP and its invoking modules must use the **esmodule **compilation mode.
- The HSP does not support the declaration of **abilities** and **extensionAbilities** in its configuration file.
The HSP can be classified as [in-application HSP](in-app-hsp.md) or [inter-application HSP](cross-app-hsp.md), depending on the configuration files and usage methods.
...@@ -105,3 +105,55 @@ export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbil ...@@ -105,3 +105,55 @@ export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbil
} }
}; };
``` ```
## EnterpriseAdminExtensionAbility.onAppStart<sup>10+</sup>
onAppStart(bundleName: string): void
Called when an application is started.
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
**System API**: This is a system API.
**Parameters**
| Parameter | Type | Mandatory | Description |
| ----- | ----------------------------------- | ---- | ------- |
| bundleName | string | Yes | Bundle name of the application started.|
**Example**
```ts
export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility {
onAppStart(bundleName: string) {
console.log("started bundle name: " + bundleName);
}
};
```
## EnterpriseAdminExtensionAbility.onAppStop<sup>10+</sup>
onAppStop(bundleName: string): void
Called when an application is stopped.
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
**System API**: This is a system API.
**Parameters**
| Parameter | Type | Mandatory | Description |
| ----- | ----------------------------------- | ---- | ------- |
| bundleName | string | Yes | Bundle name of the application stopped.|
**Example**
```ts
export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility {
onAppStop(bundleName: string) {
console.log("stopped bundle name: " + bundleName);
}
};
```
...@@ -4,7 +4,7 @@ The **appRecovery** module provides APIs for recovering faulty applications. ...@@ -4,7 +4,7 @@ The **appRecovery** module provides APIs for recovering faulty applications.
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. In the current version, only applications with a single ability in a single process can be recovered. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. In API version 9, only applications with a single ability in a process can be recovered. In API version 10, applications with multiple abilities in a process can be recovered.
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -51,7 +51,7 @@ Enumerates the application state saving modes. This enum is used as an input par ...@@ -51,7 +51,7 @@ Enumerates the application state saving modes. This enum is used as an input par
enableAppRecovery(restart?: [RestartFlag](#apprecoveryrestartflag), saveOccasion?: [SaveOccasionFlag](#apprecoverysaveoccasionflag), saveMode?: [SaveModeFlag](#apprecoverysavemodeflag)) : void; enableAppRecovery(restart?: [RestartFlag](#apprecoveryrestartflag), saveOccasion?: [SaveOccasionFlag](#apprecoverysaveoccasionflag), saveMode?: [SaveModeFlag](#apprecoverysavemodeflag)) : void;
Enables application recovery. Enables application recovery. After this API is called, the first ability that is displayed when the application is started from the initiator can be restored.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -63,8 +63,8 @@ Enables application recovery. ...@@ -63,8 +63,8 @@ Enables application recovery.
| saveOccasion | [SaveOccasionFlag](#apprecoverysaveoccasionflag) | No| Scenario for saving the application state. By default, the state is saved when a fault occurs.| | saveOccasion | [SaveOccasionFlag](#apprecoverysaveoccasionflag) | No| Scenario for saving the application state. By default, the state is saved when a fault occurs.|
| saveMode | [SaveModeFlag](#apprecoverysavemodeflag) | No| Application state saving mode. By default, the application state is written to the local file cache.| | saveMode | [SaveModeFlag](#apprecoverysavemodeflag) | No| Application state saving mode. By default, the application state is written to the local file cache.|
**Example** **Example**
```ts ```ts
import appRecovery from '@ohos.app.ability.appRecovery'; import appRecovery from '@ohos.app.ability.appRecovery';
import AbilityStage from '@ohos.app.ability.AbilityStage'; import AbilityStage from '@ohos.app.ability.AbilityStage';
...@@ -84,13 +84,22 @@ export default class MyAbilityStage extends AbilityStage { ...@@ -84,13 +84,22 @@ export default class MyAbilityStage extends AbilityStage {
restartApp(): void; restartApp(): void;
Restarts the application. This API can be used together with APIs of [errorManager](js-apis-app-ability-errorManager.md). Restarts the current process and starts the first ability that is displayed when the application is started. If the state of this ability is saved, the saved state data is passed into the **wantParam** attribute in the **want** parameter of the **OnCreate** lifecycle callback of the ability.
In API version 10, the ability specified by [setRestartWant](#apprecoverysetrestartwant) is started. If no ability is specified, the following rules are used:
- If the ability of the current application running in the foreground supports recovery, that ability is started.
- If multiple abilities that support recovery is running in the foreground, only the last ability is started.
- If no ability is running in the foreground, none of them is started.
This API can be used together with the APIs of [errorManager](js-apis-app-ability-errorManager.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Example**
**Example**
```ts ```ts
import appRecovery from '@ohos.app.ability.appRecovery'; import appRecovery from '@ohos.app.ability.appRecovery';
import errorManager from '@ohos.app.ability.errorManager'; import errorManager from '@ohos.app.ability.errorManager';
...@@ -113,7 +122,7 @@ try { ...@@ -113,7 +122,7 @@ try {
saveAppState(): boolean; saveAppState(): boolean;
Saves the application state. This API can be used together with APIs of [errorManager](js-apis-app-ability-errorManager.md). Saves the application state. This API can be used together with the APIs of [errorManager](js-apis-app-ability-errorManager.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -123,8 +132,8 @@ Saves the application state. This API can be used together with APIs of [errorMa ...@@ -123,8 +132,8 @@ Saves the application state. This API can be used together with APIs of [errorMa
| -------- | -------- | | -------- | -------- |
| boolean | Whether the application state is saved. The value **true** is returned if the application state is saved, and **false** is returned otherwise.| | boolean | Whether the application state is saved. The value **true** is returned if the application state is saved, and **false** is returned otherwise.|
**Example** **Example**
```ts ```ts
import appRecovery from '@ohos.app.ability.appRecovery'; import appRecovery from '@ohos.app.ability.appRecovery';
import errorManager from '@ohos.app.ability.errorManager'; import errorManager from '@ohos.app.ability.errorManager';
...@@ -142,3 +151,53 @@ try { ...@@ -142,3 +151,53 @@ try {
console.error('error: ${paramError.code}, ${paramError.message}'); console.error('error: ${paramError.code}, ${paramError.message}');
} }
``` ```
## appRecovery.saveAppState<sup>10+</sup>
saveAppState(context?: UIAbilityContext): boolean;
Saves the ability state, which will be used for recovery. This API can be used together with the APIs of [errorManager](js-apis-app-ability-errorManager.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Whether the application state is saved. The value **true** is returned if the application state is saved, and **false** is returned otherwise.|
**Example**
```ts
import appRecovery from '@ohos.app.ability.appRecovery';
onBackground() {
hilog.info(0x0000, '[demo]', '%{public}s', 'EntryAbility onBackground');
appRecovery.saveAppState(this.context)
}
```
## appRecovery.setRestartWant<sup>10+</sup>
setRestartWant(want: Want): void;
Sets an ability that will be recovered. The ability must be a UIAbility in the current bundle.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Example**
```ts
import appRecovery from '@ohos.app.ability.appRecovery';
Button ("Start to Recover Ability")
.fontSize(40)
.fontWeight(FontWeight.Bold)
.onClick(()=> {
// set restart want
let want = {
bundleName: "ohos.samples.recovery",
abilityName: "RecoveryAbility"
};
appRecovery.setRestartWant(want);
})
```
...@@ -18,7 +18,7 @@ import batteryStats from '@ohos.batteryStatistics'; ...@@ -18,7 +18,7 @@ import batteryStats from '@ohos.batteryStatistics';
getBatteryStats(): Promise<Array&lt;BatteryStatsInfo&gt;> getBatteryStats(): Promise<Array&lt;BatteryStatsInfo&gt;>
Obtains the power consumption information list, using a promise to return the result. Obtains the power consumption information list. This API uses a promise to return the result.
**System API**: This is a system API. **System API**: This is a system API.
...@@ -34,9 +34,9 @@ Obtains the power consumption information list, using a promise to return the re ...@@ -34,9 +34,9 @@ Obtains the power consumption information list, using a promise to return the re
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message | | Code | Error Message |
| -------- | -------------- | |---------|---------|
| 4600101 | Operation failed. Cannot connect to service.| | 4600101 | Operation failed. Cannot connect to service.|
**Example** **Example**
...@@ -64,15 +64,15 @@ Obtains the power consumption information list. This API uses an asynchronous ca ...@@ -64,15 +64,15 @@ Obtains the power consumption information list. This API uses an asynchronous ca
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback<Array<[BatteryStatsInfo](#batterystatsinfo)>> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the array of power consumption information obtained. If the operation failed, **err** is an error object.| | callback | AsyncCallback<Array<[BatteryStatsInfo](#batterystatsinfo)>> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the array of power consumption information obtained (that is, **Array<[BatteryStatsInfo](#batterystatsinfo)>>**). If the operation failed, **err** is an error object.|
**Error codes** **Error codes**
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message | | Code | Error Message |
| -------- | -------------- | |---------|---------|
| 4600101 | Operation failed. Cannot connect to service.| | 4600101 | Operation failed. Cannot connect to service.|
**Example** **Example**
...@@ -112,9 +112,9 @@ Obtains the power consumption of an application. ...@@ -112,9 +112,9 @@ Obtains the power consumption of an application.
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message | | Code | Error Message |
| -------- | -------------- | |---------|---------|
| 4600101 | Operation failed. Cannot connect to service.| | 4600101 | Operation failed. Cannot connect to service.|
**Example** **Example**
...@@ -153,9 +153,9 @@ Obtains the proportion of the power consumption of an application. ...@@ -153,9 +153,9 @@ Obtains the proportion of the power consumption of an application.
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message | | Code | Error Message |
| -------- | -------------- | |---------|---------|
| 4600101 | Operation failed. Cannot connect to service.| | 4600101 | Operation failed. Cannot connect to service.|
**Example** **Example**
...@@ -194,16 +194,16 @@ Obtains the power consumption of a hardware unit according to the consumption ty ...@@ -194,16 +194,16 @@ Obtains the power consumption of a hardware unit according to the consumption ty
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message | | Code | Error Message |
| -------- | -------------- | |---------|---------|
| 4600101 | Operation failed. Cannot connect to service.| | 4600101 | Operation failed. Cannot connect to service.|
**Example** **Example**
```js ```js
try { try {
var value = batteryStats.getHardwareUnitPowerValue(ConsumptionType.CONSUMPTION_TYPE_SCREEN); var value = batteryStats.getHardwareUnitPowerValue(ConsumptionType.CONSUMPTION_TYPE_SCREEN);
console.info('battery statistics percent of hardware is: ' + percent); console.info('battery statistics value of hardware is: ' + value);
} catch(err) { } catch(err) {
console.error('get battery statistics percent of hardware failed, err: ' + err); console.error('get battery statistics percent of hardware failed, err: ' + err);
} }
...@@ -235,15 +235,15 @@ Obtains the proportion of the power consumption of a hardware unit according to ...@@ -235,15 +235,15 @@ Obtains the proportion of the power consumption of a hardware unit according to
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message | | Code | Error Message |
| -------- | -------------- | |---------|---------|
| 4600101 | Operation failed. Cannot connect to service.| | 4600101 | Operation failed. Cannot connect to service.|
**Example** **Example**
```js ```js
try { try {
var value = batteryStats.getHardwareUnitPowerPercent(ConsumptionType.CONSUMPTION_TYPE_SCREEN); var percent = batteryStats.getHardwareUnitPowerPercent(ConsumptionType.CONSUMPTION_TYPE_SCREEN);
console.info('battery statistics percent of hardware is: ' + percent); console.info('battery statistics percent of hardware is: ' + percent);
} catch(err) { } catch(err) {
console.error('get battery statistics percent of hardware failed, err: ' + err); console.error('get battery statistics percent of hardware failed, err: ' + err);
......
# SharedBundleInfo
The **SharedBundleInfo** module provides information about the shared bundle. The information can be obtained by calling [bundleManager.getSharedBundleInfo](js-apis-bundleManager.md).
> **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.
## SharedBundleInfo
Defines the shared bundle information.
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
| Name | Type | Readable| Writable| Description |
| ---------------- | ------------------------------ | ---- | ---- | ---------------------- |
| name | string | Yes | No | Name of the shared bundle. |
| compatiblePolicy | bundleManager.CompatiblePolicy | Yes | No | Compatibility type of the shared bundle.|
| sharedModuleInfo | Array\<SharedModuleInfo> | Yes | No | Information about the shared module. |
## SharedModuleInfo
Defines the shared module information.
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
| Name | Type | Readable| Writable| Description |
| ------------- | ------ | ---- | ---- | -------------------------- |
| name | string | Yes | No | Module name of the shared bundle. |
| versionCode | number | Yes | No | Version number of the shared bundle. |
| versionName | string | Yes | No | Version description of the shared bundle.|
| description | string | Yes | No | Description of the shared bundle. |
| descriptionId | number | Yes | No | Description ID of the shared bundle. |
...@@ -112,6 +112,7 @@ Enumerates the types of Extension abilities. ...@@ -112,6 +112,7 @@ Enumerates the types of Extension abilities.
| ENTERPRISE_ADMIN | 11 | [EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md): provides APIs for processing enterprise management events, such as application installation events on devices and events indicating too many incorrect screen-lock password attempts.| | ENTERPRISE_ADMIN | 11 | [EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md): provides APIs for processing enterprise management events, such as application installation events on devices and events indicating too many incorrect screen-lock password attempts.|
| THUMBNAIL | 13 | ThumbnailExtensionAbility: provides thumbnails for files. This ability is reserved.| | THUMBNAIL | 13 | ThumbnailExtensionAbility: provides thumbnails for files. This ability is reserved.|
| PREVIEW | 14 | PreviewExtensionAbility: provides APIs for file preview so that other applications can be embedded and displayed in the current application. This ability is reserved.| | PREVIEW | 14 | PreviewExtensionAbility: provides APIs for file preview so that other applications can be embedded and displayed in the current application. This ability is reserved.|
| PRINT<sup>10+</sup> | 15 | PrintExtensionAbility: provides APIs for printing images. Printing documents is not supported yet.|
| UNSPECIFIED | 255 | No type is specified. It is used together with **queryExtensionAbilityInfo** to query all types of Extension abilities.| | UNSPECIFIED | 255 | No type is specified. It is used together with **queryExtensionAbilityInfo** to query all types of Extension abilities.|
...@@ -2861,6 +2862,191 @@ try { ...@@ -2861,6 +2862,191 @@ try {
} }
``` ```
### bundleManager.getSharedBundleInfo<sup>10+</sup>
getSharedBundleInfo(bundleName: string, moduleName: string, callback: AsyncCallback\<Array\<SharedBundleInfo\>\>): void;
Obtains the shared bundle information based on the given bundle name. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| bundleName | string | Yes | Bundle name. |
| moduleName | string | Yes | Module name. |
| callback | AsyncCallback\<Array\<[SharedBundleInfo](js-apis-bundleManager-sharedBundleInfo.md)\>\> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the shared bundle information obtained.|
**Error codes**
For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
| ID| Error Message |
| -------- | -------------------------------------- |
| 17700001 | The specified bundleName is not found. |
| 17700002 | The specified moduleName is not found. |
**Example**
```ts
import bundleManager from '@ohos.bundle.bundleManager';
import hilog from '@ohos.hilog';
let bundleName = 'com.example.myapplication';
let moduleName = 'library';
try {
bundleManager.getSharedBundleInfo(bundleName, moduleName, (err, data) => {
if (err) {
hilog.error(0x0000, 'testTag', 'getSharedBundleInfo failed: %{public}s', err.message);
} else {
hilog.info(0x0000, 'testTag', 'getSharedBundleInfo successfully: %{public}s', JSON.stringify(data));
}
});
} catch (err) {
hilog.error(0x0000, 'testTag', 'getSharedBundleInfo failed: %{public}s', err.message);
}
```
### bundleManager.getSharedBundleInfo<sup>10+</sup>
function getSharedBundleInfo(bundleName: string, moduleName: string): Promise\<Array\<SharedBundleInfo\>\>;
Obtains the shared bundle information based on the given bundle name. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | ------ | ---- | -------------------------- |
| bundleName | string | Yes | Bundle name.|
| moduleName | string | Yes | Module name.|
**Return value**
| Type | Description |
| ------------------------------------------------------------ | ----------------------------------- |
| Promise\<Array\<[SharedBundleInfo](js-apis-bundleManager-sharedBundleInfo.md)\>\> | Promise used to return the shared bundle information obtained.|
**Error codes**
For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
| ID| Error Message |
| -------- | -------------------------------------- |
| 17700001 | The specified bundleName is not found. |
| 17700002 | The specified moduleName is not found. |
**Example**
```ts
import bundleManager from '@ohos.bundle.bundleManager';
import hilog from '@ohos.hilog';
let bundleName = 'com.example.myapplication';
let moduleName = 'library';
try {
bundleManager.getSharedBundleInfo(bundleName, moduleName).then((data) => {
hilog.info(0x0000, 'testTag', 'getSharedBundleInfo successfully. Data: %{public}s', JSON.stringify(data));
}).catch(err => {
hilog.error(0x0000, 'testTag', 'getSharedBundleInfo failed. Cause: %{public}s', err.message);
});
} catch (err) {
hilog.error(0x0000, 'testTag', 'getSharedBundleInfo failed. Cause: %{public}s', err.message);
}
```
### bundleManager.getAllSharedBundleInfo<sup>10+</sup>
getAllSharedBundleInfo(callback: AsyncCallback\<Array\<SharedBundleInfo\>\>): void;
Obtains the information about all shared bundles. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback\<Array\<[SharedBundleInfo](js-apis-bundleManager-sharedBundleInfo.md)\>\> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is an array of the shared bundle information obtained.|
**Example**
```ts
import bundleManager from '@ohos.bundle.bundleManager';
import hilog from '@ohos.hilog';
try {
bundleManager.getAllSharedBundleInfo((err, data) => {
if (err) {
hilog.error(0x0000, 'testTag', 'getAllSharedBundleInfo failed: %{public}s', err.message);
} else {
hilog.info(0x0000, 'testTag', 'getAllSharedBundleInfo successfully: %{public}s', JSON.stringify(data));
}
});
} catch (err) {
hilog.error(0x0000, 'testTag', 'getAllSharedBundleInfo failed: %{public}s', err.message);
}
```
### bundleManager.getAllSharedBundleInfo<sup>10+</sup>
function getAllSharedBundleInfo(): Promise\<Array\<SharedBundleInfo\>\>;
Obtains the information about all shared bundles. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
**Return value**
| Type | Description |
| ------------------------------------------------------------ | ----------------------------------- |
| Promise\<Array\<[SharedBundleInfo](js-apis-bundleManager-sharedBundleInfo.md)\>\> | Promise used to return an array of the shared bundle information obtained.|
**Example**
```ts
import bundleManager from '@ohos.bundle.bundleManager';
import hilog from '@ohos.hilog';
try {
bundleManager.getAllSharedBundleInfo().then((data) => {
hilog.info(0x0000, 'testTag', 'getAllSharedBundleInfo successfully. Data: %{public}s', JSON.stringify(data));
}).catch(err => {
hilog.error(0x0000, 'testTag', 'getAllSharedBundleInfo failed. Cause: %{public}s', err.message);
});
} catch (err) {
hilog.error(0x0000, 'testTag', 'getAllSharedBundleInfo failed. Cause: %{public}s', err.message);
}
```
## CompatiblePolicy
Defines the version compatibility type of the shared library.
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
| Name | Value | Description |
| ---------------------- | ---- | -------------------------------- |
| BACKWARD_COMPATIBILITY | 1 | The shared library is backward compatible.|
## ModuleType ## ModuleType
Enumerates the module types. Enumerates the module types.
......
...@@ -953,5 +953,7 @@ Enumerates the system management events that can be subscribed to. ...@@ -953,5 +953,7 @@ Enumerates the system management events that can be subscribed to.
| Name | Value | Description | | Name | Value | Description |
| -------------------------- | ---- | ------------- | | -------------------------- | ---- | ------------- |
| MANAGED_EVENT_BUNDLE_ADDED | 0 | Application installation event.| | MANAGED_EVENT_BUNDLE_ADDED | 0 | Bundle added.|
| MANAGED_EVENT_BUNDLE_REMOVED | 1 | Application uninstallation event.| | MANAGED_EVENT_BUNDLE_REMOVED | 1 | Bundle removed.|
| MANAGED_EVENT_APP_START | 2 | Application started.|
| MANAGED_EVENT_APP_STOP | 3 | Application stopped.|
# @ohos.hiAppEvent (Application Event Logging) # @ohos.hiAppEvent (Application Event Logging)
The HiAppEvent module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration. The **hiAppEvent** module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration.
> **NOTE** > **NOTE**
>
> - The APIs provided by this module are deprecated since API version 9. You are advised to use [`@ohos.hiviewdfx.hiAppEvent`](js-apis-hiviewdfx-hiappevent.md) instead. > - The APIs provided by this module are deprecated since API version 9. You are advised to use [`@ohos.hiviewdfx.hiAppEvent`](js-apis-hiviewdfx-hiappevent.md) instead.
> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -19,7 +20,7 @@ Before using application event logging, you need to understand the requirements ...@@ -19,7 +20,7 @@ Before using application event logging, you need to understand the requirements
**Event Name** **Event Name**
An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_). An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (\_).
**Event Type** **Event Type**
...@@ -30,9 +31,10 @@ An event type is an enumerated value of [EventType](#eventtype). ...@@ -30,9 +31,10 @@ An event type is an enumerated value of [EventType](#eventtype).
An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows: An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows:
- A parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (\_). - A parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (\_).
- The parameter value is a string, number, boolean, or array. - The parameter value can be of the string, number, boolean, or array type.
- When the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be truncated. - If the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be discarded.
- When the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded. - If the parameter value is a number, the value must be within the range of **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. Otherwise, uncertain values may be generated.
- If the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.
- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded. - The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.
**Event Callback** **Event Callback**
......
# @ohos.hiviewdfx.hiAppEvent (Application Event Logging) # @ohos.hiviewdfx.hiAppEvent (Application Event Logging)
This module provides application event-related functions, including flushing application events to a disk, querying and clearing application events, and customizing application event logging configuration. The **hiAppEvent** module provides application event-related functions, including flushing application events to a disk, querying and clearing application events, and customizing application event logging configuration.
> **NOTE** > **NOTE**
> >
...@@ -120,12 +120,12 @@ Defines parameters for an **AppEventInfo** object. ...@@ -120,12 +120,12 @@ Defines parameters for an **AppEventInfo** object.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent **System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | ----------------------- | ---- | ---------- | | --------- | ----------------------- | ---- | ------------------------------------------------------------ |
| domain | string | Yes | Event domain.| | domain | string | Yes | Event domain. Event domain name, which is a string of up to 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).|
| name | string | Yes | Event name.| | name | string | Yes | Event name. Event name, which is a string of up to 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).|
| eventType | [EventType](#eventtype) | Yes | Event type.| | eventType | [EventType](#eventtype) | Yes | Event type. |
| params | object | Yes | Event parameters.| | params | object | Yes | Event parameter object, which consists of a parameter name and a parameter value. The specifications are as follows:<br>- The parameter name is a string of up to 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).<br>- The parameter value can be a string, number, boolean, or array. If the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be discarded. If the parameter value is a number, the value must be within the range of **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. Otherwise, uncertain values may be generated. If the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.<br>- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.|
## hiAppEvent.configure ## hiAppEvent.configure
......
# @ohos.net.http (Data Request) # @ohos.net.http (Data Request)
The **http** module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. This module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
>**NOTE** >**NOTE**
> >
...@@ -13,10 +13,10 @@ The **http** module provides the HTTP data request capability. An application ca ...@@ -13,10 +13,10 @@ The **http** module provides the HTTP data request capability. An application ca
import http from '@ohos.net.http'; import http from '@ohos.net.http';
``` ```
## Examples ## Example
```js ```js
// Import the HTTP namespace. // Import the http namespace.
import http from '@ohos.net.http'; import http from '@ohos.net.http';
// Each httpRequest corresponds to an HTTP request task and cannot be reused. // Each httpRequest corresponds to an HTTP request task and cannot be reused.
...@@ -27,7 +27,7 @@ httpRequest.on('headersReceive', (header) => { ...@@ -27,7 +27,7 @@ httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header)); console.info('header: ' + JSON.stringify(header));
}); });
httpRequest.request( httpRequest.request(
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. // Customize EXAMPLE_URL on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL", "EXAMPLE_URL",
{ {
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
...@@ -112,7 +112,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback ...@@ -112,7 +112,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
**Error codes** **Error codes**
| ID | Error Message | | Code | Error Message |
|---------|-------------------------------------------------------| |---------|-------------------------------------------------------|
| 401 | Parameter error. | | 401 | Parameter error. |
| 201 | Permission denied. | | 201 | Permission denied. |
...@@ -164,7 +164,7 @@ Initiates an HTTP request containing specified options to a given URL. This API ...@@ -164,7 +164,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Error codes** **Error codes**
| ID | Error Message | | Code | Error Message |
|---------|-------------------------------------------------------| |---------|-------------------------------------------------------|
| 401 | Parameter error. | | 401 | Parameter error. |
| 201 | Permission denied. | | 201 | Permission denied. |
...@@ -231,7 +231,7 @@ httpRequest.request("EXAMPLE_URL", ...@@ -231,7 +231,7 @@ httpRequest.request("EXAMPLE_URL",
request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\> request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\>
Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result. Initiates an HTTP request to a given URL. This API uses a promise to return the result.
>**NOTE** >**NOTE**
>This API supports only transfer of data not greater than 5 MB. >This API supports only transfer of data not greater than 5 MB.
...@@ -255,7 +255,7 @@ Initiates an HTTP request containing specified options to a given URL. This API ...@@ -255,7 +255,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Error codes** **Error codes**
| ID | Error Message | | Code | Error Message |
|---------|-------------------------------------------------------| |---------|-------------------------------------------------------|
| 401 | Parameter error. | | 401 | Parameter error. |
| 201 | Permission denied. | | 201 | Permission denied. |
...@@ -349,7 +349,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback ...@@ -349,7 +349,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
**Error codes** **Error codes**
| ID | Error Message | | Code | Error Message |
|---------|-------------------------------------------------------| |---------|-------------------------------------------------------|
| 401 | Parameter error. | | 401 | Parameter error. |
| 201 | Permission denied. | | 201 | Permission denied. |
...@@ -395,7 +395,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback ...@@ -395,7 +395,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
**Error codes** **Error codes**
| ID | Error Message | | Code | Error Message |
|---------|-------------------------------------------------------| |---------|-------------------------------------------------------|
| 401 | Parameter error. | | 401 | Parameter error. |
| 201 | Permission denied. | | 201 | Permission denied. |
...@@ -477,7 +477,7 @@ Initiates an HTTP request containing specified options to a given URL. This API ...@@ -477,7 +477,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Error codes** **Error codes**
| ID | Error Message | | Code | Error Message |
|---------|-------------------------------------------------------| |---------|-------------------------------------------------------|
| 401 | Parameter error. | | 401 | Parameter error. |
| 201 | Permission denied. | | 201 | Permission denied. |
...@@ -513,7 +513,7 @@ Initiates an HTTP request containing specified options to a given URL. This API ...@@ -513,7 +513,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
>**NOTE** >**NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). > For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see: > The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
**Example** **Example**
...@@ -839,7 +839,7 @@ Enumerates the response codes for an HTTP request. ...@@ -839,7 +839,7 @@ Enumerates the response codes for an HTTP request.
| Name | Value | Description | | Name | Value | Description |
| ----------------- | ---- | ------------------------------------------------------------ | | ----------------- | ---- | ------------------------------------------------------------ |
| OK | 200 | "OK." The request has been processed successfully. This return code is generally used for GET and POST requests. | | OK | 200 | The request is successful. The request has been processed successfully. This return code is generally used for GET and POST requests. |
| CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. | | CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. |
| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. | | ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. |
| NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. | | NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. |
...@@ -1007,7 +1007,7 @@ Disables the cache and deletes the data in it. This API uses a promise to return ...@@ -1007,7 +1007,7 @@ Disables the cache and deletes the data in it. This API uses a promise to return
| Type | Description | | Type | Description |
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<void\> | Promise used to return the result.| | Promise\<void\> | Promise used to return the result.|
**Example** **Example**
......
...@@ -15,10 +15,10 @@ Want is a carrier for information transfer between objects (application componen ...@@ -15,10 +15,10 @@ Want is a carrier for information transfer between objects (application componen
| abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| | abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.|
| uri | string | No | URI. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| | uri | string | No | URI. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.|
| type | string | No | MIME type, that is, the type of the file to open, for example, **'text/xml'** and **'image/*'**. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | | type | string | No | MIME type, that is, the type of the file to open, for example, **'text/xml'** and **'image/*'**. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. |
| flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantConstant.Flags).| | flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantconstantflags). |
| action | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details, see [action](js-apis-app-ability-wantConstant.md#wantConstant.Action). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](application-models/explicit-implicit-want-mappings.md). | | action | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details, see [action](js-apis-app-ability-wantConstant.md#wantconstantaction). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](application-models/explicit-implicit-want-mappings.md). |
| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:<br>**ohos.aafwk.callerPid**: PID of the caller.<br>**ohos.aafwk.param.callerToken**: token of the caller.<br>**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information.<br>- **component.startup.newRules**: whether to enable the new control rule.<br>- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.<br>- **ohos.dlp.params.sandbox**: available only for DLP files. | | parameters | {[key: string]: Object} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:<br>- **ohos.aafwk.callerPid**: PID of the caller.<br>**ohos.aafwk.param.callerToken**: token of the caller.<br>- **ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information.<br>- **component.startup.newRules**: whether to enable the new control rule.<br>- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.<br>- **ohos.dlp.params.sandbox**: available only for DLP files. |
| entities | Array\<string> | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want and is used to filter ability types. For details, see [entity](js-apis-app-ability-wantConstant.md#wantConstant.Entity). | | entities | Array\<string> | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want and is used to filter ability types. For details, see [entity](js-apis-app-ability-wantConstant.md#wantconstantentity). |
| moduleName<sup>9+</sup> | string | No | Module to which the ability belongs.| | moduleName<sup>9+</sup> | string | No | Module to which the ability belongs.|
**Example** **Example**
...@@ -68,4 +68,5 @@ Want is a carrier for information transfer between objects (application componen ...@@ -68,4 +68,5 @@ Want is a carrier for information transfer between objects (application componen
- For more details and examples, see [Want](../../application-models/want-overview.md). - For more details and examples, see [Want](../../application-models/want-overview.md).
<!--no_check--> <!--no_check-->
# AccessibilityExtensionContext (Accessibility Extension Context) # AccessibilityExtensionContext (Accessibility Extension Context)
The **AccessibilityExtensionContext** module, inherited from **ExtensionContext**, provides context for **Accessibility Extension** abilities. The **AccessibilityExtensionContext** module, inherited from **ExtensionContext**, provides context for **AccessibilityExtensionAbility**.
You can use the APIs of this module to configure the concerned information, obtain root information, and inject gestures. You can use the APIs of this module to configure the concerned information, obtain root information, and inject gestures.
...@@ -131,7 +131,7 @@ Sets the concerned target bundle. This API uses an asynchronous callback to retu ...@@ -131,7 +131,7 @@ Sets the concerned target bundle. This API uses an asynchronous callback to retu
let targetNames = ['com.ohos.xyz']; let targetNames = ['com.ohos.xyz'];
try { try {
axContext.setTargetBundleName(targetNames, (err, data) => { axContext.setTargetBundleName(targetNames, (err, data) => {
if (err) { if (err && err.code) {
console.error('failed to set target bundle names, because ${JSON.stringify(err)}'); console.error('failed to set target bundle names, because ${JSON.stringify(err)}');
return; return;
} }
...@@ -214,7 +214,7 @@ For details about the error codes, see [Accessibility Error Codes](../errorcodes ...@@ -214,7 +214,7 @@ For details about the error codes, see [Accessibility Error Codes](../errorcodes
let focusElement; let focusElement;
try { try {
axContext.getFocusElement((err, data) => { axContext.getFocusElement((err, data) => {
if (err) { if (err && err.code) {
console.error('failed to get focus element, because ${JSON.stringify(err)}'); console.error('failed to get focus element, because ${JSON.stringify(err)}');
return; return;
} }
...@@ -248,7 +248,7 @@ let focusElement; ...@@ -248,7 +248,7 @@ let focusElement;
let isAccessibilityFocus = true; let isAccessibilityFocus = true;
try { try {
axContext.getFocusElement(isAccessibilityFocus, (err, data) => { axContext.getFocusElement(isAccessibilityFocus, (err, data) => {
if (err) { if (err && err.code) {
console.error('failed to get focus element, because ${JSON.stringify(err)}'); console.error('failed to get focus element, because ${JSON.stringify(err)}');
return; return;
} }
...@@ -331,7 +331,7 @@ For details about the error codes, see [Accessibility Error Codes](../errorcodes ...@@ -331,7 +331,7 @@ For details about the error codes, see [Accessibility Error Codes](../errorcodes
let rootElement; let rootElement;
try { try {
axContext.getWindowRootElement((err, data) => { axContext.getWindowRootElement((err, data) => {
if (err) { if (err && err.code) {
console.error('failed to get root element of the window, because ${JSON.stringify(err)}'); console.error('failed to get root element of the window, because ${JSON.stringify(err)}');
return; return;
} }
...@@ -373,7 +373,7 @@ let rootElement; ...@@ -373,7 +373,7 @@ let rootElement;
let windowId = 10; let windowId = 10;
try { try {
axContext.getWindowRootElement(windowId, (err, data) => { axContext.getWindowRootElement(windowId, (err, data) => {
if (err) { if (err && err.code) {
console.error('failed to get root element of the window, because ${JSON.stringify(err)}'); console.error('failed to get root element of the window, because ${JSON.stringify(err)}');
return; return;
} }
...@@ -457,7 +457,7 @@ For details about the error codes, see [Accessibility Error Codes](../errorcodes ...@@ -457,7 +457,7 @@ For details about the error codes, see [Accessibility Error Codes](../errorcodes
let windows; let windows;
try { try {
axContext.getWindows((err, data) => { axContext.getWindows((err, data) => {
if (err) { if (err && err.code) {
console.error('failed to get windows, because ${JSON.stringify(err)}'); console.error('failed to get windows, because ${JSON.stringify(err)}');
return; return;
} }
...@@ -499,7 +499,7 @@ let windows; ...@@ -499,7 +499,7 @@ let windows;
let displayId = 10; let displayId = 10;
try { try {
axContext.getWindows(displayId, (err, data) => { axContext.getWindows(displayId, (err, data) => {
if (err) { if (err && err.code) {
console.error('failed to get windows, because ${JSON.stringify(err)}'); console.error('failed to get windows, because ${JSON.stringify(err)}');
return; return;
} }
...@@ -594,7 +594,7 @@ try { ...@@ -594,7 +594,7 @@ try {
gesturePath.points.push(gesturePoint); gesturePath.points.push(gesturePoint);
} }
axContext.injectGesture(gesturePath, (err, data) => { axContext.injectGesture(gesturePath, (err, data) => {
if (err) { if (err && err.code) {
console.error('failed to inject gesture, because ${JSON.stringify(err)}'); console.error('failed to inject gesture, because ${JSON.stringify(err)}');
return; return;
} }
...@@ -818,7 +818,7 @@ Performs an action based on the specified action name. This API uses a promise t ...@@ -818,7 +818,7 @@ Performs an action based on the specified action name. This API uses a promise t
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----------- | ---------------------------------------- | ---- | -------------- | | ----------- | ---------------------------------------- | ---- | -------------- |
| actionName | string | Yes | Action name. | | actionName | string | Yes | Action name. For details, see [Action](./js-apis-accessibility.md#action).
| parameters | object | No | Parameter required for performing the target action. | | parameters | object | No | Parameter required for performing the target action. |
**Return value** **Return value**
...@@ -861,7 +861,7 @@ Performs an action based on the specified action name. This API uses an asynchro ...@@ -861,7 +861,7 @@ Performs an action based on the specified action name. This API uses an asynchro
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----------- | ---------------------------------------- | ---- | -------------- | | ----------- | ---------------------------------------- | ---- | -------------- |
| actionName | string | Yes | Attribute name. | | actionName | string | Yes | Action name. For details, see [Action](./js-apis-accessibility.md#action).
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Error codes** **Error codes**
...@@ -900,7 +900,7 @@ Performs an action based on the specified action name. This API uses an asynchro ...@@ -900,7 +900,7 @@ Performs an action based on the specified action name. This API uses an asynchro
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----------- | ---------------------------------------- | ---- | -------------- | | ----------- | ---------------------------------------- | ---- | -------------- |
| actionName | string | Yes | Action name. | | actionName | string | Yes | Action name. For details, see [Action](./js-apis-accessibility.md#action).|
| parameters | object | Yes | Parameter required for performing the target action. | | parameters | object | Yes | Parameter required for performing the target action. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
The **bundle.installer** module provides APIs for you to install, uninstall, and recover bundles on devices. The **bundle.installer** module provides APIs for you to install, uninstall, and recover bundles on devices.
> **NOTE** > **NOTE**
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
...@@ -118,6 +119,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -118,6 +119,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| 17700017 | Failed to install the HAP since the version of the HAP to install is too early. | | 17700017 | Failed to install the HAP since the version of the HAP to install is too early. |
| 17700018 | Failed to install because the dependent module does not exist. | | 17700018 | Failed to install because the dependent module does not exist. |
| 17700031 | Failed to install the HAP because the overlay check of the HAP is failed. | | 17700031 | Failed to install the HAP because the overlay check of the HAP is failed. |
| 17700036 | Failed to install because without allow app shared bundle permission. |
**Example** **Example**
...@@ -164,7 +166,7 @@ Uninstalls a bundle. This API uses an asynchronous callback to return the result ...@@ -164,7 +166,7 @@ Uninstalls a bundle. This API uses an asynchronous callback to return the result
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | | ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- |
| bundleName | string | Yes | Name of the target bundle. | | bundleName | string | Yes | Name of the target bundle. |
| installParam | [InstallParam](#installparam) | Yes | Parameters required for the installation. | | installParam | [InstallParam](#installparam) | Yes | Parameters required for the uninstall. |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the operation is successful, **err** is undefined; otherwise, **err** is an error object.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the operation is successful, **err** is undefined; otherwise, **err** is an error object.|
**Error codes** **Error codes**
...@@ -204,6 +206,119 @@ try { ...@@ -204,6 +206,119 @@ try {
} }
``` ```
## BundleInstaller.uninstall<sup>10+</sup>
uninstall(uninstallParam: UninstallParam, callback : AsyncCallback\<void>) : void ;
Uninstalls a shared bundle. This API uses an asynchronous callback to return the result.
**System API**: This is a system API and cannot be called by third-party applications.
**Required permissions**: ohos.permission.INSTALL_BUNDLE
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------------- | ----------------------------------- | ---- | -------------------------------------------------------- |
| uninstallParam | [UninstallParam](#uninstallparam10) | Yes | Parameters required for the uninstall. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. If the operation is successful, **err** is undefined; otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. |
| 17700037 | The version of shared bundle is dependent on other applications. |
| 17700038 | The specified shared bundle does not exist. |
**Example**
```ts
import installer from '@ohos.bundle.installer';
let uninstallParam = {
bundleName : "com.ohos.demo",
};
try {
installer.getBundleInstaller().then(data => {
data.uninstall(uninstallParam, err => {
if (err) {
console.error('uninstall failed:' + err.message);
} else {
console.info('uninstall successfully.');
}
});
}).catch(error => {
console.error('getBundleInstaller failed. Cause: ' + error.message);
});
} catch (error) {
console.error('getBundleInstaller failed. Cause: ' + error.message);
}
```
## BundleInstaller.uninstall<sup>10+</sup>
uninstall(uninstallParam: UninstallParam) : Promise\<void>;
Uninstalls a shared bundle. This API uses a promise to return the result.
**System API**: This is a system API and cannot be called by third-party applications.
**Required permissions**: ohos.permission.INSTALL_BUNDLE
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------------- | ----------------------------------- | ---- | ---------------------------- |
| uninstallParam | [UninstallParam](#uninstallparam10) | Yes | Parameters required for the uninstall.|
**Return value**
| Type | Description |
| ------------- | -------------------------------------- |
| Promise\<void\> | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. |
| 17700037 | The version of shared bundle is dependent on other applications. |
| 17700038 | The specified shared bundle does not exist. |
**Example**
```ts
import installer from '@ohos.bundle.installer';
let uninstallParam = {
bundleName : "com.ohos.demo",
};
try {
installer.getBundleInstaller().then(data => {
data.uninstall(uninstallParam, err => {
if (err) {
console.error('uninstall failed:' + err.message);
} else {
console.info('uninstall successfully.');
}
});
}).catch(error => {
console.error('getBundleInstaller failed. Cause: ' + error.message);
});
} catch (error) {
console.error('getBundleInstaller failed. Cause: ' + error.message);
}
```
## BundleInstaller.recover ## BundleInstaller.recover
recover(bundleName: string, installParam: InstallParam, callback: AsyncCallback&lt;void&gt;): void; recover(bundleName: string, installParam: InstallParam, callback: AsyncCallback&lt;void&gt;): void;
...@@ -221,7 +336,7 @@ Recovers a bundle. This API uses an asynchronous callback to return the result. ...@@ -221,7 +336,7 @@ Recovers a bundle. This API uses an asynchronous callback to return the result.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | | ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- |
| bundleName | string | Yes | Name of the target bundle. | | bundleName | string | Yes | Name of the target bundle. |
| installParam | [InstallParam](#installparam) | Yes | Parameters required for the installation. | | installParam | [InstallParam](#installparam) | Yes | Parameters required for the recovering. |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the operation is successful, **err** is undefined; otherwise, **err** is an error object.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the operation is successful, **err** is undefined; otherwise, **err** is an error object.|
**Error codes** **Error codes**
...@@ -288,3 +403,17 @@ Defines the parameters that need to be specified for bundle installation, uninst ...@@ -288,3 +403,17 @@ Defines the parameters that need to be specified for bundle installation, uninst
| isKeepData | boolean | Yes | Whether to retain the data directory during bundle uninstall.| | isKeepData | boolean | Yes | Whether to retain the data directory during bundle uninstall.|
| hashParams | Array<[HashParam](#hashparam)> | Yes| Hash parameters. | | hashParams | Array<[HashParam](#hashparam)> | Yes| Hash parameters. |
| crowdtestDeadline| number | Yes |End date of crowdtesting.| | crowdtestDeadline| number | Yes |End date of crowdtesting.|
| sharedBundleDirPaths | Array\<String> | No|Paths of the shared bundle files.|
## UninstallParam<sup>10+</sup>
Defines the parameters required for the uninstallation of a shared bundle.
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
**System API**: This is a system API and cannot be called by third-party applications.
| Name | Type | Mandatory| Description |
| ----------- | ------ | ---- | ------------------------------------------------------------ |
| bundleName | string | Yes | Name of the shared bundle. |
| versionCode | number | No | Version number of the shared bundle. If this parameter is not set, all shared bundles of the specified name are uninstalled.|
# @ohos.intl (Internationalization) # @ohos.intl (Internationalization)
The **intl** module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n APIs defined in ECMA 402. The **intl** module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n APIs defined in ECMA 402.
The [i18n](js-apis-i18n.md) module provides enhanced i18n capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the intl module to provide a complete suite of i18n capabilities. The [i18n](js-apis-i18n.md) module provides enhanced i18n capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the intl module to provide a complete suite of i18n capabilities.
> **NOTE** > **NOTE**
......
...@@ -114,9 +114,9 @@ ethernet.setIfaceConfig("eth0", { ...@@ -114,9 +114,9 @@ ethernet.setIfaceConfig("eth0", {
dnsServers: "1.1.1.1", dnsServers: "1.1.1.1",
domain: "2.2.2.2" domain: "2.2.2.2"
}).then(() => { }).then(() => {
console.log("setIfaceConfig promiss ok "); console.log("setIfaceConfig promise ok ");
}).catch(error => { }).catch(error => {
console.log("setIfaceConfig promiss error = " + JSON.stringify(error)); console.log("setIfaceConfig promise error = " + JSON.stringify(error));
}); });
``` ```
...@@ -207,15 +207,15 @@ Obtains the configuration of a network interface. This API uses a promise to ret ...@@ -207,15 +207,15 @@ Obtains the configuration of a network interface. This API uses a promise to ret
```js ```js
ethernet.getIfaceConfig("eth0").then((data) => { ethernet.getIfaceConfig("eth0").then((data) => {
console.log("getIfaceConfig promiss mode = " + JSON.stringify(data.mode)); console.log("getIfaceConfig promise mode = " + JSON.stringify(data.mode));
console.log("getIfaceConfig promiss ipAddr = " + JSON.stringify(data.ipAddr)); console.log("getIfaceConfig promise ipAddr = " + JSON.stringify(data.ipAddr));
console.log("getIfaceConfig promiss route = " + JSON.stringify(data.route)); console.log("getIfaceConfig promise route = " + JSON.stringify(data.route));
console.log("getIfaceConfig promiss gateway = " + JSON.stringify(data.gateway)); console.log("getIfaceConfig promise gateway = " + JSON.stringify(data.gateway));
console.log("getIfaceConfig promiss netMask = " + JSON.stringify(data.netMask)); console.log("getIfaceConfig promise netMask = " + JSON.stringify(data.netMask));
console.log("getIfaceConfig promiss dnsServers = " + JSON.stringify(data.dnsServers)); console.log("getIfaceConfig promise dnsServers = " + JSON.stringify(data.dnsServers));
console.log("getIfaceConfig promiss domain = " + JSON.stringify(data.domain)); console.log("getIfaceConfig promise domain = " + JSON.stringify(data.domain));
}).catch(error => { }).catch(error => {
console.log("getIfaceConfig promiss error = " + JSON.stringify(error)); console.log("getIfaceConfig promise error = " + JSON.stringify(error));
}); });
``` ```
...@@ -300,9 +300,9 @@ Checks whether a network interface is active. This API uses a promise to return ...@@ -300,9 +300,9 @@ Checks whether a network interface is active. This API uses a promise to return
```js ```js
ethernet.isIfaceActive("eth0").then((data) => { ethernet.isIfaceActive("eth0").then((data) => {
console.log("isIfaceActive promiss = " + JSON.stringify(data)); console.log("isIfaceActive promise = " + JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log("isIfaceActive promiss error = " + JSON.stringify(error)); console.log("isIfaceActive promise error = " + JSON.stringify(error));
}); });
``` ```
...@@ -377,12 +377,12 @@ Obtains the list of all active network interfaces. This API uses a promise to re ...@@ -377,12 +377,12 @@ Obtains the list of all active network interfaces. This API uses a promise to re
```js ```js
ethernet.getAllActiveIfaces().then((data) => { ethernet.getAllActiveIfaces().then((data) => {
console.log("getAllActiveIfaces promiss data.length = " + JSON.stringify(data.length)); console.log("getAllActiveIfaces promise data.length = " + JSON.stringify(data.length));
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
console.log("getAllActiveIfaces promiss = " + JSON.stringify(data[i])); console.log("getAllActiveIfaces promise = " + JSON.stringify(data[i]));
} }
}).catch(error => { }).catch(error => {
console.log("getAllActiveIfaces promiss error = " + JSON.stringify(error)); console.log("getAllActiveIfaces promise error = " + JSON.stringify(error));
}); });
``` ```
......
# # @ohos.net.socket (Socket Connection) # Socket Connection
The **socket** module implements data transfer over TCPSocket, UDPSocket, WebSocket, and TLSSocket connections. The **socket** module implements data transfer over TCPSocket, UDPSocket, WebSocket, and TLSSocket connections.
...@@ -364,7 +364,7 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ...@@ -364,7 +364,7 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\<void\>): void setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\<void\>): void
Sets other attributes of the UDPSocket connection. This API uses an asynchronous callback to return the result. Sets other properties of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE** >**NOTE**
>This API can be called only after **bind** is successfully called. >This API can be called only after **bind** is successfully called.
...@@ -418,7 +418,7 @@ udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> { ...@@ -418,7 +418,7 @@ udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> {
setExtraOptions(options: UDPExtraOptions): Promise\<void\> setExtraOptions(options: UDPExtraOptions): Promise\<void\>
Sets other attributes of the UDPSocket connection. This API uses a promise to return the result. Sets other properties of the UDPSocket connection. This API uses a promise to return the result.
>**NOTE** >**NOTE**
>This API can be called only after **bind** is successfully called. >This API can be called only after **bind** is successfully called.
...@@ -522,7 +522,7 @@ let callback = value =>{ ...@@ -522,7 +522,7 @@ let callback = value =>{
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
} }
udp.on('message', callback); udp.on('message', callback);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
udp.off('message', callback); udp.off('message', callback);
udp.off('message'); udp.off('message');
``` ```
...@@ -582,14 +582,14 @@ let callback1 = () =>{ ...@@ -582,14 +582,14 @@ let callback1 = () =>{
console.log("on listening, success"); console.log("on listening, success");
} }
udp.on('listening', callback1); udp.on('listening', callback1);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
udp.off('listening', callback1); udp.off('listening', callback1);
udp.off('listening'); udp.off('listening');
let callback2 = () =>{ let callback2 = () =>{
console.log("on close, success"); console.log("on close, success");
} }
udp.on('close', callback2); udp.on('close', callback2);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
udp.off('close', callback2); udp.off('close', callback2);
udp.off('close'); udp.off('close');
``` ```
...@@ -646,7 +646,7 @@ let callback = err =>{ ...@@ -646,7 +646,7 @@ let callback = err =>{
console.log("on error, err:" + JSON.stringify(err)); console.log("on error, err:" + JSON.stringify(err));
} }
udp.on('error', callback); udp.on('error', callback);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
udp.off('error', callback); udp.off('error', callback);
udp.off('error'); udp.off('error');
``` ```
...@@ -1426,7 +1426,7 @@ let callback = value =>{ ...@@ -1426,7 +1426,7 @@ let callback = value =>{
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
} }
tcp.on('message', callback); tcp.on('message', callback);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
tcp.off('message', callback); tcp.off('message', callback);
tcp.off('message'); tcp.off('message');
``` ```
...@@ -1486,14 +1486,14 @@ let callback1 = () =>{ ...@@ -1486,14 +1486,14 @@ let callback1 = () =>{
console.log("on connect success"); console.log("on connect success");
} }
tcp.on('connect', callback1); tcp.on('connect', callback1);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
tcp.off('connect', callback1); tcp.off('connect', callback1);
tcp.off('connect'); tcp.off('connect');
let callback2 = () =>{ let callback2 = () =>{
console.log("on close success"); console.log("on close success");
} }
tcp.on('close', callback2); tcp.on('close', callback2);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
tcp.off('close', callback2); tcp.off('close', callback2);
tcp.off('close'); tcp.off('close');
``` ```
...@@ -1550,7 +1550,7 @@ let callback = err =>{ ...@@ -1550,7 +1550,7 @@ let callback = err =>{
console.log("on error, err:" + JSON.stringify(err)); console.log("on error, err:" + JSON.stringify(err));
} }
tcp.on('error', callback); tcp.on('error', callback);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
tcp.off('error', callback); tcp.off('error', callback);
tcp.off('error'); tcp.off('error');
``` ```
......
...@@ -46,6 +46,8 @@ battery.getStatus({ ...@@ -46,6 +46,8 @@ battery.getStatus({
Object that contains the API calling result. Object that contains the API calling result.
**System capability**: SystemCapability.PowerManager.BatteryManager.Core
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ |
| success | (data: [BatteryResponse](#batteryresponse)) => void | No | Called when API call is successful. **data** is a return value of the [BatteryResponse](#batteryresponse) type.| | success | (data: [BatteryResponse](#batteryresponse)) => void | No | Called when API call is successful. **data** is a return value of the [BatteryResponse](#batteryresponse) type.|
...@@ -56,7 +58,9 @@ Object that contains the API calling result. ...@@ -56,7 +58,9 @@ Object that contains the API calling result.
Defines a response that returns the charging status and remaining power of the device. Defines a response that returns the charging status and remaining power of the device.
| Name| Type| Description| **System capability**: SystemCapability.PowerManager.BatteryManager.Core
| -------- | -------- | -------- |
| charging | boolean | Whether the battery is being charged.| | Name| Type| Readable| Writable| Description|
| level | number | Current battery level, which ranges from **0.00** to **1.00**.| | -------- | -------- | -------- | -------- | -------- |
| charging | boolean | Yes| No| Whether the battery is being charged.|
| level | number | Yes| No| Current battery level, which ranges from **0.00** to **1.00**.|
...@@ -45,7 +45,7 @@ Obtains the current screen brightness. ...@@ -45,7 +45,7 @@ Obtains the current screen brightness.
## brightness.setValue ## brightness.setValue
etValue(options?: SetBrightnessOptions): void setValue(options?: SetBrightnessOptions): void
Sets the screen brightness. Sets the screen brightness.
...@@ -74,7 +74,7 @@ Sets the screen brightness. ...@@ -74,7 +74,7 @@ Sets the screen brightness.
## brightness.getMode ## brightness.getMode
getMode(options?: GetBrightnessModeOptions: void getMode(options?: GetBrightnessModeOptions): void
Obtains the screen brightness adjustment mode. Obtains the screen brightness adjustment mode.
...@@ -161,67 +161,81 @@ Sets whether to always keep the screen on. Call this API in **onShow()**. ...@@ -161,67 +161,81 @@ Sets whether to always keep the screen on. Call this API in **onShow()**.
Defines the options for obtaining the screen brightness. Defines the options for obtaining the screen brightness.
**System capability**: SystemCapability.PowerManager.DisplayPowerManager
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| success | (data: [BrightnessResponse](#brightnessresponse)) => void | No | Called when API call is successful. **data** is a return value of the [BrightnessResponse](#brightnessresponse) type.| | success | (data: [BrightnessResponse](#brightnessresponse)) => void | No | Called when API call is successful. **data** is a return value of the [BrightnessResponse](#brightnessresponse) type.|
| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. | | fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. |
| complete | () => void | No | Called when API call is complete. | | complete | () => void | No | Called when the API call is complete. |
## SetBrightnessOptions ## SetBrightnessOptions
Defines the options for setting the screen brightness. Defines the options for setting the screen brightness.
**System capability**: SystemCapability.PowerManager.DisplayPowerManager
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------ | ---- | ------------------------------------------------------------ |
| value | number | Yes | Screen brightness. The value is an integer ranging from **1** to **255**.<br>-&nbsp;If the value is less than or equal to **0**, value **1** will be used.<br>-&nbsp;If the value is greater than **255**, value **255** will be used.<br>-&nbsp;If the value contains decimals, the integral part of the value will be used. For example, if value **8.1** is set, value **8** will be used.| | value | number | Yes | Screen brightness. The value is an integer ranging from **1** to **255**.<br>-&nbsp;If the value is less than or equal to **0**, value **1** will be used.<br>-&nbsp;If the value is greater than **255**, value **255** will be used.<br>-&nbsp;If the value contains decimals, the integral part of the value will be used. For example, if value **8.1** is set, value **8** will be used.|
| success | () => void | No | Called when API call is successful. | | success | () => void | No | Callback upon a successful API call. |
| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. | | fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. |
| complete | () => void | No | Called when API call is complete. | | complete | () => void | No | Called when the API call is complete. |
## BrightnessResponse ## BrightnessResponse
Defines a response that returns the screen brightness. Defines a response that returns the screen brightness.
| Parameter| Type | Description| **System capability**: SystemCapability.PowerManager.DisplayPowerManager
| -------- | -------- | -------- |
| value | number | Screen brightness. The value ranges from 1 to 255.| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| value | number | Yes| No| Screen brightness. The value ranges from **1** to **255**.|
## GetBrightnessModeOptions ## GetBrightnessModeOptions
Defines the options for obtaining the screen brightness mode. Defines the options for obtaining the screen brightness mode.
**System capability**: SystemCapability.PowerManager.DisplayPowerManager
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| success | (data: [BrightnessModeResponse](#brightnessmoderesponse)) => void | No | Called when API call is successful. **data** is a return value of the [BrightnessModeResponse](#brightnessmoderesponse) type.| | success | (data: [BrightnessModeResponse](#brightnessmoderesponse)) => void | No | Called when API call is successful. **data** is a return value of the [BrightnessModeResponse](#brightnessmoderesponse) type.|
| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. | | fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. |
| complete | () => void | No | Called when API call is complete. | | complete | () => void | No | Called when the API call is complete. |
## SetBrightnessModeOptions ## SetBrightnessModeOptions
Defines the options for setting the screen brightness mode. Defines the options for setting the screen brightness mode.
**System capability**: SystemCapability.PowerManager.DisplayPowerManager
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------ | ---- | ------------------------------------------------------ | | -------- | ------------------------------------ | ---- | ------------------------------------------------------ |
| mode | number | Yes | The value **0** indicates the manual adjustment mode, and the value **1** indicates the automatic adjustment mode.| | mode | number | Yes | The value **0** indicates the manual adjustment mode, and the value **1** indicates the automatic adjustment mode.|
| success | () => void | No | Called when API call is successful. | | success | () => void | No | Callback upon a successful API call. |
| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code.| | fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code.|
| complete | () => void | No | Called when API call is complete. | | complete | () => void | No | Called when the API call is complete. |
## BrightnessModeResponse ## BrightnessModeResponse
Defines a response that returns the screen brightness mode. Defines a response that returns the screen brightness mode.
| Name| Type | Description| **System capability**: SystemCapability.PowerManager.DisplayPowerManager
| -------- | -------- | -------- |
| mode | number | The value **0** indicates the manual adjustment mode, and the value **1** indicates the automatic adjustment mode.| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| mode | number | Yes| No| The value **0** indicates the manual adjustment mode, and the value **1** indicates the automatic adjustment mode.|
## SetKeepScreenOnOptions ## SetKeepScreenOnOptions
Defines the options for setting the screen to be steady on. Defines the options for setting the screen to be steady on.
**System capability**: SystemCapability.PowerManager.DisplayPowerManager
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------ | ------------------------------------ | ---- | ------------------------------------------------------ | | ------------ | ------------------------------------ | ---- | ------------------------------------------------------ |
| keepScreenOn | boolean | Yes | The value **true** means to keep the screen steady on, and the value **false** indicates the opposite. | | keepScreenOn | boolean | Yes | The value **true** means to keep the screen steady on, and the value **false** indicates the opposite. |
| success | () => void | No | Called when API call is successful. | | success | () => void | No | Callback upon a successful API call. |
| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code.| | fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code.|
| complete | () => void | No | Called when API call is complete. | | complete | () => void | No | Called when the API call is complete. |
...@@ -16,7 +16,7 @@ import device from '@system.device'; ...@@ -16,7 +16,7 @@ import device from '@system.device';
## device.getInfo ## device.getInfo
getInfo(Object): void getInfo(options?: GetDeviceOptions): void
Obtains the device information. Obtains the device information.
...@@ -30,11 +30,25 @@ Obtains the device information. ...@@ -30,11 +30,25 @@ Obtains the device information.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| success | Function | No| Called when API call is successful.| | options | [GetDeviceOptions](#getdeviceoptions) | No| Parameters for obtaining the device information.|
| fail | Function | No| Called when API call has failed.|
| complete | Function | No| Called when API call is complete.|
**Return value of success()** ## GetDeviceOptions
Defines the parameters for obtaining the device information.
**System capability**: SystemCapability.Startup.SystemInfo
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| success | (data: DeviceResponse)=> void| No| Called when API call is successful. **data** indicates the returned device information. For details, see [DeviceResponse](#deviceresponse).|
| fail | (data: any,code:number)=> void| No| Called when API call has failed. **code** indicates the error code returned upon a failure.<br>**code:200**: Certain information could not be obtained.|
| complete | () => void| No| Called when API call is complete.|
## DeviceResponse
Provides the device information.
**System capability**: SystemCapability.Startup.SystemInfo
| Name| Type| Description| | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -49,14 +63,9 @@ Obtains the device information. ...@@ -49,14 +63,9 @@ Obtains the device information.
| screenDensity<sup>4+</sup> | number | Screen density.| | screenDensity<sup>4+</sup> | number | Screen density.|
| screenShape<sup>4+</sup> | string | Screen shape. The options are as follows:<br>- **rect**: rectangular screen<br>- **circle**: round screen| | screenShape<sup>4+</sup> | string | Screen shape. The options are as follows:<br>- **rect**: rectangular screen<br>- **circle**: round screen|
| apiVersion<sup>4+</sup> | number | API version.| | apiVersion<sup>4+</sup> | number | API version.|
| releaseType<sup>4+</sup> | string | Release type. The value includes both the release type and the API version, for example, Beta1.<br>Available release types are as follows:<br>- **Canary**: For the same API version, different canary releases are compatible with each other, but not compatible with those of the **beta** and **release** type.<br>- **Beta**: For the same API version, different beta releases are compatible with each other, but not compatible with those of the **release** type.<br>- **Release**: Releases of this type are compatible with the latest five API versions.| | releaseType<sup>4+</sup> | string | Release type. The value includes both the release type and the API version, for example, Beta1.<br>Available release types are as follows:<br>- **Canary**: Releases of this type are compatible with each other under the same API version, but not with those of the **beta** and **release** type.<br>- **Beta**: Releases of this type are compatible with each other under the same API version, but not with those of the **release** type.<br>- **Release**: Releases of this type are compatible with the latest five API versions.|
| deviceType<sup>4+</sup> | string | Device type.| | deviceType<sup>4+</sup> | string | Device type.|
**Return value of fail()**
| Error Code| Description|
| -------- | -------- |
| 200 | Certain information cannot be obtained.|
**Example** **Example**
......
# @system.fetch (Data Request) # @system.fetch (Data Request)
> **NOTE** > **NOTE**
>
> - The APIs of this module are no longer maintained since API version 6. You are advised to use [`@ohos.net.http`](js-apis-http.md) instead. > - The APIs of this module are no longer maintained since API version 6. You are advised to use [`@ohos.net.http`](js-apis-http.md) instead.
> >
> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -15,7 +14,7 @@ import fetch from '@system.fetch'; ...@@ -15,7 +14,7 @@ import fetch from '@system.fetch';
``` ```
## fetch.fetch ## fetch.fetch<sup>3+</sup>
fetch(Object): void fetch(Object): void
...@@ -31,9 +30,9 @@ Obtains data through a network. ...@@ -31,9 +30,9 @@ Obtains data through a network.
| header | Object | No| Request header.| | header | Object | No| Request header.|
| method | string | No| Request method. The default value is **GET**. The value can be **OPTIONS**, **GET**, **HEAD**, **POST**, **PUT**, **DELETE **or **TRACE**.| | method | string | No| Request method. The default value is **GET**. The value can be **OPTIONS**, **GET**, **HEAD**, **POST**, **PUT**, **DELETE **or **TRACE**.|
| responseType | string | No| Response type. The return type can be text or JSON. By default, the return type is determined based on **Content-Type** in the header returned by the server. For details, see return values in the **success** callback.| | responseType | string | No| Response type. The return type can be text or JSON. By default, the return type is determined based on **Content-Type** in the header returned by the server. For details, see return values in the **success** callback.|
| success | Function | No| Called when data is obtained successfully. The return value is [FetchResponse](#fetchresponse). | | success | Function | No| Called when the API call is successful. The return value is defined by [FetchResponse](#fetchresponse).|
| fail | Function | No| Called when data failed to be obtained.| | fail | Function | No| Called when API call has failed.|
| complete | Function | No| Called when the execution is complete.| | complete | Function | No| Called when the API call is complete.|
**Table 1** Mapping between data and Content-Type **Table 1** Mapping between data and Content-Type
...@@ -46,11 +45,11 @@ Obtains data through a network. ...@@ -46,11 +45,11 @@ Obtains data through a network.
## FetchResponse ## FetchResponse
| Name| Type| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| code | number | Server status code.| | code | number | Yes| No| Server status code.|
| data | string \| Object | The type of the returned data is determined by **responseType**. For details, see the mapping between **responseType** and **data** in **success** callback.| | data | string \| Object | Yes| No| The type of the returned data is determined by **responseType**. For details, see the mapping between **responseType** and **data** in **success** callback.|
| headers | Object | All headers in the response from the server.| | headers | Object | Yes| No| All headers in the response from the server.|
**Table 2** Mapping between responseType and data in success callback **Table 2** Mapping between responseType and data in success callback
...@@ -85,7 +84,7 @@ export default { ...@@ -85,7 +84,7 @@ export default {
``` ```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/> > **NOTE**
> HTTPS is supported by default. To support HTTP, you need to add **"network"** to the **config.json** file, and set the attribute **"cleartextTraffic"** to **true**. That is: > HTTPS is supported by default. To support HTTP, you need to add **"network"** to the **config.json** file, and set the attribute **"cleartextTraffic"** to **true**. That is:
> >
> ``` > ```
......
...@@ -21,44 +21,22 @@ ohos.permission.LOCATION ...@@ -21,44 +21,22 @@ ohos.permission.LOCATION
## geolocation.getLocation<sup>(deprecated)</sup> ## geolocation.getLocation<sup>(deprecated)</sup>
getLocation(Object): void getLocation(options?: GetLocationOption): void
Obtains the geographic location. Obtains the geographic location.
> **NOTE** > **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation).
**Required permissions**: ohos.permission.LOCATION
**System capability**: SystemCapability.Location.Location.Lite **System capability**: SystemCapability.Location.Location.Lite
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| timeout | number | No| Timeout duration, in ms. The default value is **30000**.<br>The timeout duration is necessary in case the request to obtain the geographic location is rejected for the lack of the required permission, weak positioning signal, or incorrect location settings. After the timeout duration expires, the fail function will be called.<br>The value is a 32-digit positive integer. If the specified value is less than or equal to **0**, the default value will be used.| | options | [GetLocationOption](#getlocationoptiondeprecated) | No| Options of a single location request.|
| coordType | string | No| Coordinate system type. Available types can be obtained by **getSupportedCoordTypes**. The default type is **wgs84**.|
| success | Function | No| Called when API call is successful.|
| fail | Function | No| Called when API call has failed.|
| complete | Function | No| Called when API call is complete.|
**Return value of success()**
| Name| Type| Description|
| -------- | -------- | -------- |
| longitude | number | Longitude.|
| latitude | number | Latitude.|
| altitude | number | Altitude.|
| accuracy | number | Location accuracy.|
| time | number | Time when the location is obtained.|
**Return value of fail()**
| Error Code| Description|
| -------- | -------- |
| 601 | Failed to obtain the required permission because the user rejected the request.|
| 602 | Permission not declared.|
| 800 | Operation times out due to a poor network condition or GNSS unavailability.|
| 801 | System location disabled.|
| 802 | API called again while the previous execution result is not returned yet.|
**Example** **Example**
...@@ -70,7 +48,7 @@ export default { ...@@ -70,7 +48,7 @@ export default {
console.log('success get location data. latitude:' + data.latitude); console.log('success get location data. latitude:' + data.latitude);
}, },
fail: function(data, code) { fail: function(data, code) {
console.log('fail to get location. code:' + code + ', data:' + data); console.log('fail to get location. code:' + code + ', data:' + data);
} }
}); });
} }
...@@ -80,12 +58,12 @@ export default { ...@@ -80,12 +58,12 @@ export default {
## geolocation.getLocationType<sup>(deprecated)</sup> ## geolocation.getLocationType<sup>(deprecated)</sup>
getLocationType(Object): void getLocationType(options?: GetLocationTypeOption): void
Obtains the supported location types. Obtains the supported location types.
> **NOTE** > **NOTE**
> This API is deprecated since API version 9. The location subsystem supports only two location types: GPS positioning and network positioning. No APIs will be provided to query the supported location types. > This API is deprecated since API version 9. The location subsystem supports only two location types: GNSS positioning and network positioning. No APIs will be provided to query the supported location types.
**System capability**: SystemCapability.Location.Location.Lite **System capability**: SystemCapability.Location.Location.Lite
...@@ -93,15 +71,7 @@ Obtains the supported location types. ...@@ -93,15 +71,7 @@ Obtains the supported location types.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| success | Function | No| Called when API call is successful.| | options | [GetLocationTypeOption](#getlocationtypeoptiondeprecated) | No| Callback used to return the result.|
| fail | Function | No| Called when API call has failed.|
| complete | Function | No| Called when API call is complete.|
**Return value of success()**
| Name| Type| Description|
| -------- | -------- | -------- |
| types | Array&lt;string&gt; | Available location types, ['gps', 'network']|
**Example** **Example**
...@@ -123,40 +93,22 @@ export default { ...@@ -123,40 +93,22 @@ export default {
## geolocation.subscribe<sup>(deprecated)</sup> ## geolocation.subscribe<sup>(deprecated)</sup>
subscribe(Object): void subscribe(options: SubscribeLocationOption): void
Listens to the geographic location. If this method is called multiple times, the last call takes effect. Listens to the geographic location. If this method is called multiple times, the last call takes effect.
> **NOTE** > **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('locationChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationchange). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('locationChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationchange).
**Required permissions**: ohos.permission.LOCATION
**System capability**: SystemCapability.Location.Location.Lite **System capability**: SystemCapability.Location.Location.Lite
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| coordType | string | No| Coordinate system type. Available types can be obtained by **getSupportedCoordTypes**. The default type is **wgs84**.| | options | [SubscribeLocationOption](#subscribelocationoptiondeprecated) | Yes| Options for continuous location.|
| success | Function | Yes| Called when the geographic location changes.|
| fail | Function | No| Called when API call has failed.|
**Return value of success()**
| Name| Type| Description|
| -------- | -------- | -------- |
| longitude | number | Longitude.|
| latitude | number | Latitude.|
| altitude | number | Altitude.|
| accuracy | number | Location accuracy.|
| time | number | Time when the location is obtained.|
**Return value of fail()**
| Error Code| Description|
| -------- | -------- |
| 601 | Failed to obtain the required permission because the user rejected the request.|
| 602 | Permission not declared.|
| 801 | System location disabled.|
**Example** **Example**
...@@ -185,6 +137,8 @@ Cancels listening to the geographic location. ...@@ -185,6 +137,8 @@ Cancels listening to the geographic location.
> **NOTE** > **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('locationChange')](js-apis-geoLocationManager.md#geolocationmanagerofflocationchange). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('locationChange')](js-apis-geoLocationManager.md#geolocationmanagerofflocationchange).
**Required permissions**: ohos.permission.LOCATION
**System capability**: SystemCapability.Location.Location.Lite **System capability**: SystemCapability.Location.Location.Lite
**Example** **Example**
...@@ -192,7 +146,7 @@ Cancels listening to the geographic location. ...@@ -192,7 +146,7 @@ Cancels listening to the geographic location.
``` ```
export default { export default {
unsubscribe() { unsubscribe() {
geolocation.unsubscribe(); geolocation.unsubscribe();
} }
} }
``` ```
...@@ -224,3 +178,102 @@ export default { ...@@ -224,3 +178,102 @@ export default {
}, },
} }
``` ```
## GetLocationOption<sup>(deprecated)</sup>
Defines the options of a single location request.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.CurrentLocationRequest](js-apis-geoLocationManager.md#CurrentLocationRequest).
**Required permissions**: ohos.permission.LOCATION
**System capability**: SystemCapability.Location.Location.Lite
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| timeout | number | No| Timeout duration, in ms. The default value is **30000**.<br>The timeout duration is necessary in case the request to obtain the geographic location is rejected for the lack of the required permission, weak positioning signal, or incorrect location settings. After the timeout duration expires, the fail function will be called.<br>The value is a 32-digit positive integer. If the specified value is less than or equal to **0**, the default value will be used.|
| coordType | string | No| Coordinate system type. Available types can be obtained by **getSupportedCoordTypes**. The default type is **wgs84**.|
| success | (data: [GeolocationResponse](#geolocationresponsedeprecated)) => void | No| Called when API call is successful.|
| fail | (data: string, code: number) => void | No| Called when API call has failed. **data** indicates the error information, and **code** indicates the error code.|
| complete | () => void | No| Called when API call is complete.|
**Return value of fail()**
| Error Code| Description|
| -------- | -------- |
| 601 | Failed to obtain the required permission because the user rejected the request.|
| 602 | Permission not declared.|
| 800 | Operation times out due to a poor network condition or GNSS unavailability.|
| 801 | System location disabled.|
| 802 | API called again while the previous execution result is not returned yet.|
## GeolocationResponse<sup>(deprecated)</sup>
Defines the location information, including the longitude, latitude, and location precision.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.Location](js-apis-geoLocationManager.md#location).
**System capability**: SystemCapability.Location.Location.Lite
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| longitude | number | Yes| No| Longitude.|
| latitude | number | Yes| No| Latitude.|
| altitude | number | Yes| No| Altitude.|
| accuracy | number | Yes| No| Location accuracy.|
| time | number | Yes| No| Time when the location is obtained.|
## GetLocationTypeOption<sup>(deprecated)</sup>
Defines the location type option, which holds the callback function used to return the query result.
> **NOTE**
> This API is deprecated since API version 9.
**System capability**: SystemCapability.Location.Location.Lite
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| success | (data: [GetLocationTypeResponse](#getlocationtyperesponsedeprecated)) => void | No| Called when API call is successful.|
| fail | (data: string, code: number) => void | No| Called when API call has failed.|
| complete | () => void | No| Called when API call is complete.|
## GetLocationTypeResponse<sup>(deprecated)</sup>
Defines the list of location types supported by the current device
> **NOTE**
> This API is deprecated since API version 9.
**System capability**: SystemCapability.Location.Location.Lite
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| types | Array&lt;string&gt; | Yes| No| Available location types, ['gps', 'network']|
## SubscribeLocationOption<sup>(deprecated)</sup>
Defines the options for continuous location.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.CurrentLocationRequest](js-apis-geoLocationManager.md#locationrequest).
**Required permissions**: ohos.permission.LOCATION
**System capability**: SystemCapability.Location.Location.Lite
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| coordType | string | No| Coordinate system type. Available types can be obtained by **getSupportedCoordTypes**. The default type is **wgs84**.|
| success | (data: [GeolocationResponse](#geolocationresponsedeprecated)) => void | Yes| Called when the geographic location changes.|
| fail | (data: string, code: number) => void | No| Called when API call has failed.|
**Return value of fail()**
| Error Code| Description|
| -------- | -------- |
| 601 | Failed to obtain the required permission because the user rejected the request.|
| 602 | Permission not declared.|
| 801 | System location disabled.|
# @system.network (Network State) # @system.network (Network State)
> **NOTE** > **NOTE**
> > - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.telephony.observer`](js-apis-observer.md).
> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.telephony.observer`](js-apis-observer.md) instead. >
> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -31,17 +31,17 @@ Obtains the network type. ...@@ -31,17 +31,17 @@ Obtains the network type.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| success | Function | No | Called when the execution is successful. The return value is [NetworkResponse](#networkresponse). | | success | Function | No| Called when the API call is successful. The return value is defined by [NetworkResponse](#networkresponse).|
| fail | Function | No | Called when the operation fails. | | fail | Function | No| Called when API call has failed.|
| complete | Function | No | Called when the execution is complete | | complete | Function | No| Called when the API call is complete.|
Return value of the **fail** callback: One of the following error codes will be returned if the API call has failed.
| Error Code | Description | | Error Code| Description|
| -------- | -------- | | -------- | -------- |
| 602 | The current permission is not declared. | | 602 | The current permission is not declared.|
**Example** **Example**
...@@ -71,17 +71,17 @@ Listens to the network connection state. If this method is called multiple times ...@@ -71,17 +71,17 @@ Listens to the network connection state. If this method is called multiple times
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| success | Function | No | Called when the network connection state changes | | success | Function | No| Called when the network state changes. The return value is defined by [NetworkResponse](#networkresponse).|
| fail | Function | No | Called when the multimedia volume fails to be obtained. | | fail | Function | No| Called when API call has failed.|
Return value of the **fail** callback: One of the following error codes will be returned if the API call has failed.
| Error Code | Description | | Error Code| Description|
| -------- | -------- | | -------- | -------- |
| 602 | The current permission is not declared. | | 602 | The current permission is not declared.|
| 200 | The subscription fails. | | 200 | Subscription failed.|
**Example** **Example**
...@@ -119,9 +119,12 @@ export default { ...@@ -119,9 +119,12 @@ export default {
} }
``` ```
## NetworkResponse ## NetworkResponse
| Parameter | Type | Description | **System capability**: SystemCapability.Communication.NetManager.Core
| -------- | -------- | -------- |
| metered | boolean | Whether the billing is based on the data volume. | | Name| Type| Mandatory| Description|
| type | string | Network type. The value can be **2G**, **3G**, **4G**, **5G**, **WiFi**, or **none**. | | -------- | -------- | -------- | -------- |
\ No newline at end of file | metered | boolean | No|Whether to charge by traffic.|
| type | string | Yes|Network type. The value can be **2G**, **3G**, **4G**, **5G**, **WiFi**, or **none**.|
...@@ -8,8 +8,10 @@ There are two types of updates: SD card update and over the air (OTA) update. ...@@ -8,8 +8,10 @@ There are two types of updates: SD card update and over the air (OTA) update.
- 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. - 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** > **NOTE**
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. >
> - The APIs provided by this module are system APIs. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The APIs provided by this module are system APIs.
## Modules to Import ## Modules to Import
...@@ -2034,7 +2036,7 @@ Enumerates update states. ...@@ -2034,7 +2036,7 @@ Enumerates update states.
| WAITING_INSTALL | 30 | Waiting for installation. | | WAITING_INSTALL | 30 | Waiting for installation. |
| UPDATING | 31 | Updating. | | UPDATING | 31 | Updating. |
| WAITING_APPLY | 40 | Waiting for applying the update. | | WAITING_APPLY | 40 | Waiting for applying the update. |
| APPLYING | 21 | Applying the update. | | APPLYING | 41 | Applying the update. |
| UPGRADE_SUCCESS | 50 | Update succeeded.| | UPGRADE_SUCCESS | 50 | Update succeeded.|
| UPGRADE_FAIL | 51 | Update failed.| | UPGRADE_FAIL | 51 | Update failed.|
...@@ -2056,7 +2058,7 @@ Enumerates event IDs. ...@@ -2056,7 +2058,7 @@ Enumerates event IDs.
| Name | Value | Description | | Name | Value | Description |
| ---------------------- | ---------- | ------ | | ---------------------- | ---------- | ------ |
| EVENT_TASK_BASE | 0x01000000 | Task event. | | EVENT_TASK_BASE | EventClassify.TASK | Task event. |
| EVENT_TASK_RECEIVE | 0x01000001 | Task received. | | EVENT_TASK_RECEIVE | 0x01000001 | Task received. |
| EVENT_TASK_CANCEL | 0x01000010 | Task cancelled. | | EVENT_TASK_CANCEL | 0x01000010 | Task cancelled. |
| EVENT_DOWNLOAD_WAIT | 0x01000011 | Waiting for download. | | EVENT_DOWNLOAD_WAIT | 0x01000011 | Waiting for download. |
......
# @ohos.usbManager (USB Management) # @ohos.usbManager (USB Manager)
The **usbManager** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as port management, and function switch and query on the device side. The **usbManager** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as port management, and function switch and query on the device side.
...@@ -30,7 +30,7 @@ Obtains the list of USB devices connected to the host. If no device is connected ...@@ -30,7 +30,7 @@ Obtains the list of USB devices connected to the host. If no device is connected
```js ```js
let devicesList = usb.getDevices(); let devicesList = usb.getDevices();
console.log(`devicesList = ${JSON.stringify(devicesList)}`); console.log(`devicesList = ${devicesList}`);
// devicesList is a list of USB devices. // devicesList is a list of USB devices.
// A simple example of devicesList is provided as follows: // A simple example of devicesList is provided as follows:
[ [
...@@ -119,13 +119,12 @@ For details about the error codes, see [USB Error Codes](../errorcodes/errorcode ...@@ -119,13 +119,12 @@ For details about the error codes, see [USB Error Codes](../errorcodes/errorcode
let devicesList = usb.getDevices(); let devicesList = usb.getDevices();
if (devicesList.length == 0) { if (devicesList.length == 0) {
console.log(`device list is empty`); console.log(`device list is empty`);
return;
} }
let device = devicesList[0]; let device = devicesList[0];
usb.requestRight(device.name); usb.requestRight(device.name);
let devicepipe = usb.connectDevice(device); let devicepipe = usb.connectDevice(device);
console.log(`devicepipe = ${JSON.stringify(devicepipe)}`); console.log(`devicepipe = ${devicepipe}`);
``` ```
## usb.hasRight ## usb.hasRight
...@@ -155,7 +154,7 @@ Checks whether the user, for example, the application or system, has the device ...@@ -155,7 +154,7 @@ Checks whether the user, for example, the application or system, has the device
```js ```js
let devicesName="1-1"; let devicesName="1-1";
let bool = usb.hasRight(devicesName); let bool = usb.hasRight(devicesName);
console.log(bool); console.log(`${bool}`);
``` ```
## usb.requestRight ## usb.requestRight
...@@ -183,7 +182,7 @@ Requests the temporary permission for the application to access a USB device. Th ...@@ -183,7 +182,7 @@ Requests the temporary permission for the application to access a USB device. Th
```js ```js
let devicesName="1-1"; let devicesName="1-1";
usb.requestRight(devicesName).then((ret) => { usb.requestRight(devicesName).then((ret) => {
console.log(`requestRight = ${JSON.stringify(ret)}`); console.log(`requestRight = ${ret}`);
}); });
``` ```
...@@ -211,7 +210,7 @@ Removes the permission for the application to access a USB device. ...@@ -211,7 +210,7 @@ Removes the permission for the application to access a USB device.
```js ```js
let devicesName="1-1"; let devicesName="1-1";
if (usb.removeRight(devicesName) { if usb.removeRight(devicesName) {
console.log(`Succeed in removing right`); console.log(`Succeed in removing right`);
} }
``` ```
...@@ -246,7 +245,7 @@ Adds the permission for the application to access a USB device. ...@@ -246,7 +245,7 @@ Adds the permission for the application to access a USB device.
```js ```js
let devicesName = "1-1"; let devicesName = "1-1";
let bundleName = "com.example.hello"; let bundleName = "com.example.hello";
if (usb.addRight(bundleName, devicesName) { if usb.addRight(bundleName, devicesName) {
console.log(`Succeed in adding right`); console.log(`Succeed in adding right`);
} }
``` ```
...@@ -455,8 +454,9 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ...@@ -455,8 +454,9 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
**Example** **Example**
```js ```js
usb.controlTransfer(devicepipe, USBControlParams).then((ret) => { let param = new usb.USBControlParams();
console.log(`controlTransfer = ${JSON.stringify(ret)}`); usb.controlTransfer(devicepipe, param).then((ret) => {
console.log(`controlTransfer = ${ret}`);
}) })
``` ```
...@@ -492,7 +492,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ...@@ -492,7 +492,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
// Pass the obtained USB device as a parameter to usb.connectDevice. Then, call usb.connectDevice to connect the USB device. // Pass the obtained USB device as a parameter to usb.connectDevice. Then, call usb.connectDevice to connect the USB device.
// Call usb.claimInterface to claim the USB interface. After that, call usb.bulkTransfer to start bulk transfer. // Call usb.claimInterface to claim the USB interface. After that, call usb.bulkTransfer to start bulk transfer.
usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => { usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => {
console.log(`bulkTransfer = ${JSON.stringify(ret)}`); console.log(`bulkTransfer = ${ret}`);
}); });
``` ```
...@@ -579,7 +579,7 @@ Converts the USB function list in the numeric mask format to a string in Device ...@@ -579,7 +579,7 @@ Converts the USB function list in the numeric mask format to a string in Device
**Example** **Example**
```js ```js
let funcs = ACM | ECM; let funcs = usb.ACM | usb.ECM;
let ret = usb.usbFunctionsToString(funcs); let ret = usb.usbFunctionsToString(funcs);
``` ```
...@@ -608,7 +608,7 @@ Sets the current USB function list in Device mode. ...@@ -608,7 +608,7 @@ Sets the current USB function list in Device mode.
**Example** **Example**
```js ```js
let funcs = HDC; let funcs = usb.HDC;
usb.setCurrentFunctions(funcs).then(() => { usb.setCurrentFunctions(funcs).then(() => {
console.info('usb setCurrentFunctions successfully.'); console.info('usb setCurrentFunctions successfully.');
}).catch(err => { }).catch(err => {
...@@ -716,7 +716,7 @@ Sets the role types supported by a specified port, which can be **powerRole** (f ...@@ -716,7 +716,7 @@ Sets the role types supported by a specified port, which can be **powerRole** (f
```js ```js
let portId = 1; let portId = 1;
usb.usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => { usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => {
console.info('usb setPortRoles successfully.'); console.info('usb setPortRoles successfully.');
}).catch(err => { }).catch(err => {
console.error('usb setPortRoles failed: ' + err.code + ' message: ' + err.message); console.error('usb setPortRoles failed: ' + err.code + ' message: ' + err.message);
......
...@@ -15,6 +15,7 @@ This error code is reported if the **write** API is called to perform applicatio ...@@ -15,6 +15,7 @@ This error code is reported if the **write** API is called to perform applicatio
The application event logging function is disabled. The application event logging function is disabled.
**Solution** **Solution**
Invoke the **configure** API to enable the application event logging function. Invoke the **configure** API to enable the application event logging function.
```js ```js
...@@ -41,6 +42,7 @@ The specified event domain name does not comply with the following rules: ...@@ -41,6 +42,7 @@ The specified event domain name does not comply with the following rules:
- The event domain name is not empty and contains a maximum of 32 characters. - The event domain name is not empty and contains a maximum of 32 characters.
**Solution** **Solution**
Specify a valid event domain name. Specify a valid event domain name.
## 11101002 Invalid Event Name ## 11101002 Invalid Event Name
......
# Socket Error Codes # Socket Error Codes
> **NOTE**
>
> The following describes only the error codes specific to the **socket** module. For details about common error codes, see [Common Error Codes](errorcode-universal.md) file.
## 2301001 Operation Not Allowed ## 2301001 Operation Not Allowed
**Error Message** **Error Message**
......
# SystemCapability List # SystemCapability List
SysCap, short for System Capability, refers to a standalone feature in the OpenHarmony system. SystemCapability (SysCap) is a standalone feature in the OpenHarmony system.
Before using an API for development, you are advised to familiarize yourself with [SysCap](syscap.md), and then consult the following tables to see whether the SysCap set required for the API is supported by the target device type. Before using an API for development, you are advised to familiarize yourself with [SysCap](syscap.md), and then consult the following tables to see whether the SysCap set required for the API is supported by the target device type.
...@@ -172,14 +172,6 @@ Basic network management services ...@@ -172,14 +172,6 @@ Basic network management services
| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ |
| Yes | No | Yes | Yes | Yes | Yes | No | No | | Yes | No | Yes | Yes | Yes | Yes | No | No |
## SystemCapability.Communication.NetManager.Extension
Extended network management services
| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router |
| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ |
| Yes | No | No | Yes | Yes | Yes | No | No |
## SystemCapability.Communication.NetStack ## SystemCapability.Communication.NetStack
Basic network stack capability Basic network stack capability
...@@ -315,14 +307,6 @@ Input device management ...@@ -315,14 +307,6 @@ Input device management
| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ |
| Yes | No | No | Yes | Yes | Yes | No | No | | Yes | No | No | Yes | Yes | Yes | No | No |
## SystemCapability.MultimodalInput.Input.RemoteInputDevice
Distributed input device management
| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router |
| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ |
| Yes | No | No | Yes | Yes | Yes | No | No |
## SystemCapability.MultimodalInput.Input.InputMonitor ## SystemCapability.MultimodalInput.Input.InputMonitor
Input event listener Input event listener
...@@ -347,14 +331,6 @@ Input event simulator ...@@ -347,14 +331,6 @@ Input event simulator
| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ |
| Yes | No | No | Yes | Yes | Yes | No | No | | Yes | No | No | Yes | Yes | Yes | No | No |
## SystemCapability.MultimodalInput.Input.InputFilter
Input event filter
| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router |
| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ |
| Yes | No | No | Yes | Yes | Yes | No | No |
## SystemCapability.PowerManager.BatteryManager.Extension ## SystemCapability.PowerManager.BatteryManager.Extension
Battery manager extension capability Battery manager extension capability
...@@ -453,7 +429,7 @@ Media audio recorder capability ...@@ -453,7 +429,7 @@ Media audio recorder capability
## SystemCapability.Multimedia.Media.VideoPlayer ## SystemCapability.Multimedia.Media.VideoPlayer
Media video player capability Video player capability
| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | | Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router |
| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ |
...@@ -1347,7 +1323,7 @@ Contacts ...@@ -1347,7 +1323,7 @@ Contacts
| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ |
| Yes | No | Yes | Yes | Yes | No | No | No | | Yes | No | Yes | Yes | Yes | No | No | No |
## SystemCapability.Applictaions.settings.Core ## SystemCapability.Applications.settings.Core
API setting API setting
...@@ -1658,3 +1634,35 @@ Quick fix ...@@ -1658,3 +1634,35 @@ Quick fix
| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | | Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router |
| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ |
| Yes | No | Yes | Yes | Yes | Yes | No | No | | Yes | No | Yes | Yes | Yes | Yes | No | No |
## SystemCapability.MultimodalInput.Input.Pointer
Pointer input enhancement
| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router |
| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ |
| Yes | No | No | Yes | Yes | Yes | No | No |
## SystemCapability.Communication.SecureElement
Secure element access
| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router |
| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ |
| No | No | No | No | No | No | No | No |
## SystemCapability.Msdp.DeviceStatus.Stationarty
Device status awareness
| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router |
| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ |
| Yes | No | No | Yes | Yes | Yes | No | No |
## SystemCapability.Base
General type
| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router |
| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ |
| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
...@@ -109,3 +109,6 @@ ...@@ -109,3 +109,6 @@
- [bytrace](subsys-toolchain-bytrace-guide.md) - [bytrace](subsys-toolchain-bytrace-guide.md)
- [hdc](subsys-toolchain-hdc-guide.md) - [hdc](subsys-toolchain-hdc-guide.md)
- [hiperf](subsys-toolchain-hiperf.md) - [hiperf](subsys-toolchain-hiperf.md)
- Power Management
- Display Management
- [System Brightness Customization](subsys-power-brightness-customization.md)
...@@ -36,7 +36,7 @@ The AI subsystem is the part of OpenHarmony that provides native distributed AI ...@@ -36,7 +36,7 @@ The AI subsystem is the part of OpenHarmony that provides native distributed AI
* **Programming language**: C/C++ * **Programming language**: C/C++
* **Operating system**: OpenHarmony * **Operating system**: OpenHarmony mini- and small-system
* **Others**: The System Ability Manager \(Samgr\) has been started and is running properly. * **Others**: The System Ability Manager \(Samgr\) has been started and is running properly.
...@@ -314,9 +314,7 @@ The AI subsystem is the part of OpenHarmony that provides native distributed AI ...@@ -314,9 +314,7 @@ The AI subsystem is the part of OpenHarmony that provides native distributed AI
} }
``` ```
4. Develop a sample application. For details, see the [keyword spotting demo](https://gitee.com/openharmony/applications_sample_camera/tree/master/ai). 4. Develop a sample application.
Directory: //applications/sample/camera/ai/asr/keyword\_spotting
Call the **Create** API. Call the **Create** API.
......
此差异已折叠。
# 接口 # 接口
- [开发说明](development-intro.md) - [开发说明](development-intro.md)
...@@ -231,8 +231,6 @@ ...@@ -231,8 +231,6 @@
- [@ohos.data.preferences (首选项)](js-apis-data-preferences.md) - [@ohos.data.preferences (首选项)](js-apis-data-preferences.md)
- [@ohos.data.relationalStore (关系型数据库)](js-apis-data-relationalStore.md) - [@ohos.data.relationalStore (关系型数据库)](js-apis-data-relationalStore.md)
- [@ohos.data.ValuesBucket (数据集)](js-apis-data-valuesBucket.md) - [@ohos.data.ValuesBucket (数据集)](js-apis-data-valuesBucket.md)
- data/rdb
- [resultSet (结果集)](js-apis-data-resultset.md)
- 文件管理 - 文件管理
- [@ohos.file.environment (目录环境能力)](js-apis-file-environment.md) - [@ohos.file.environment (目录环境能力)](js-apis-file-environment.md)
...@@ -445,3 +443,5 @@ ...@@ -445,3 +443,5 @@
- [PermissionDef](js-apis-bundle-PermissionDef.md) - [PermissionDef](js-apis-bundle-PermissionDef.md)
- [remoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md) - [remoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)
- [shortcutInfo](js-apis-bundle-ShortcutInfo.md) - [shortcutInfo](js-apis-bundle-ShortcutInfo.md)
- data/rdb
- [resultSet (结果集)](js-apis-data-resultset.md)
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册