未验证 提交 c3102a91 编写于 作者: O openharmony_ci 提交者: Gitee

!16136 翻译已完成14820+15389+15381+15317+15707+15636+15620+15857+15837

Merge pull request !16136 from shawn_he/14820-b
# 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)
# Socket Connection # Socket Connection
## Introduction
## Use Cases The Socket Connection module allows an application to transmit data over a Socket connection through the TCP, UDP, or TLS protocol.
Your application can transmit data through Socket connections. Currently, the TCP and UDP protocols are supported. ## Basic Concepts
- Socket: An abstraction of endpoints for bidirectional communication between application processes running on different hosts in a network.
- TCP: Transmission Control Protocol, which is a byte stream–based transport layer communication protocol that is connection-oriented and reliable.
- UDP: User Datagram Protocol, which is a simple datagram-oriented transport layer communication protocol.
- TLS: Transport Layer Security, which is a protocol that ensures the data confidentiality and integrity between communication programs.
## When to Use
Applications transmit data over TCP, UDP, or TLS Socket connections. The main application scenarios are as follows:
- Implementing data transmission over TCP/UDP Socket connections
- Implementing encrypted data transmission over TLS Socket connections
## Available APIs ## Available APIs
The Socket connection function is mainly implemented by the Socket module. The following table describes the related APIs. For the complete list of APIs and example code, see [Socket Connection](../reference/apis/js-apis-socket.md).
Socket connection functions are mainly implemented by the **socket** module. The following table describes the related APIs.
| API| Description | | API| Description|
| -------- | -------- | | -------- | -------- |
| constructUDPSocketInstance() | Creates a **UDPSocket** object. | | constructUDPSocketInstance() | Creates a **UDPSocket** object.|
| constructTCPSocketInstance() | Creates a **TCPSocket** object. | | constructTCPSocketInstance() | Creates a **TCPSocket** object.|
| bind() | Binds the IP address and port number. | | bind() | Binds the IP address and port number.|
| send() | Sends data.| | send() | Sends data.|
| close() | Closes a Socket connection. | | close() | Closes a Socket connection.|
| getState() | Obtains the Socket connection status. | | getState() | Obtains the Socket connection status.|
| connect() | Connects to the specified IP address and port. This function is supported only for TCP. | | connect() | Connects to the specified IP address and port. This function is supported only for TCP.|
| getRemoteAddress() | Obtains the peer address of the Socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API. | | getRemoteAddress() | Obtains the peer address of the Socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API.|
| on(type:&nbsp;'message') | Enables listening for **message** events of the Socket connection. | | on(type:&nbsp;'message') | Subscribes to **message** events of the Socket connection.|
| off(type:&nbsp;'message') | Disables listening for **message** events of the Socket connection. | | off(type:&nbsp;'message') | Unsubscribes from **message** events of the Socket connection.|
| on(type:&nbsp;'close') | Enables listening for **close** events of the Socket connection. | | on(type:&nbsp;'close') | Subscribes to **close** events of the Socket connection.|
| off(type:&nbsp;'close') | Disables listening for **close** events of the Socket connection. | | off(type:&nbsp;'close') | Unsubscribes from **close** events of the Socket connection.|
| on(type:&nbsp;'error') | Enables listening for **error** events of the Socket connection. | | on(type:&nbsp;'error') | Subscribes to **error** events of the Socket connection.|
| off(type:&nbsp;'error') | Disables listening for **error** events of the Socket connection. | | off(type:&nbsp;'error') | Unsubscribes from **error** events of the Socket connection.|
| on(type:&nbsp;'listening') | Enables listening for **listening** events of the UDPSocket connection. | | on(type:&nbsp;'listening') | Subscribes to **listening** events of the UDP Socket connection. |
| off(type:&nbsp;'listening') | Disables listening for **listening** events of the UDPSocket connection. | | off(type:&nbsp;'listening') | Unsubscribes from **listening** events of the UDP Socket connection. |
| on(type:&nbsp;'connect') | Enables listening for **connect** events of the TCPSocket connection. | | on(type:&nbsp;'connect') | Subscribes to **connect** events of the TCP Socket connection. |
| off(type:&nbsp;'connect') | Disables listening for **connect** events of the TCPSocket connection. | | off(type:&nbsp;'connect') | Unsubscribes from **connect** events of the TCP Socket connection.|
TLS Socket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs.
| API| Description|
| -------- | -------- |
| constructTLSSocketInstance() | Creates a **TLSSocket** object.|
| bind() | Binds the IP address and port number.|
| close(type:&nbsp;'error') | Closes a Socket connection.|
| connect() | Sets up a connection to the specified IP address and port number.|
| getCertificate() | Obtains an object representing the local certificate.|
| getCipherSuite() | Obtains a list containing information about the negotiated cipher suite.|
| getProtocol() | Obtains a string containing the SSL/TLS protocol version negotiated for the current connection.|
| getRemoteAddress() | Obtains the peer address of the TLS Socket connection.|
| getRemoteCertificate() | Obtains an object representing a peer certificate.|
| getSignatureAlgorithms() | Obtains a list containing signature algorithms shared between the server and client, in descending order of priority.|
| getState() | Obtains the TLS Socket connection status.|
| off(type:&nbsp;'close') | Unsubscribes from **close** events of the TLS Socket connection.|
| off(type:&nbsp;'error') | Unsubscribes from **error** events of the TLS Socket connection.|
| off(type:&nbsp;'message') | Unsubscribes from **message** events of the TLS Socket connection.|
| on(type:&nbsp;'close') | Subscribes to **close** events of the TLS Socket connection.|
| on(type:&nbsp;'error') | Subscribes to **error** events of the TLS Socket connection.|
| on(type:&nbsp;'message') | Subscribes to **message** events of the TLS Socket connection.|
| send() | Sends data.|
| setExtraOptions() | Sets other properties of the TLS Socket connection.|
## How to Develop ## Transmitting Data over TCP/UDP Socket Connections
The implementation is similar for UDPSocket and TCPSocket. The following uses the TCPSocket as an example. The implementation is similar for UDP Socket and TCP Socket connections. The following uses data transmission over a TCP Socket connection as an example.
1. Import the required Socket module. 1. Import the required **socket** module.
2. Create a **TCPSocket** object. 2. Create a **TCPSocket** object.
3. (Optional) Enable listening for TCPSocket events. 3. (Optional) Subscribe to TCP Socket connection events.
4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system. 4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system.
...@@ -48,15 +85,15 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -48,15 +85,15 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
6. Send data. 6. Send data.
7. Enable the TCPSocket connection to be automatically closed after use. 7. Enable the TCP Socket connection to be automatically closed after use.
```js ```js
import socket from '@ohos.net.socket' import socket from '@ohos.net.socket'
// Create a TCPSocket object. // Create a TCPSocket object.
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
// Enable listening for TCPSocket events. // Subscribe to TCP Socket connection events.
tcp.on('message', value => { tcp.on('message', value => {
console.log("on message") console.log("on message")
let buffer = value.message let buffer = value.message
...@@ -73,7 +110,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -73,7 +110,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
tcp.on('close', () => { tcp.on('close', () => {
console.log("on close") console.log("on close")
}); });
// Bind the local IP address and port number. // Bind the local IP address and port number.
let bindAddress = { let bindAddress = {
address: '192.168.xx.xx', address: '192.168.xx.xx',
...@@ -86,6 +123,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -86,6 +123,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
return; return;
} }
console.log('bind success'); console.log('bind success');
// Set up a connection to the specified IP address and port number. // Set up a connection to the specified IP address and port number.
let connectAddress = { let connectAddress = {
address: '192.168.xx.xx', address: '192.168.xx.xx',
...@@ -100,6 +138,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -100,6 +138,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
return; return;
} }
console.log('connect success'); console.log('connect success');
// Send data. // Send data.
tcp.send({ tcp.send({
data: 'Hello, server!' data: 'Hello, server!'
...@@ -112,7 +151,8 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -112,7 +151,8 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
}) })
}); });
}); });
// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket events.
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
setTimeout(() => { setTimeout(() => {
tcp.close((err) => { tcp.close((err) => {
console.log('close socket.') console.log('close socket.')
...@@ -122,3 +162,167 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -122,3 +162,167 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
tcp.off('close'); tcp.off('close');
}, 30 * 1000); }, 30 * 1000);
``` ```
## Implementing Encrypted Data Transmission over TLS Socket Connections
### How to Develop
TLS Socket connection process on the client:
1. Import the required **socket** module.
2. Bind the IP address and port number of the server.
3. For two-way authentication, upload the client CA certificate and digital certificate. For one-way authentication, upload the client CA certificate.
4. Create a **TLSSocket** object.
5. (Optional) Subscribe to TLS Socket connection events.
6. Send data.
7. Enable the TLS Socket connection to be automatically closed after use.
```js
import socket from '@ohos.net.socket'
// Create a TLS Socket connection (for two-way authentication).
let tlsTwoWay = socket.constructTLSSocketInstance();
// Subscribe to TLS Socket connection events.
tcp.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0; i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log("on connect received:" + str)
});
tcp.on('connect', () => {
console.log("on connect")
});
tcp.on('close', () => {
console.log("on close")
});
// Bind the local IP address and port number.
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
// Set the communication parameters.
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
// Set up a connection to the specified IP address and port number.
address: {
address: "192.168.xx.xxx",
port: xxxx, // Port
family: 1,
},
// Set the parameters used for authentication during communication.
secureOptions: {
key: "xxxx", // Key
cert: "xxxx", // Digital certificate
ca: ["xxxx"], // CA certificate
passwd: "xxxx", // Password for generating the key
protocols: [socket.Protocol.TLSv12], // Communication protocol
useRemoteCipherPrefer: true, // Whether to preferentially use the peer cipher suite
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // Signature algorithm
cipherSuite: "AES256-SHA256", // Cipher suite
},
};
// Set up a connection.
tlsTwoWay.connect(options, (err, data) => {
console.error(err);
console.log(data);
});
// Enable the TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events.
tls.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
tls.off('message');
tls.off('connect');
tls.off('close');
});
// Create a TLS Socket connection (for one-way authentication).
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
// Subscribe to TLS Socket connection events.
tcp.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0;i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log("on connect received:" + str)
});
tcp.on('connect', () => {
console.log("on connect")
});
tcp.on('close', () => {
console.log("on close")
});
// Bind the local IP address and port number.
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
// Set the communication parameters.
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"], // CA certificate
cipherSuite: "AES256-SHA256", // Cipher suite
},
};
// Set up a connection.
tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err);
console.log(data);
});
// Enable the TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events.
tls.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
tls.off('message');
tls.off('connect');
tls.off('close');
});
```
## Samples
The following samples are provided to help you better understand how to develop Socket connection features:
- [`Socket`: Socket Connection (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket)
- [UDP Socket (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/UdpDemoOH)
- [TCP Socket (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/TcpSocketDemo)
...@@ -77,43 +77,48 @@ When designing a color picker, you can have the mouse pointer switched to the co ...@@ -77,43 +77,48 @@ When designing a color picker, you can have the mouse pointer switched to the co
5. Set the mouse pointer to the default style. 5. Set the mouse pointer to the default style.
```js ```js
import pointer from '@ohos.multimodalInput.pointer';
import window from '@ohos.window'; import window from '@ohos.window';
// 1. Enable the color pickup function. // 1. Enable the color pickup function.
// 2. Obtain the window ID. // 2. Obtain the window ID.
window.getTopWindow((error, windowClass) => { window.getLastWindow(this.context, (error, windowClass) => {
windowClass.getProperties((error, data) => { if (error.code) {
var windowId = data.id; console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
if (windowId < 0) { return;
console.log(`Invalid windowId`); }
return; var windowId = windowClass.getWindowProperties().id;
} if (windowId < 0) {
try { console.log(`Invalid windowId`);
// 3. Set the mouse pointer to the color picker style. return;
pointer.setPointerStyle(windowId, pointer.PointerStyle.COLOR_SUCKER).then(() => { }
console.log(`Successfully set mouse pointer style`); try {
}); // 3. Set the mouse pointer to the color picker style.
} catch (error) { pointer.setPointerStyle(windowId, pointer.PointerStyle.COLOR_SUCKER).then(() => {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(message)}`); console.log(`Successfully set mouse pointer style`);
} });
}); } catch (error) {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(`message`)}`);
}
}); });
// 4. End color pickup. // 4. End color pickup.
window.getTopWindow((error, windowClass) => { window.getLastWindow(this.context, (error, windowClass) => {
windowClass.getProperties((error, data) => { if (error.code) {
var windowId = data.id; console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
if (windowId < 0) { return;
console.log(`Invalid windowId`); }
return; var windowId = windowClass.getWindowProperties().id;
} if (windowId < 0) {
try { console.log(`Invalid windowId`);
// 5. Set the mouse pointer to the default style. return;
pointer.setPointerStyle(windowId, pointer.PointerStyle.DEFAULT).then(() => { }
console.log(`Successfully set mouse pointer style`); try {
}); // 5. Set the mouse pointer to the default style.
} catch (error) { pointer.setPointerStyle(windowId, pointer.PointerStyle.DEFAULT).then(() => {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(message)}`); console.log(`Successfully set mouse pointer style`);
} });
}); } catch (error) {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(`message`)}`);
}
}); });
``` ```
...@@ -12,11 +12,11 @@ Application error management APIs are provided by the **errorManager** module. F ...@@ -12,11 +12,11 @@ Application error management APIs are provided by the **errorManager** module. F
| API | Description | | API | Description |
| ------------------------------------------------------------ | ---------------------------------------------------- | | ------------------------------------------------------------ | ---------------------------------------------------- |
| registerErrorObserver(observer: ErrorObserver): number | Registers an observer for application errors. A callback will be invoked when an application error is detected. This API works in a synchronous manner. The return value is the SN of the registered observer.| | on(type: "error", observer: ErrorObserver): number | Registers an observer for application errors. A callback will be invoked when an application error is detected. This API works in a synchronous manner. The return value is the SN of the registered observer.|
| unregisterErrorObserver(observerId: number, callback: AsyncCallback\<void\>): void | Unregisters an observer in callback mode. The number passed to this API is the SN of the registered observer. | | off(type: "error", observerId: number, callback: AsyncCallback\<void\>): void | Unregisters an observer in callback mode. The number passed to this API is the SN of the registered observer. |
| unregisterErrorObserver(observerId: number): Promise\<void\> | Unregisters an observer in promise mode. The number passed to this API is the SN of the registered observer. | | off(type: "error", observerId: number): Promise\<void\> | Unregisters an observer in promise mode. The number passed to this API is the SN of the registered observer. |
When an asynchronous callback is used, the return value can be processed directly in the callback. If a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Result Codes for Unregistering an Observer](#result-codes-for-unregistering-an-observer). When an asynchronous callback is used, the return value can be processed directly in the callback. If a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Result Codes for Unregistering an Observer](#result codes-for-unregistering-an-observer).
**Table 2** Description of the ErrorObserver API **Table 2** Description of the ErrorObserver API
...@@ -36,7 +36,7 @@ When an asynchronous callback is used, the return value can be processed directl ...@@ -36,7 +36,7 @@ When an asynchronous callback is used, the return value can be processed directl
## Development Example ## Development Example
```ts ```ts
import Ability from '@ohos.application.Ability' import UIAbility from '@ohos.app.ability.UIAbility';
import errorManager from '@ohos.app.ability.errorManager'; import errorManager from '@ohos.app.ability.errorManager';
let registerId = -1; let registerId = -1;
...@@ -45,15 +45,16 @@ let callback = { ...@@ -45,15 +45,16 @@ let callback = {
console.log(errMsg); console.log(errMsg);
} }
} }
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate") console.log("[Demo] EntryAbility onCreate")
registerId = errorManager.on("error", callback); registerId = errorManager.on("error", callback);
globalThis.abilityWant = want; globalThis.abilityWant = want;
} }
onDestroy() { onDestroy() {
console.log("[Demo] MainAbility onDestroy") console.log("[Demo] EntryAbility onDestroy")
errorManager.off("error", registerId, (result) => { errorManager.off("error", registerId, (result) => {
console.log("[Demo] result " + result.code + ";" + result.message) console.log("[Demo] result " + result.code + ";" + result.message)
}); });
...@@ -61,7 +62,7 @@ export default class MainAbility extends Ability { ...@@ -61,7 +62,7 @@ export default class MainAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
// Main window is created for this ability. // Main window is created for this ability.
console.log("[Demo] MainAbility onWindowStageCreate") console.log("[Demo] EntryAbility onWindowStageCreate")
windowStage.loadContent("pages/index", (err, data) => { windowStage.loadContent("pages/index", (err, data) => {
if (err.code) { if (err.code) {
...@@ -74,17 +75,17 @@ export default class MainAbility extends Ability { ...@@ -74,17 +75,17 @@ export default class MainAbility extends Ability {
onWindowStageDestroy() { onWindowStageDestroy() {
// Main window is destroyed to release UI resources. // Main window is destroyed to release UI resources.
console.log("[Demo] MainAbility onWindowStageDestroy") console.log("[Demo] EntryAbility onWindowStageDestroy")
} }
onForeground() { onForeground() {
// Ability is brought to the foreground. // Ability is brought to the foreground.
console.log("[Demo] MainAbility onForeground") console.log("[Demo] EntryAbility onForeground")
} }
onBackground() { onBackground() {
// Ability is brought back to the background. // Ability is brought back to the background.
console.log("[Demo] MainAbility onBackground") console.log("[Demo] EntryAbility onBackground")
} }
}; };
``` ```
# @ohos.i18n (Internationalization) # @ohos.i18n (Internationalization)
The **i18n** module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402. This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402.
The [intl](js-apis-intl.md) module provides basic i18n capabilities through the standard i18n APIs defined in ECMA 402. It works with the i18n module to provide a complete suite of i18n capabilities. The [Intl](js-apis-intl.md) module provides basic I18N capabilities through the standard I18N APIs defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities.
> **NOTE** > **NOTE**
> - 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.
> >
> - This module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402. For details about the basic i18n capabilities, see [intl](js-apis-intl.md). > - This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. For details about the basic I18N capabilities, see [Intl](js-apis-intl.md).
## Modules to Import ## Modules to Import
...@@ -42,7 +42,7 @@ Obtains the localized script for the specified country. ...@@ -42,7 +42,7 @@ Obtains the localized script for the specified country.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -81,7 +81,7 @@ Obtains the localized script for the specified language. ...@@ -81,7 +81,7 @@ Obtains the localized script for the specified language.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -112,7 +112,7 @@ Obtains the list of system languages. For details about languages, see [Instanti ...@@ -112,7 +112,7 @@ Obtains the list of system languages. For details about languages, see [Instanti
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -149,7 +149,7 @@ Obtains the list of countries and regions supported for the specified language. ...@@ -149,7 +149,7 @@ Obtains the list of countries and regions supported for the specified language.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -187,7 +187,7 @@ Checks whether the system language matches the specified region. ...@@ -187,7 +187,7 @@ Checks whether the system language matches the specified region.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -218,7 +218,7 @@ Obtains the system language. For details about languages, see [Instantiating the ...@@ -218,7 +218,7 @@ Obtains the system language. For details about languages, see [Instantiating the
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -239,7 +239,7 @@ static setSystemLanguage(language: string): void ...@@ -239,7 +239,7 @@ static setSystemLanguage(language: string): void
Sets the system language. Currently, this API does not support real-time updating of the system language. Sets the system language. Currently, this API does not support real-time updating of the system language.
**System API**: This is a system API. This is a system API.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION **Permission required**: ohos.permission.UPDATE_CONFIGURATION
...@@ -253,7 +253,7 @@ Sets the system language. Currently, this API does not support real-time updatin ...@@ -253,7 +253,7 @@ Sets the system language. Currently, this API does not support real-time updatin
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -284,7 +284,7 @@ Obtains the system region. For details about system regions, see [Instantiating ...@@ -284,7 +284,7 @@ Obtains the system region. For details about system regions, see [Instantiating
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -305,7 +305,7 @@ static setSystemRegion(region: string): void ...@@ -305,7 +305,7 @@ static setSystemRegion(region: string): void
Sets the system region. Sets the system region.
**System API**: This is a system API. This is a system API.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION **Permission required**: ohos.permission.UPDATE_CONFIGURATION
...@@ -319,7 +319,7 @@ Sets the system region. ...@@ -319,7 +319,7 @@ Sets the system region.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -350,7 +350,7 @@ Obtains the system locale. For details about system locales, see [Instantiating ...@@ -350,7 +350,7 @@ Obtains the system locale. For details about system locales, see [Instantiating
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -371,7 +371,7 @@ static setSystemLocale(locale: string): void ...@@ -371,7 +371,7 @@ static setSystemLocale(locale: string): void
Sets the system locale. Sets the system locale.
**System API**: This is a system API. This is a system API.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION **Permission required**: ohos.permission.UPDATE_CONFIGURATION
...@@ -385,7 +385,7 @@ Sets the system locale. ...@@ -385,7 +385,7 @@ Sets the system locale.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -416,7 +416,7 @@ Checks whether the 24-hour clock is used. ...@@ -416,7 +416,7 @@ Checks whether the 24-hour clock is used.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -437,7 +437,7 @@ static set24HourClock(option: boolean): void ...@@ -437,7 +437,7 @@ static set24HourClock(option: boolean): void
Sets the 24-hour clock. Sets the 24-hour clock.
**System API**: This is a system API. This is a system API.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION **Permission required**: ohos.permission.UPDATE_CONFIGURATION
...@@ -451,7 +451,7 @@ Sets the 24-hour clock. ...@@ -451,7 +451,7 @@ Sets the 24-hour clock.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -473,7 +473,7 @@ static addPreferredLanguage(language: string, index?: number): void ...@@ -473,7 +473,7 @@ static addPreferredLanguage(language: string, index?: number): void
Adds a preferred language to the specified position on the preferred language list. Adds a preferred language to the specified position on the preferred language list.
**System API**: This is a system API. This is a system API.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION **Permission required**: ohos.permission.UPDATE_CONFIGURATION
...@@ -488,7 +488,7 @@ Adds a preferred language to the specified position on the preferred language li ...@@ -488,7 +488,7 @@ Adds a preferred language to the specified position on the preferred language li
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -512,7 +512,7 @@ static removePreferredLanguage(index: number): void ...@@ -512,7 +512,7 @@ static removePreferredLanguage(index: number): void
Deletes a preferred language from the specified position on the preferred language list. Deletes a preferred language from the specified position on the preferred language list.
**System API**: This is a system API. This is a system API.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION **Permission required**: ohos.permission.UPDATE_CONFIGURATION
...@@ -526,7 +526,7 @@ Deletes a preferred language from the specified position on the preferred langua ...@@ -526,7 +526,7 @@ Deletes a preferred language from the specified position on the preferred langua
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -547,7 +547,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -547,7 +547,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getPreferredLanguageList(): Array&lt;string&gt; static getPreferredLanguageList(): Array&lt;string&gt;
Obtains the preferred language list. Obtains the list of preferred languages.
**System capability**: SystemCapability.Global.I18n **System capability**: SystemCapability.Global.I18n
...@@ -555,11 +555,11 @@ Obtains the preferred language list. ...@@ -555,11 +555,11 @@ Obtains the preferred language list.
| Type | Description | | Type | Description |
| ------------------- | --------- | | ------------------- | --------- |
| Array&lt;string&gt; | Preferred language list.| | Array&lt;string&gt; | List of preferred languages.|
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -590,7 +590,7 @@ Obtains the first language in the preferred language list. ...@@ -590,7 +590,7 @@ Obtains the first language in the preferred language list.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -621,7 +621,7 @@ Obtains the preferred language of an application. ...@@ -621,7 +621,7 @@ Obtains the preferred language of an application.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -642,7 +642,7 @@ static setUsingLocalDigit(flag: boolean): void ...@@ -642,7 +642,7 @@ static setUsingLocalDigit(flag: boolean): void
Specifies whether to enable use of local digits. Specifies whether to enable use of local digits.
**System API**: This is a system API. This is a system API.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION **Permission required**: ohos.permission.UPDATE_CONFIGURATION
...@@ -652,11 +652,11 @@ Specifies whether to enable use of local digits. ...@@ -652,11 +652,11 @@ Specifies whether to enable use of local digits.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------- | ---- | ------------------------------- | | ---- | ------- | ---- | ------------------------------- |
| flag | boolean | Yes | Whether to enable the local digit switch. The value **true** means to enable the local digit switch, and the value **false** indicates the opposite.| | flag | boolean | Yes | Whether to turn on the local digit switch. The value **true** means to turn on the local digit switch, and the value **false** indicates the opposite.|
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -687,7 +687,7 @@ Checks whether use of local digits is enabled. ...@@ -687,7 +687,7 @@ Checks whether use of local digits is enabled.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -1059,7 +1059,7 @@ Creates a **PhoneNumberFormat** object. ...@@ -1059,7 +1059,7 @@ Creates a **PhoneNumberFormat** object.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------- | | ------- | ---------------------------------------- | ---- | ---------------- |
| country | string | Yes | Country or region to which the phone number to be formatted belongs.| | country | string | Yes | Country or region to which the phone number to be formatted belongs.|
| options | [PhoneNumberFormatOptions](#phonenumberformatoptions8) | No | Options of the **PhoneNumberFormat** object. | | options | [PhoneNumberFormatOptions](#phonenumberformatoptions9) | No | Options of the **PhoneNumberFormat** object. |
**Example** **Example**
```js ```js
...@@ -1149,7 +1149,7 @@ Obtains the home location of a phone number. ...@@ -1149,7 +1149,7 @@ Obtains the home location of a phone number.
``` ```
## PhoneNumberFormatOptions<sup>8+</sup> ## PhoneNumberFormatOptions<sup>9+</sup>
Defines the options for this PhoneNumberFormat object. Defines the options for this PhoneNumberFormat object.
...@@ -1194,7 +1194,7 @@ Creates an **IndexUtil** object. ...@@ -1194,7 +1194,7 @@ Creates an **IndexUtil** object.
**Example** **Example**
```js ```js
let indexUtil= I18n.getInstance("zh-CN"); let indexUtil = I18n.getInstance("zh-CN");
``` ```
...@@ -1267,7 +1267,7 @@ Obtains the index of a text object. ...@@ -1267,7 +1267,7 @@ Obtains the index of a text object.
**Example** **Example**
```js ```js
let indexUtil= I18n.getInstance("zh-CN"); let indexUtil = I18n.getInstance("zh-CN");
let index = indexUtil.getIndex("hi"); // index = "H" let index = indexUtil.getIndex("hi"); // index = "H"
``` ```
...@@ -1382,7 +1382,7 @@ Puts the [BreakIterator](#breakiterator8) object to the first text boundary, whi ...@@ -1382,7 +1382,7 @@ Puts the [BreakIterator](#breakiterator8) object to the first text boundary, whi
**Example** **Example**
```js ```js
let iterator = i18n.getLineInstance("en"); let iterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit."); iterator.setLineBreakText("Apple is my favorite fruit.");
let firstPos = iterator.first(); // firstPos = 0 let firstPos = iterator.first(); // firstPos = 0
``` ```
...@@ -1689,7 +1689,7 @@ Obtains the list of time zone city IDs supported by the system. ...@@ -1689,7 +1689,7 @@ Obtains the list of time zone city IDs supported by the system.
static getCityDisplayName(cityID: string, locale: string): string static getCityDisplayName(cityID: string, locale: string): string
Obtains the localized representation of a time zone city in the specified locale. Obtains the localized display of a time zone city in the specified locale.
**System capability**: SystemCapability.Global.I18n **System capability**: SystemCapability.Global.I18n
...@@ -2363,7 +2363,7 @@ This API is supported since API version 8 and is deprecated since API version 9. ...@@ -2363,7 +2363,7 @@ This API is supported since API version 8 and is deprecated since API version 9.
getPreferredLanguageList(): Array&lt;string&gt; getPreferredLanguageList(): Array&lt;string&gt;
Obtains the preferred language list. Obtains the list of preferred languages.
This API is supported since API version 8 and is deprecated since API version 9. You are advised to use [System.getPreferredLanguageList](#getpreferredlanguagelist9) instead. This API is supported since API version 8 and is deprecated since API version 9. You are advised to use [System.getPreferredLanguageList](#getpreferredlanguagelist9) instead.
...@@ -2373,7 +2373,7 @@ This API is supported since API version 8 and is deprecated since API version 9. ...@@ -2373,7 +2373,7 @@ This API is supported since API version 8 and is deprecated since API version 9.
| Type | Description | | Type | Description |
| ------------------- | --------- | | ------------------- | --------- |
| Array&lt;string&gt; | Preferred language list.| | Array&lt;string&gt; | List of preferred languages.|
**Example** **Example**
```js ```js
......
...@@ -67,7 +67,7 @@ Creates a **Locale** object. ...@@ -67,7 +67,7 @@ Creates a **Locale** object.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | -------------------------------- | ---- | ---------------------------- | | -------------------- | -------------------------------- | ---- | ---------------------------- |
| locale | string | Yes | A string containing locale information, including the language, optional script, and region. For details about the international standards and combination modes for the language, script, and country or region, see [intl Development](../../internationalization/intl-guidelines.md#setting-locale-information).| | locale | string | Yes | A string containing locale information, including the language, optional script, and region. For details about the international standards and combination modes for the language, script, and country or region, see [intl Development](../../internationalization/intl-guidelines.md#setting-locale-information).|
| options<sup>9+</sup> | [LocaleOptions](#localeoptions6) | No | Options for creating the **Locale** object. | | options<sup>9+</sup> | [LocaleOptions](#localeoptions9) | No | Options for creating the **Locale** object. |
**Example** **Example**
```js ```js
...@@ -159,7 +159,7 @@ Minimizes information of the **Locale** object. If the script and locale informa ...@@ -159,7 +159,7 @@ Minimizes information of the **Locale** object. If the script and locale informa
``` ```
## LocaleOptions<sup>6+</sup> ## LocaleOptions<sup>9+</sup>
Represents the locale options. Represents the locale options.
...@@ -206,7 +206,7 @@ Creates a **DateTimeOptions** object for the specified locale. ...@@ -206,7 +206,7 @@ Creates a **DateTimeOptions** object for the specified locale.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | ------------------------------------ | ---- | ---------------------------- | | -------------------- | ------------------------------------ | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options<sup>9+</sup> | [DateTimeOptions](#datetimeoptions6) | No | Options for creating a **DateTimeFormat** object. | | options<sup>9+</sup> | [DateTimeOptions](#datetimeoptions9) | No | Options for creating a **DateTimeFormat** object. |
**Example** **Example**
```js ```js
...@@ -298,7 +298,7 @@ Obtains the formatting options for **DateTimeFormat** object. ...@@ -298,7 +298,7 @@ Obtains the formatting options for **DateTimeFormat** object.
| Type | Description | | Type | Description |
| ------------------------------------ | ----------------------------- | | ------------------------------------ | ----------------------------- |
| [DateTimeOptions](#datetimeoptions6) | Formatting options for **DateTimeFormat** objects.| | [DateTimeOptions](#datetimeoptions9) | Formatting options for **DateTimeFormat** objects.|
**Example** **Example**
```js ```js
...@@ -310,7 +310,7 @@ Obtains the formatting options for **DateTimeFormat** object. ...@@ -310,7 +310,7 @@ Obtains the formatting options for **DateTimeFormat** object.
``` ```
## DateTimeOptions<sup>6+</sup> ## DateTimeOptions<sup>9+</sup>
Provides the options for the **DateTimeFormat** object. Provides the options for the **DateTimeFormat** object.
...@@ -370,7 +370,7 @@ Creates a **NumberFormat** object for the specified locale. ...@@ -370,7 +370,7 @@ Creates a **NumberFormat** object for the specified locale.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | -------------------------------- | ---- | ---------------------------- | | -------------------- | -------------------------------- | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options<sup>9+</sup> | [NumberOptions](#numberoptions6) | No | Options for creating a **NumberFormat** object. | | options<sup>9+</sup> | [NumberOptions](#numberoptions9) | No | Options for creating a **NumberFormat** object. |
**Example** **Example**
```js ```js
...@@ -420,7 +420,7 @@ Obtains the options of the **NumberFormat** object. ...@@ -420,7 +420,7 @@ Obtains the options of the **NumberFormat** object.
| Type | Description | | Type | Description |
| -------------------------------- | --------------------------- | | -------------------------------- | --------------------------- |
| [NumberOptions](#numberoptions6) | Formatting options for **NumberFormat** objects.| | [NumberOptions](#numberoptions9) | Formatting options for **NumberFormat** objects.|
**Example** **Example**
...@@ -433,7 +433,7 @@ Obtains the options of the **NumberFormat** object. ...@@ -433,7 +433,7 @@ Obtains the options of the **NumberFormat** object.
``` ```
## NumberOptions<sup>6+</sup> ## NumberOptions<sup>9+</sup>
Defines the device capability. Defines the device capability.
...@@ -493,7 +493,7 @@ Creates a **Collator** object. ...@@ -493,7 +493,7 @@ Creates a **Collator** object.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | ------------------------------------ | ---- | ---------------------------- | | -------------------- | ------------------------------------ | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options<sup>9+</sup> | [CollatorOptions](#collatoroptions8) | No | Options for creating a **Collator** object. | | options<sup>9+</sup> | [CollatorOptions](#collatoroptions9) | No | Options for creating a **Collator** object. |
**Example** **Example**
```js ```js
...@@ -544,7 +544,7 @@ Returns properties reflecting the locale and collation options of a **Collator** ...@@ -544,7 +544,7 @@ Returns properties reflecting the locale and collation options of a **Collator**
| Type | Description | | Type | Description |
| ------------------------------------ | ----------------- | | ------------------------------------ | ----------------- |
| [CollatorOptions](#collatoroptions8) | Properties of the **Collator** object.| | [CollatorOptions](#collatoroptions9) | Properties of the **Collator** object.|
**Example** **Example**
```js ```js
...@@ -556,7 +556,7 @@ Returns properties reflecting the locale and collation options of a **Collator** ...@@ -556,7 +556,7 @@ Returns properties reflecting the locale and collation options of a **Collator**
``` ```
## CollatorOptions<sup>8+</sup> ## CollatorOptions<sup>9+</sup>
Represents the properties of a **Collator** object. Represents the properties of a **Collator** object.
...@@ -604,7 +604,7 @@ Creates a **PluralRules** object to obtain the singular-plural type of numbers. ...@@ -604,7 +604,7 @@ Creates a **PluralRules** object to obtain the singular-plural type of numbers.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | ---------------------------------------- | ---- | ---------------------------- | | -------------------- | ---------------------------------------- | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options<sup>9+</sup> | [PluralRulesOptions](#pluralrulesoptions8) | No | Options for creating a **PluralRules** object. | | options<sup>9+</sup> | [PluralRulesOptions](#pluralrulesoptions9) | No | Options for creating a **PluralRules** object. |
**Example** **Example**
```js ```js
...@@ -647,7 +647,7 @@ Obtains a string that represents the singular-plural type of the specified numbe ...@@ -647,7 +647,7 @@ Obtains a string that represents the singular-plural type of the specified numbe
``` ```
## PluralRulesOptions<sup>8+</sup> ## PluralRulesOptions<sup>9+</sup>
Represents the properties of a **PluralRules** object. Represents the properties of a **PluralRules** object.
...@@ -695,7 +695,7 @@ Creates a **RelativeTimeFormat** object. ...@@ -695,7 +695,7 @@ Creates a **RelativeTimeFormat** object.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | ---------------------------------------- | ---- | ---------------------------- | | -------------------- | ---------------------------------------- | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options<sup>9+</sup> | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions8) | No | Options for creating a **RelativeTimeFormat** object. | | options<sup>9+</sup> | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions9) | No | Options for creating a **RelativeTimeFormat** object. |
**Example** **Example**
```js ```js
...@@ -787,7 +787,7 @@ Obtains the formatting options for **RelativeTimeFormat** objects. ...@@ -787,7 +787,7 @@ Obtains the formatting options for **RelativeTimeFormat** objects.
``` ```
## RelativeTimeFormatInputOptions<sup>8+</sup> ## RelativeTimeFormatInputOptions<sup>9+</sup>
Represents the properties of a **RelativeTimeFormat** object. Represents the properties of a **RelativeTimeFormat** object.
......
# @ohos.net.connection (Network Connection Management) # @ohos.net.connection (Network Connection Management)
The **connection** module provides basic network management capabilities. You can obtain the default active data network or the list of all active data networks, enable or disable the airplane mode, and obtain network capability information. The network connection management module provides basic network management capabilities. You can obtain the default active data network or the list of all active data networks, enable or disable the airplane mode, and obtain network capability information.
> **NOTE**<br> > **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
...@@ -10,6 +10,40 @@ The **connection** module provides basic network management capabilities. You ca ...@@ -10,6 +10,40 @@ The **connection** module provides basic network management capabilities. You ca
```js ```js
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
``` ```
## connection.createNetConnection
createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection
Creates a **NetConnection** object. **netSpecifier** specifies the network, and **timeout** specifies the timeout interval in ms. **timeout** is configurable only when **netSpecifier** is specified. If neither of them is present, the default network is used.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| netSpecifier | [NetSpecifier](#netspecifier) | No | Network specifier. If this parameter is not set, the default network is used. |
| timeout | number | No | Timeout interval for obtaining the network specified by **netSpecifier**. This parameter is valid only when **netSpecifier** is set.|
**Return value**
| Type | Description |
| ------------------------------- | -------------------- |
| [NetConnection](#netconnection) | Handle of the network specified by **netSpecifier**.|
**Example**
```js
// Default network
let netConnection = connection.createNetConnection()
// Cellular network
let netConnectionCellular = connection.createNetConnection({
netCapabilities: {
bearerTypes: [connection.NetBearType.BEARER_CELLULAR]
}
})
```
## connection.getDefaultNet ## connection.getDefaultNet
...@@ -25,14 +59,22 @@ Obtains the default active data network. This API uses an asynchronous callback ...@@ -25,14 +59,22 @@ Obtains the default active data network. This API uses an asynchronous callback
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result.| | callback | AsyncCallback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. If the default activated data network is obtained successfully, err is undefined and data is the default activated data network. Otherwise, err is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet(function (error, netHandle) { connection.getDefaultNet(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(netHandle)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -52,17 +94,25 @@ Obtains the default active data network. This API uses a promise to return the r ...@@ -52,17 +94,25 @@ Obtains the default active data network. This API uses a promise to return the r
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<[NetHandle](#nethandle)> | Promise used to return the result.| | Promise\<[NetHandle](#nethandle)> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (data) {
console.log(JSON.stringify(netHandle)) console.log(JSON.stringify(data))
}) })
``` ```
## connection.getDefaultNetSync<sup>9+</sup> ## connection.getDefaultNetSync<sup>9+</sup>
getDefaultNetSync(): NetHandle; getDefaultNetSync(): NetHandle
Obtains the default active data network in synchronous mode. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities. Obtains the default active data network in synchronous mode. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities.
...@@ -76,59 +126,321 @@ Obtains the default active data network in synchronous mode. You can use [getNet ...@@ -76,59 +126,321 @@ Obtains the default active data network in synchronous mode. You can use [getNet
| --------- | ---------------------------------- | | --------- | ---------------------------------- |
| NetHandle | Handle of the default active data network.| | NetHandle | Handle of the default active data network.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
let netHandle = connection.getDefaultNetSync(); let netHandle = connection.getDefaultNetSync();
``` ```
## connection.getGlobalHttpProxy<sup>10+</sup>
## connection.hasDefaultNet getGlobalHttpProxy(callback: AsyncCallback\<HttpProxy>): void
hasDefaultNet(callback: AsyncCallback\<boolean>): void Obtains the global HTTP proxy configuration of the network. This API uses an asynchronous callback to return the result.
Checks whether the default data network is activated. This API uses an asynchronous callback to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any. **System API**: This is a system API.
**Required permission**: ohos.permission.GET_NETWORK_INFO **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| callback | AsyncCallback\<[HttpProxy](#httpproxy)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **err** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.getGlobalHttpProxy((error,data) => {
console.info(JSON.stringify(error));
console.info(JSON.stringify(data));
})
```
## connection.getGlobalHttpProxy<sup>10+</sup>
getGlobalHttpProxy(): Promise\<HttpProxy>;
Obtains the global HTTP proxy configuration of the network. This API uses a promise to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<[HttpProxy](#httpproxy)> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.getGlobalHttpProxy().then((data) => {
console.info(JSON.stringify(data));
}).catch(error => {
console.info(JSON.stringify(error));
})
```
## connection.setGlobalHttpProxy<sup>10+</sup>
setGlobalHttpProxy(httpProxy: HttpProxy, callback: AsyncCallback\<void>): void
Sets the global HTTP proxy configuration of the network. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | --------- | ------------------------------------------------------------ | ---- | ---------------- |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** indicates that the default data network is activated.| | httpProxy | [HttpProxy](#httpproxy) | Yes | Global HTTP proxy configuration of the network.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is set successfully, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.hasDefaultNet(function (error, has) { let exclusionStr="192.168,baidu.com"
console.log(JSON.stringify(error)) let exclusionArray = exclusionStr.split(',');
console.log('has: ' + has) let httpProxy = {
host: "192.168.xx.xxx",
port: 8080,
exclusionList: exclusionArray
}
connection.setGlobalHttpProxy(httpProxy, (error, data) => {
console.info(JSON.stringify(error));
console.info(JSON.stringify(data));
});
```
## connection.setGlobalHttpProxy<sup>10+</sup>
setGlobalHttpProxy(httpProxy: HttpProxy): Promise\<void>;
Sets the global HTTP proxy configuration of the network. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| httpProxy | [HttpProxy](#httpproxy) | Yes | Global HTTP proxy configuration of the network.|
**Return value**
| Type | Description |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | Promise that returns no value.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let exclusionStr="192.168,baidu.com"
let exclusionArray = exclusionStr.split(',');
let httpProxy = {
host: "192.168.xx.xxx",
port: 8080,
exclusionList: exclusionArray
}
connection.setGlobalHttpProxy(httpProxy).then((error, data) => {
console.info(JSON.stringify(data));
}).catch(error=>{
console.info(JSON.stringify(error));
}) })
``` ```
## connection.hasDefaultNet ## connection.getAppNet<sup>9+</sup>
hasDefaultNet(): Promise\<boolean> getAppNet(callback: AsyncCallback\<NetHandle>): void
Checks whether the default data network is activated. This API uses a promise to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any. Obtains information about the network bound to an application. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| callback | AsyncCallback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. If information about the network bound to the application is successfully obtained, **err** is **undefined** and **data** is the obtained network information. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.getAppNet(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## connection.getAppNet<sup>9+</sup>
getAppNet(): Promise\<NetHandle>;
Obtains information about the network bound to an application. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------- | ----------------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<boolean> | Promise used to return the result. The value **true** indicates that the default data network is activated.| | Promise\<[NetHandle](#nethandle)> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.getAppNet().then((data) => {
console.info(JSON.stringify(data));
}).catch(error => {
console.info(JSON.stringify(error));
})
```
## connection.SetAppNet<sup>9+</sup>
setAppNet(netHandle: NetHandle, callback: AsyncCallback\<void>): void
Binds an application to the specified network, so that the application can access the external network only through this network. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the application is successfully bound to the specified network, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.hasDefaultNet().then(function (has) { connection.getDefaultNet(function (error, netHandle) {
console.log('has: ' + has) connection.setAppNet(netHandle, (error, data) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
})
```
## connection.SetAppNet<sup>9+</sup>
setAppNet(netHandle: NetHandle): Promise\<void>;
Binds an application to the specified network, so that the application can access the external network only through this network. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.|
**Return value**
| Type | Description |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | Promise that returns no value.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.getDefaultNet().then(function (netHandle) {
connection.setAppNet(netHandle).then((error, data) => {
console.log(JSON.stringify(data))
}).catch(error => {
console.log(JSON.stringify(error))
})
}) })
``` ```
...@@ -136,7 +448,7 @@ connection.hasDefaultNet().then(function (has) { ...@@ -136,7 +448,7 @@ connection.hasDefaultNet().then(function (has) {
getAllNets(callback: AsyncCallback&lt;Array&lt;NetHandle&gt;&gt;): void getAllNets(callback: AsyncCallback&lt;Array&lt;NetHandle&gt;&gt;): void
Obtains the list of all active data networks. This API uses an asynchronous callback to return the result. Obtains the list of all connected networks. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
...@@ -146,23 +458,30 @@ Obtains the list of all active data networks. This API uses an asynchronous call ...@@ -146,23 +458,30 @@ Obtains the list of all active data networks. This API uses an asynchronous call
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | Yes| Callback used to return the result.| | callback | AsyncCallback&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | Yes| Callback used to return the result. If the list of all connected networks is obtained successfully, **err** is **undefined** and **data** is the list of activated data networks. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getAllNets(function (error, nets) { connection.getAllNets(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(nets)) console.log(JSON.stringify(data))
}); });
``` ```
## connection.getAllNets ## connection.getAllNets
getAllNets(): Promise&lt;Array&lt;NetHandle&gt;&gt; getAllNets(): Promise&lt;Array&lt;NetHandle&gt;&gt;
Obtains the list of all active data networks. This API uses a promise to return the result. Obtains the list of all connected networks. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
...@@ -174,11 +493,19 @@ Obtains the list of all active data networks. This API uses a promise to return ...@@ -174,11 +493,19 @@ Obtains the list of all active data networks. This API uses a promise to return
| -------- | -------- | | -------- | -------- |
| Promise&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | Promise used to return the result.| | Promise&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getAllNets().then(function (nets) { connection.getAllNets().then(function (data) {
console.log(JSON.stringify(nets)) console.log(JSON.stringify(data))
}); });
``` ```
...@@ -186,7 +513,7 @@ connection.getAllNets().then(function (nets) { ...@@ -186,7 +513,7 @@ connection.getAllNets().then(function (nets) {
getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<ConnectionProperties>): void getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<ConnectionProperties>): void
Obtains connection properties of the network corresponding to the given network handle. This API uses an asynchronous callback to return the result. Obtains connection properties of the network corresponding to the **netHandle**. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
...@@ -197,15 +524,25 @@ Obtains connection properties of the network corresponding to the given network ...@@ -197,15 +524,25 @@ Obtains connection properties of the network corresponding to the given network
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- | | --------- | ------------------------------------------------------------ | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| | netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.|
| callback | AsyncCallback\<[ConnectionProperties](#connectionproperties)> | Yes | Callback used to return the result. | | callback | AsyncCallback\<[ConnectionProperties](#connectionproperties)> | Yes | Callback used to return the result. If the connection properties of the network corresponding to the **netHandle** is obtained successfully, **err** is **undefined** and **data** is the obtained network connection information. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
connection.getConnectionProperties(netHandle, function (error, info) { connection.getConnectionProperties(netHandle, function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(info)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -214,7 +551,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -214,7 +551,7 @@ connection.getDefaultNet().then(function (netHandle) {
getConnectionProperties(netHandle: NetHandle): Promise\<ConnectionProperties> getConnectionProperties(netHandle: NetHandle): Promise\<ConnectionProperties>
Obtains connection properties of the network corresponding to **netHandle**. This API uses a promise to return the result. Obtains connection properties of the network corresponding to the **netHandle**. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
...@@ -232,12 +569,22 @@ Obtains connection properties of the network corresponding to **netHandle**. Thi ...@@ -232,12 +569,22 @@ Obtains connection properties of the network corresponding to **netHandle**. Thi
| ------------------------------------------------------- | --------------------------------- | | ------------------------------------------------------- | --------------------------------- |
| Promise\<[ConnectionProperties](#connectionproperties)> | Promise used to return the result.| | Promise\<[ConnectionProperties](#connectionproperties)> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
connection.getConnectionProperties(netHandle).then(function (info) { connection.getConnectionProperties(netHandle).then(function (data) {
console.log(JSON.stringify(info)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -246,7 +593,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -246,7 +593,7 @@ connection.getDefaultNet().then(function (netHandle) {
getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilities>): void getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilities>): void
Obtains capability information of the network corresponding to **netHandle**. This API uses an asynchronous callback to return the result. Obtains capability information of the network corresponding to the **netHandle**. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
...@@ -257,15 +604,25 @@ Obtains capability information of the network corresponding to **netHandle**. Th ...@@ -257,15 +604,25 @@ Obtains capability information of the network corresponding to **netHandle**. Th
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | --------------------------------------------------- | ---- | ---------------- | | --------- | --------------------------------------------------- | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| | netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.|
| callback | AsyncCallback\<[NetCapabilities](#netcapabilities)> | Yes | Callback used to return the result. | | callback | AsyncCallback\<[NetCapabilities](#netcapabilities)> | Yes | Callback used to return the result. If the capability information of the network corresponding to the **netHandle** is obtained successfully, **err** is **undefined** and **data** is the obtained network capability information. Otherwise, **err** is an error object. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
connection.getNetCapabilities(netHandle, function (error, info) { connection.getNetCapabilities(netHandle, function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(info)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -274,7 +631,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -274,7 +631,7 @@ connection.getDefaultNet().then(function (netHandle) {
getNetCapabilities(netHandle: NetHandle): Promise\<NetCapabilities> getNetCapabilities(netHandle: NetHandle): Promise\<NetCapabilities>
Obtains capability information of the network corresponding to **netHandle**. This API uses a promise to return the result. Obtains capability information of the network corresponding to the **netHandle**. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
...@@ -292,12 +649,22 @@ Obtains capability information of the network corresponding to **netHandle**. Th ...@@ -292,12 +649,22 @@ Obtains capability information of the network corresponding to **netHandle**. Th
| --------------------------------------------- | --------------------------------- | | --------------------------------------------- | --------------------------------- |
| Promise\<[NetCapabilities](#netcapabilities)> | Promise used to return the result.| | Promise\<[NetCapabilities](#netcapabilities)> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
connection.getNetCapabilities(netHandle).then(function (info) { connection.getNetCapabilities(netHandle).then(function (data) {
console.log(JSON.stringify(info)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -318,12 +685,20 @@ Checks whether the data traffic usage on the current network is metered. This AP ...@@ -318,12 +685,20 @@ Checks whether the data traffic usage on the current network is metered. This AP
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** indicates the data traffic usage is metered.| | callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** indicates the data traffic usage is metered.|
**Example**: **Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js ```js
connection.isDefaultNetMetered(function (error, has) { connection.isDefaultNetMetered(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log('has: ' + has) console.log('data: ' + data)
}) })
``` ```
...@@ -343,11 +718,216 @@ Checks whether the data traffic usage on the current network is metered. This AP ...@@ -343,11 +718,216 @@ Checks whether the data traffic usage on the current network is metered. This AP
| ----------------- | ----------------------------------------------- | | ----------------- | ----------------------------------------------- |
| Promise\<boolean> | Promise used to return the result. The value **true** indicates the data traffic usage is metered.| | Promise\<boolean> | Promise used to return the result. The value **true** indicates the data traffic usage is metered.|
**Example**: **Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.isDefaultNetMetered().then(function (data) {
console.log('data: ' + data)
})
```
## connection.hasDefaultNet
hasDefaultNet(callback: AsyncCallback\<boolean>): void
Checks whether the default data network is activated. This API uses an asynchronous callback to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** indicates the default data network is activated.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.hasDefaultNet(function (error, data) {
console.log(JSON.stringify(error))
console.log('data: ' + data)
})
```
## connection.hasDefaultNet
hasDefaultNet(): Promise\<boolean>
Checks whether the default data network is activated. This API uses a promise to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| ----------------- | ----------------------------------------------- |
| Promise\<boolean> | Promise used to return the result. The value **true** indicates that the default data network is activated.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js ```js
connection.isDefaultNetMetered().then(function (has) { connection.hasDefaultNet().then(function (data) {
console.log('has: ' + has) console.log('data: ' + data)
})
```
## connection.enableAirplaneMode
enableAirplaneMode(callback: AsyncCallback\<void>): void
Enables the airplane mode. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.enableAirplaneMode(function (error) {
console.log(JSON.stringify(error))
})
```
## connection.enableAirplaneMode
enableAirplaneMode(): Promise\<void>
Enables the airplane mode. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | Promise that returns no value.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.enableAirplaneMode().then(function (error) {
console.log(JSON.stringify(error))
})
```
## connection.disableAirplaneMode
disableAirplaneMode(callback: AsyncCallback\<void>): void
Disables the airplane mode. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the airplane mode is disabled successfully, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.disableAirplaneMode(function (error) {
console.log(JSON.stringify(error))
})
```
## connection.disableAirplaneMode
disableAirplaneMode(): Promise\<void>
Disables the airplane mode. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | Promise that returns no value.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.disableAirplaneMode().then(function (error) {
console.log(JSON.stringify(error))
}) })
``` ```
...@@ -355,9 +935,8 @@ connection.isDefaultNetMetered().then(function (has) { ...@@ -355,9 +935,8 @@ connection.isDefaultNetMetered().then(function (has) {
reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
Reports connection of the data network. This API uses an asynchronous callback to return the result. Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager.
This API uses an asynchronous callback to return the result.
If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...@@ -368,7 +947,17 @@ If this API is called, the application considers that the network connection sta ...@@ -368,7 +947,17 @@ If this API is called, the application considers that the network connection sta
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the network status is reported successfully, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
...@@ -384,9 +973,8 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -384,9 +973,8 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt; reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;
Reports connection of the data network. This API uses a promise to return the result. Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager.
This API uses a promise to return the result.
If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...@@ -399,11 +987,20 @@ If this API is called, the application considers that the network connection sta ...@@ -399,11 +987,20 @@ If this API is called, the application considers that the network connection sta
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
...@@ -414,14 +1011,12 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -414,14 +1011,12 @@ connection.getDefaultNet().then(function (netHandle) {
}); });
``` ```
## connection.reportNetDisconnected ## connection.reportNetDisconnected
reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
Reports disconnection of the data network. This API uses an asynchronous callback to return the result. Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager.
This API uses an asynchronous callback to return the result.
If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...@@ -432,7 +1027,17 @@ If this API is called, the application considers that the network connection sta ...@@ -432,7 +1027,17 @@ If this API is called, the application considers that the network connection sta
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the network status is reported successfully, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
...@@ -444,14 +1049,12 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -444,14 +1049,12 @@ connection.getDefaultNet().then(function (netHandle) {
}); });
``` ```
## connection.reportNetDisconnected ## connection.reportNetDisconnected
reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt; reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt;
Reports disconnection of the data network. This API uses a promise to return the result. Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager.
This API uses a promise to return the result.
If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...@@ -464,11 +1067,20 @@ If this API is called, the application considers that the network connection sta ...@@ -464,11 +1067,20 @@ If this API is called, the application considers that the network connection sta
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
...@@ -493,213 +1105,185 @@ Resolves the host name by using the default network to obtain all IP addresses. ...@@ -493,213 +1105,185 @@ Resolves the host name by using the default network to obtain all IP addresses.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------ | | -------- | ------------------------------------------------- | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.| | host | string | Yes | Host name to resolve.|
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. | | callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. If all IP addresses are successfully obtained, **err** is **undefined**, and **data** is the list of all obtained IP addresses. Otherwise, **err** is an error object.|
**Example** **Error codes**
```js | ID| Error Message |
let host = "xxxx"; | ------- | ----------------------------- |
connection.getAddressesByName(host, function (error, addresses) { | 201 | Permission denied. |
console.log(JSON.stringify(error)) | 401 | Parameter error. |
console.log(JSON.stringify(addresses)) | 2100001 | Invalid parameter value. |
}) | 2100002 | Operation failed. Cannot connect to service.|
``` | 2100003 | System internal error. |
## connection.getAddressesByName
getAddressesByName(host: string): Promise\<Array\<NetAddress>>
Resolves the host name by using the default network to obtain all IP addresses. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.|
**Return value**
| Type | Description |
| ------------------------------------------- | ----------------------------- |
| Promise\<Array\<[NetAddress](#netaddress)>> | Promise used to return the result.|
**Example**
```js
let host = "xxxx";
connection.getAddressesByName(host).then(function (addresses) {
console.log(JSON.stringify(addresses))
})
```
## connection.enableAirplaneMode
enableAirplaneMode(callback: AsyncCallback\<void>): void
Enables the airplane mode. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example** **Example**
```js ```js
connection.enableAirplaneMode(function (error) { let host = "xxxx";
connection.getAddressesByName(host, function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
}) })
``` ```
## connection.enableAirplaneMode ## connection.getAddressesByName
enableAirplaneMode(): Promise\<void> getAddressesByName(host: string): Promise\<Array\<NetAddress>>
Enables the airplane mode. This API uses a promise to return the result. Resolves the host name by using the default network to obtain all IP addresses. This API uses a promise to return the result.
**System API**: This is a system API. **Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.Core **Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ |
| host | string | Yes | Host name to resolve.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------------------------- | ----------------------------- | | ------------------------------------------- | ----------------------------- |
| Promise\<void> | Promise that returns no value.| | Promise\<Array\<[NetAddress](#netaddress)>> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.enableAirplaneMode().then(function (error) { let host = "xxxx";
console.log(JSON.stringify(error)) connection.getAddressesByName(host).then(function (data) {
console.log(JSON.stringify(data))
}) })
``` ```
## connection.disableAirplaneMode ## NetConnection
disableAirplaneMode(callback: AsyncCallback\<void>): void
Disables the airplane mode. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** Represents the network connection handle.
| Name | Type | Mandatory| Description | ### register
| -------- | ------------------------------------------------- | ---- | ------------------ |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example** register(callback: AsyncCallback\<void>): void
```js Registers a listener for network status changes.
connection.disableAirplaneMode(function (error) {
console.log(JSON.stringify(error))
})
```
## connection.disableAirplaneMode **Required permission**: ohos.permission.GET_NETWORK_INFO
disableAirplaneMode(): Promise\<void> **System capability**: SystemCapability.Communication.NetManager.Core
Disables the airplane mode. This API uses a promise to return the result. **Parameters**
**System API**: This is a system API. | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If a listener for network status changes is registered successfully, **err** is **undefined**. Otherwise, **err** is an error object.|
**System capability**: SystemCapability.Communication.NetManager.Core **Error codes**
**Return value** | ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
| 2101008 | The callback is not exists. |
| 2101022 | The number of requests exceeded the maximum. |
| Type | Description |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | Promise that returns no value.|
**Example** **Example**
```js ```js
connection.disableAirplaneMode().then(function (error) { netConnection.register(function (error) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
}) })
``` ```
## connection.createNetConnection ### unregister
createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection unregister(callback: AsyncCallback\<void>): void
Obtains the handle of the network specified by **netSpecifier**. Unregisters the listener for network status changes.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | | -------- | -------------------- | ---- | ---------- |
| netSpecifier | [NetSpecifier](#netspecifier) | No | Network specifier. If this parameter is not set, the default network is used. | | callback | AsyncCallback\<void> | Yes | Callback used to return the result. If a listener for network status changes is unregistered successfully, **err** is **undefined**. Otherwise, **err** is an error object.|
| timeout | number | No | Timeout interval for obtaining the network specified by **netSpecifier**. This parameter is valid only when **netSpecifier** is set.|
**Return value** **Error codes**
| Type | Description | | ID| Error Message |
| ------------------------------- | -------------------- | | ------- | ----------------------------- |
| [NetConnection](#netconnection) | Handle of the network specified by **netSpecifier**.| | 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
| 2101007 | The same callback exists. |
**Example** **Example**
```js ```js
// Default network netConnection.unregister(function (error) {
let netConnection = connection.createNetConnection() console.log(JSON.stringify(error))
// Cellular network
let netConnectionCellular = connection.createNetConnection({
netCapabilities: {
bearerTypes: [connection.NetBearType.BEARER_CELLULAR]
}
}) })
``` ```
## NetConnection
Represents the network connection handle.
### on('netAvailable') ### on('netAvailable')
on(type: 'netAvailable', callback: Callback\<NetHandle>): void on(type: 'netAvailable', callback: Callback\<NetHandle>): void
Registers a listener for **netAvailable** events. Registers a listener for **netAvailable** events.
**Model restriction**: Before you call this API, make sure that you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed at **netAvailable**.<br>**netAvailable**: event indicating that the data network is available.| | type | string | Yes | Event type. The value is fixed to **netAvailable**.<br>**netAvailable**: event indicating that the data network is available.|
| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. | | callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the network handle.|
**Example** **Example**
```js ```js
netConnection.on('netAvailable', function (data) { // Create a NetConnection object.
let netCon = connection.createNetConnection()
// Call register to register a listener.
netCon.register(function (error) {
console.log(JSON.stringify(error))
})
// Subscribe to netAvailable events. Event notifications can be received only after register is called.
netCon.on('netAvailable', function (data) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
// Call unregister to unregister the listener.
netCon.unregister(function (error) {
console.log(JSON.stringify(error))
})
``` ```
### on('netCapabilitiesChange') ### on('netBlockStatusChange')
on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void on(type: 'netBlockStatusChange', callback: Callback&lt;{ netHandle: NetHandle, blocked: boolean }&gt;): void
Registers a listener for **netCapabilitiesChange** events. Registers a listener for **netBlockStatusChange** events.
**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
...@@ -707,22 +1291,38 @@ Registers a listener for **netCapabilitiesChange** events. ...@@ -707,22 +1291,38 @@ Registers a listener for **netCapabilitiesChange** events.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed at **netCapabilitiesChange**.<br>**netCapabilitiesChange**: event indicating that network capabilities have changed.| | type | string | Yes | Event type. The value is fixed to **netBlockStatusChange**.<br>**netBlockStatusChange**: event indicating a change in the network blocking status.|
| callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | Yes | Callback used to return the result. | | callback | Callback&lt;{&nbsp;netHandle:&nbsp;[NetHandle](#nethandle),&nbsp;blocked:&nbsp;boolean&nbsp;}&gt; | Yes | Callback used to return the network handle (**netHandle**) and network status (**blocked**).|
**Example** **Example**
```js ```js
netConnection.on('netCapabilitiesChange', function (data) { // Create a NetConnection object.
let netCon = connection.createNetConnection()
// Call register to register a listener.
netCon.register(function (error) {
console.log(JSON.stringify(error))
})
// Subscribe to netBlockStatusChange events. Event notifications can be received only after register is called.
netCon.on('netBlockStatusChange', function (data) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
// Call unregister to unregister the listener.
netCon.unregister(function (error) {
console.log(JSON.stringify(error))
})
``` ```
### on('netConnectionPropertiesChange') ### on('netCapabilitiesChange')
on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void
Registers a listener for **netConnectionPropertiesChange** events. Registers a listener for **netCapabilitiesChange** events.
**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
...@@ -730,22 +1330,38 @@ Registers a listener for **netConnectionPropertiesChange** events. ...@@ -730,22 +1330,38 @@ Registers a listener for **netConnectionPropertiesChange** events.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed at **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.| | type | string | Yes | Event type. The value is fixed to **netCapabilitiesChange**.<br>**netCapabilitiesChange**: event indicating that the network capabilities have changed.|
| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the result. | | callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).|
**Example** **Example**
```js ```js
netConnection.on('netConnectionPropertiesChange', function (data) { // Create a NetConnection object.
let netCon = connection.createNetConnection()
// Call register to register a listener.
netCon.register(function (error) {
console.log(JSON.stringify(error))
})
// Subscribe to netCapabilitiesChange events. Event notifications can be received only after register is called.
netCon.on('netCapabilitiesChange', function (data) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
// Call unregister to unregister the listener.
netCon.unregister(function (error) {
console.log(JSON.stringify(error))
})
``` ```
### on('netBlockStatusChange') ### on('netConnectionPropertiesChange')
on(type: 'netBlockStatusChange', callback: Callback&lt;{ netHandle: NetHandle, blocked: boolean }&gt;): void on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void
Registers a listener for **netBlockStatusChange** events. Registers a listener for **netConnectionPropertiesChange** events.
**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
...@@ -753,15 +1369,29 @@ Registers a listener for **netBlockStatusChange** events. ...@@ -753,15 +1369,29 @@ Registers a listener for **netBlockStatusChange** events.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed at **netBlockStatusChange**.<br>**netBlockStatusChange**: event indicating a change in the network blocking status.| | type | string | Yes | Event type. The value is fixed to **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.|
| callback | Callback&lt;{&nbsp;netHandle:&nbsp;[NetHandle](#nethandle),&nbsp;blocked:&nbsp;boolean&nbsp;}&gt; | Yes | Callback used to return the result. | | callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).|
**Example** **Example**
```js ```js
netConnection.on('netBlockStatusChange', function (data) { // Create a NetConnection object.
let netCon = connection.createNetConnection()
// Call register to register a listener.
netCon.register(function (error) {
console.log(JSON.stringify(error))
})
// Subscribe to netConnectionPropertiesChange events. Event notifications can be received only after register is called.
netCon.on('netConnectionPropertiesChange', function (data) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
// Call unregister to unregister the listener.
netCon.unregister(function (error) {
console.log(JSON.stringify(error))
})
``` ```
### on('netLost') ### on('netLost')
...@@ -770,22 +1400,37 @@ on(type: 'netLost', callback: Callback\<NetHandle>): void ...@@ -770,22 +1400,37 @@ on(type: 'netLost', callback: Callback\<NetHandle>): void
Registers a listener for **netLost** events. Registers a listener for **netLost** events.
**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed at **netLost**.<br>netLost: event indicating that the network is interrupted or normally disconnected.| | type | string | Yes | Event type. The value is fixed to **netLost**.<br>netLost: event indicating that the network is interrupted or normally disconnected.|
| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. | | callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the network handle (**netHandle**).|
**Example** **Example**
```js ```js
let netConnection1 = connection.createNetConnection() // Create a NetConnection object.
netConnection1.on('netLost', function (data) { let netCon = connection.createNetConnection()
// Call register to register a listener.
netCon.register(function (error) {
console.log(JSON.stringify(error))
})
// Subscribe to netLost events. Event notifications can be received only after register is called.
netCon.on('netLost', function (data) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
// Call unregister to unregister the listener.
netCon.unregister(function (error) {
console.log(JSON.stringify(error))
})
``` ```
### on('netUnavailable') ### on('netUnavailable')
...@@ -794,65 +1439,35 @@ on(type: 'netUnavailable', callback: Callback\<void>): void ...@@ -794,65 +1439,35 @@ on(type: 'netUnavailable', callback: Callback\<void>): void
Registers a listener for **netUnavailable** events. Registers a listener for **netUnavailable** events.
**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------- | ---- | ------------------------------------------------------------ | | -------- | --------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed at **netUnavailable**.<br>**netUnavailable**: event indicating that the network is unavailable.| | type | string | Yes | Event type. The value is fixed to **netUnavailable**.<br>**netUnavailable**: event indicating that the network is unavailable.|
| callback | Callback\<void> | Yes | Callback used to return the result. | | callback | Callback\<void> | Yes | Callback used to return the result, which is empty.|
**Example** **Example**
```js ```js
netConnection.on('netUnavailable', function (data) { // Create a NetConnection object.
console.log(JSON.stringify(data)) let netCon = connection.createNetConnection()
})
```
### register
register(callback: AsyncCallback\<void>): void
Registers a listener for network status changes.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Example** // Call register to register a listener.
netCon.register(function (error) {
```js
netConnection.register(function (error) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
}) })
```
### unregister
unregister(callback: AsyncCallback\<void>): void
Unregisters the listener for network status changes.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Example** // Subscribe to netUnavailable events. Event notifications can be received only after register is called.
netCon.on('netUnavailable', function (data) {
console.log(JSON.stringify(data))
})
```js // Call unregister to unregister the listener.
netConnection.unregister(function (error) { netCon.unregister(function (error) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
}) })
``` ```
...@@ -861,24 +1476,22 @@ netConnection.unregister(function (error) { ...@@ -861,24 +1476,22 @@ netConnection.unregister(function (error) {
Defines the handle of the data network. Defines the handle of the data network.
Before invoking NetHandle APIs, call **getNetHandle** to obtain a **NetHandle** object. Before invoking **NetHandle** APIs, call **getNetHandle** to obtain a **NetHandle** object.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
### Parameters ### Attributes
| Name| Type | Description | | Name | Type | Mandatory| Description |
| ------ | ------ | ------------------------- | | ------ | ------ | --- |------------------------- |
| netId | number | Network ID. The value **0** indicates no default network. Any other value must be greater than or equal to 100.| | netId | number | Yes | Network ID. The value **0** indicates no default network. Any other value must be greater than or equal to 100.|
### bindSocket<sup>9+</sup> ### bindSocket<sup>9+</sup>
bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>): void; bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>): void
Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses an asynchronous callback to return the result. Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
...@@ -886,24 +1499,33 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses ...@@ -886,24 +1499,33 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ----------- | ------------------------ | ---- | -------------------------------| | ----------- | ------------------------ | ---- | -------------------------------|
| socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | Yes| **TCPSocket** or **UDPSocket** object.| | socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | Yes| **TCPSocket** or **UDPSocket** object.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. | | callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the **TCPSocket** or **UDPSocket** object is successfully bound to the current network, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
import socket from "@ohos.net.socket"; import socket from "@ohos.net.socket";
connection.getDefaultNet().then((netHandle)=>{ connection.getDefaultNet().then((netHandle) => {
var tcp = socket.constructTCPSocketInstance(); var tcp = socket.constructTCPSocketInstance();
var udp = socket.constructUDPSocketInstance(); var udp = socket.constructUDPSocketInstance();
let socketType = "TCPSocket"; let socketType = "TCPSocket";
if (socketType == "TCPSocket") { if (socketType == "TCPSocket") {
tcp.bind({ tcp.bind({
address: '192.168.xx.xxx', port: xxxx, family: 1 address: '192.168.xx.xxx', port: 8080, family: 1
}, err => { }, error => {
if (err) { if (error) {
console.log('bind fail'); console.log('bind fail');
} }
netHandle.bindSocket(tcp, (error, data)=>{ netHandle.bindSocket(tcp, (error, data) => {
if (error) { if (error) {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
} else { } else {
...@@ -913,19 +1535,19 @@ connection.getDefaultNet().then((netHandle)=>{ ...@@ -913,19 +1535,19 @@ connection.getDefaultNet().then((netHandle)=>{
}) })
} else { } else {
let callback = value => { let callback = value => {
console.log(TAG + "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);
udp.bind({ udp.bind({
address: '192.168.xx.xxx', port: xxxx, family: 1 address: '192.168.xx.xxx', port: 8080, family: 1
}, err => { }, error => {
if (err) { if (error) {
console.log('bind fail'); console.log('bind fail');
} }
udp.on('message', (data) => { udp.on('message', (data) => {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}); });
netHandle.bindSocket(udp,(error, data)=>{ netHandle.bindSocket(udp, (error, data) => {
if (error) { if (error) {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
} else { } else {
...@@ -937,14 +1559,12 @@ connection.getDefaultNet().then((netHandle)=>{ ...@@ -937,14 +1559,12 @@ connection.getDefaultNet().then((netHandle)=>{
}) })
``` ```
### bindSocket ### bindSocket<sup>9+</sup>
bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\<void>; bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\<void>;
Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses a promise to return the result. Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
...@@ -959,56 +1579,60 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses ...@@ -959,56 +1579,60 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses
| -------------- | ---------------------- | | -------------- | ---------------------- |
| Promise\<void> | Promise that returns no value.| | Promise\<void> | Promise that returns no value.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
import socket from "@ohos.net.socket"; import socket from "@ohos.net.socket";
connection.getDefaultNet().then((netHandle)=>{ connection.getDefaultNet().then((netHandle) => {
var tcp = socket.constructTCPSocketInstance(); var tcp = socket.constructTCPSocketInstance();
var udp = socket.constructUDPSocketInstance(); var udp = socket.constructUDPSocketInstance();
let socketType = "TCPSocket"; let socketType = "TCPSocket";
if (socketType == "TCPSocket") { if (socketType == "TCPSocket") {
tcp.bind({ tcp.bind({
address: '192.168.xx.xxx', port: xxxx, family: 1 address: '192.168.xx.xxx', port: 8080, family: 1
}, err => { }, error => {
if (err) { if (error) {
console.log('bind fail'); console.log('bind fail');
} }
netHandle.bindSocket(tcp).then((err, data) => { netHandle.bindSocket(tcp).then((data) => {
if (err) { console.log(JSON.stringify(data));
console.log(JSON.stringify(err)); }).catch(error => {
} else { console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
}
}) })
}) })
} else { } else {
let callback = value => { let callback = value => {
console.log(TAG + "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);
udp.bind({ udp.bind({
address: '192.168.xx.xxx', port: xxxx, family: 1 address: '192.168.xx.xxx', port: 8080, family: 1
}, err => { }, error => {
if (err) { if (error) {
console.log('bind fail'); console.log('bind fail');
} }
udp.on('message', (data) => { udp.on('message', (data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}) })
netHandle.bindSocket(udp).then((err, data) => { netHandle.bindSocket(udp).then((data) => {
if (err) { console.log(JSON.stringify(data));
console.log(JSON.stringify(err)); }).catch(error => {
} else { console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
}
}) })
}) })
} }
}) })
``` ```
### getAddressesByName ### getAddressesByName
getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void
...@@ -1023,17 +1647,27 @@ Resolves the host name by using the corresponding network to obtain all IP addre ...@@ -1023,17 +1647,27 @@ Resolves the host name by using the corresponding network to obtain all IP addre
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------ | | -------- | ------------------------------------------------- | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.| | host | string | Yes | Host name to resolve.|
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. | | callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. If all IP addresses are successfully obtained, **err** is **undefined**, and **data** is the list of all obtained IP addresses. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
let host = "xxxx"; let host = "xxxx";
netHandle.getAddressesByName(host, function (error, addresses) { netHandle.getAddressesByName(host, function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(addresses)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -1052,7 +1686,7 @@ Resolves the host name by using the corresponding network to obtain all IP addre ...@@ -1052,7 +1686,7 @@ Resolves the host name by using the corresponding network to obtain all IP addre
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ | | ------ | ------ | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.| | host | string | Yes | Host name to resolve.|
**Return value** **Return value**
...@@ -1060,13 +1694,23 @@ Resolves the host name by using the corresponding network to obtain all IP addre ...@@ -1060,13 +1694,23 @@ Resolves the host name by using the corresponding network to obtain all IP addre
| ------------------------------------------- | ----------------------------- | | ------------------------------------------- | ----------------------------- |
| Promise\<Array\<[NetAddress](#netaddress)>> | Promise used to return the result.| | Promise\<Array\<[NetAddress](#netaddress)>> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
let host = "xxxx"; let host = "xxxx";
netHandle.getAddressesByName(host).then(function (addresses) { netHandle.getAddressesByName(host).then(function (data) {
console.log(JSON.stringify(addresses)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -1085,17 +1729,27 @@ Resolves the host name by using the corresponding network to obtain the first IP ...@@ -1085,17 +1729,27 @@ Resolves the host name by using the corresponding network to obtain the first IP
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | ------------------ | | -------- | ----------------------------------------- | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.| | host | string | Yes | Host name to resolve.|
| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. | | callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. If the first IP address is obtained successfully, **err** is **undefined**, and **data** is the first obtained IP address. Otherwise, **err** is an error object. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
let host = "xxxx"; let host = "xxxx";
netHandle.getAddressByName(host, function (error, address) { netHandle.getAddressByName(host, function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(address)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -1114,7 +1768,7 @@ Resolves the host name by using the corresponding network to obtain the first IP ...@@ -1114,7 +1768,7 @@ Resolves the host name by using the corresponding network to obtain the first IP
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ | | ------ | ------ | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.| | host | string | Yes | Host name to resolve.|
**Return value** **Return value**
...@@ -1122,66 +1776,88 @@ Resolves the host name by using the corresponding network to obtain the first IP ...@@ -1122,66 +1776,88 @@ Resolves the host name by using the corresponding network to obtain the first IP
| ----------------------------------- | ------------------------------- | | ----------------------------------- | ------------------------------- |
| Promise\<[NetAddress](#netaddress)> | Promise used to return the result.| | Promise\<[NetAddress](#netaddress)> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
let host = "xxxx"; let host = "xxxx";
netHandle.getAddressByName(host).then(function (address) { netHandle.getAddressByName(host).then(function (data) {
console.log(JSON.stringify(address)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
## NetSpecifier ## NetCap
Provides an instance that bears data network capabilities. Defines the network capability.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory | Description | | Name | Value | Description |
| -------- | ------- | --------- | ----------- | | ------------------------ | ---- | ---------------------- |
| netCapabilities | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. | | NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.|
| bearerPrivateIdentifier | string | No | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).| | NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.|
| NET_CAPABILITY_INTERNET | 12 | The network has the Internet access capability, which is set by the network provider.|
| NET_CAPABILITY_NOT_VPN | 15 | The network does not use a virtual private network (VPN).|
| NET_CAPABILITY_VALIDATED | 16 | The Internet access capability of the network is successfully verified by the connection management module.|
## NetCapabilities ## NetBearType
Defines the network capability set. Enumerates network types.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory | Description | | Name | Value | Description |
| -------- | ------- | --------- | ----------- | | --------------- | ---- | ----------- |
| linkUpBandwidthKbps | number | No | Uplink (from the device to the network) bandwidth.| | BEARER_CELLULAR | 0 | Cellular network. |
| linkDownBandwidthKbps | number | No | Downlink (from the network to the device) bandwidth.| | BEARER_WIFI | 1 | Wi-Fi network.|
| networkCap | Array<[NetCap](#netcap)> | No | Network capability. | | BEARER_ETHERNET | 3 | Ethernet network.|
| bearerTypes | Array<[NetBearType](#netbeartype)> | Yes | Network type. |
## NetCap ## HttpProxy<sup>10+</sup>
Defines the network capability. Defines the global HTTP proxy configuration of the network.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value | Description | | Name | Type | Mandatory| Description |
| ------------------------ | ---- | ---------------------- | | ------ | ------ | --- |------------------------- |
| NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.| | host | string | No | Host name of the proxy server.|
| NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.| | port | number | No | Host port.|
| NET_CAPABILITY_INTERNET | 12 | The network can connect to the Internet.| | exclusionList | Array<string> | No | List of hosts that do not use the proxy server.|
| NET_CAPABILITY_NOT_VPN | 15 | The network does not use a Virtual Private Network (VPN).|
| NET_CAPABILITY_VALIDATED | 16 | The network is available. |
## NetBearType ## NetSpecifier
Defines the network type. Provides an instance that bears data network capabilities.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value | Description | | Name | Type | Mandatory | Description |
| --------------- | ---- | ----------- | | ----------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
| BEARER_CELLULAR | 0 | Cellular network | | netCapabilities | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. |
| BEARER_WIFI | 1 | Wi-Fi network| | bearerPrivateIdentifier | string | No | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).|
| BEARER_ETHERNET | 3 | Ethernet network|
## NetCapabilities
Defines the network capability set.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory| Description |
| --------------------- | ---------------------------------- | --- | ------------------------ |
| linkUpBandwidthKbps | number | No| Uplink (from the device to the network) bandwidth. |
| linkDownBandwidthKbps | number | No| Downlink (from the network to the device) bandwidth. |
| networkCap | Array\<[NetCap](#netcap)> | No| Network capability. |
| bearerTypes | Array\<[NetBearType](#netbeartype)> | Yes| Network type. |
## ConnectionProperties ## ConnectionProperties
...@@ -1189,48 +1865,48 @@ Defines the network connection properties. ...@@ -1189,48 +1865,48 @@ Defines the network connection properties.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------- | --------- | ----------- | | ------------- | ---------------------------------- | ----|---------------- |
| interfaceName | string | Yes | NIC card name. | | interfaceName | string | Yes|Network interface card (NIC) name. |
| domains | string | Yes | Domain. The default value is **""**.| | domains | string | Yes|Domain. The default value is **""**.|
| linkAddresses | Array\<[LinkAddress](#linkaddress)> | Yes | Link information. | | linkAddresses | Array\<[LinkAddress](#linkaddress)> | Yes|Link information. |
| routes | Array\<[RouteInfo](#routeinfo)> | Yes | Route information. | | routes | Array\<[RouteInfo](#routeinfo)> | Yes|Route information. |
| dnses | Array\<[NetAddress](#netaddress)>; | Yes | Network address. For details, see [NetAddress](#netaddress).| | dnses | Array\<[NetAddress](#netaddress)> | Yes|Network address. For details, see [NetAddress](#netaddress).|
| mtu | number | Yes | Maximum transmission unit (MTU). | | mtu | number | Yes|Maximum transmission unit (MTU). |
## LinkAddress ## RouteInfo
Network link information. Defines network route information.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory | Description | | Name | Type | Mandatory|Description |
| -------- | ------- | --------- | ----------- | | -------------- | --------------------------- | --- |---------------- |
| address | [NetAddress](#netaddress) | Yes | Link address. | | interface | string | Yes|NIC name. |
| prefixLength | number | Yes | Length of the link address prefix.| | destination | [LinkAddress](#linkaddress) | Yes|Destination address. |
| gateway | [NetAddress](#netaddress) | Yes|Gateway address. |
| hasGateway | boolean | Yes|Whether a gateway is present. |
| isDefaultRoute | boolean | Yes|Whether the route is the default route.|
## RouteInfo ## LinkAddress
Network route information. Defines network link information.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory | Description | | Name | Type | Mandatory|Description |
| -------- | ------- | --------- | ----------- | | ------------ | ----------------------- |---- |-------------------- |
| interface | string | Yes | NIC card name. | | address | [NetAddress](#netaddress) | Yes| Link address. |
| destination | [LinkAddress](#linkaddress) | Yes | Destination IP address. | | prefixLength | number | Yes|Length of the link address prefix.|
| gateway | [NetAddress](#netaddress) | Yes | Gateway address. |
| hasGateway | boolean | Yes | Whether a gateway is present. |
| isDefaultRoute | boolean | Yes | Whether the route is the default route.|
## NetAddress ## NetAddress
Defines the network address. Defines a network address.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------- | --------- | ----------- | | ------- | ------ | -- |------------------------------ |
| address | string | Yes | Network address. | | address | string | Yes|Network address. |
| family | number | Yes | Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.| | family | number | No|Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.|
| port | number | No | Port number. The value ranges from **0** to **65535**. | | port | number | No|Port number. The value ranges from **0** to **65535**. |
# @ohos.net.ethernet (Ethernet Connection Management) # # @ohos.net.ethernet (Ethernet Connection Management)
The **ethernet** module provides wired network capabilities, which allow users to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network. The **ethernet** module provides wired network capabilities, which allow users to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network.
> **NOTE**<br> > **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
...@@ -17,30 +17,51 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallbac ...@@ -17,30 +17,51 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallbac
Sets the network interface configuration. This API uses an asynchronous callback to return the result. Sets the network interface configuration. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Ethernet
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------------------------------ | | -------- | ------------------------------------------------- | ---- | ------------------------------------------ |
| iface | string | Yes | Name of the network interface. | | iface | string | Yes | Interface name. |
| ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set. | | ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.| | callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
| 2201005 | The device information does not exist. |
| 2201006 | Device disconnected. |
| 2201007 | Failed to write the user configuration. |
**Example** **Example**
```js ```js
ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", routeAddr:"192.168.1.1", ethernet.setIfaceConfig("eth0", {
gateAddr:"192.168.1.1", maskAddr:"255.255.255.0", dnsAddr0:"1.1.1.1", dnsAddr1:"2.2.2.2"}, mode: 0,
(error) => { ipAddr: "192.168.xx.xxx",
if (error) { route: "192.168.xx.xxx",
console.log("setIfaceConfig callback error = " + error); gateway: "192.168.xx.xxx",
} else { netMask: "255.255.255.0",
console.log("setIfaceConfig callback ok "); dnsServers: "1.1.1.1",
} domain: "2.2.2.2"
}); }, (error) => {
if (error) {
console.log("setIfaceConfig callback error = " + JSON.stringify(error));
} else {
console.log("setIfaceConfig callback ok ");
}
});
``` ```
## ethernet.setIfaceConfig ## ethernet.setIfaceConfig
...@@ -49,31 +70,53 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\<void> ...@@ -49,31 +70,53 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\<void>
Sets the network interface configuration. This API uses a promise to return the result. Sets the network interface configuration. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Ethernet
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------------------------------------------------- | ---- | ------------------------ | | ------ | ------------------------------------------------- | ---- | ------------------------ |
| iface | string | Yes | Name of the network interface. | | iface | string | Yes | Interface name. |
| ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set.| | ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ----------------------------------------------------------- | | ------------------- | ----------------------------------------------------------- |
| Promise\<void> | Promise that returns no value.| | Promise\<void> | Promise used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
| 2201005 | The device information does not exist. |
| 2201006 | Device disconnected. |
| 2201007 | Failed to write the user configuration. |
**Example** **Example**
```js ```js
ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", routeAddr:"192.168.1.1", ethernet.setIfaceConfig("eth0", {
gateAddr:"192.168.1.1", maskAddr:"255.255.255.0", dnsAddr0:"1.1.1.1", dnsAddr1:"2.2.2.2"}).then(() => { mode: 0,
ipAddr: "192.168.xx.xxx",
route: "192.168.xx.xxx",
gateway: "192.168.xx.xxx",
netMask: "255.255.255.0",
dnsServers: "1.1.1.1",
domain: "2.2.2.2"
}).then(() => {
console.log("setIfaceConfig promiss ok "); console.log("setIfaceConfig promiss ok ");
}).catch((error) => { }).catch(error => {
console.log("setIfaceConfig promiss error = " + error); console.log("setIfaceConfig promiss error = " + JSON.stringify(error));
}); });
``` ```
...@@ -83,31 +126,44 @@ getIfaceConfig(iface: string, callback: AsyncCallback\<InterfaceConfiguration>): ...@@ -83,31 +126,44 @@ getIfaceConfig(iface: string, callback: AsyncCallback\<InterfaceConfiguration>):
Obtains the configuration of a network interface. This API uses an asynchronous callback to return the result. Obtains the configuration of a network interface. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Ethernet
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ----------------------------------------------- | ----- | ------------ | | -------- | ----------------------------------------------- | ----- | ------------ |
| iface | string | Yes | Name of the network interface.| | iface | string | Yes | Interface name.|
| callback | AsyncCallback\<[InterfaceConfiguration](#interfaceconfiguration)> | Yes | Callback used to return the configuration. | | callback | AsyncCallback\<[InterfaceConfiguration](#interfaceconfiguration)> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
| 2201005 | The device information does not exist. |
**Example** **Example**
```js ```js
ethernet.getIfaceConfig("eth0", (error, value) => { ethernet.getIfaceConfig("eth0", (error, value) => {
if (error) { if (error) {
console.log("getIfaceConfig callback error = " + error); console.log("getIfaceConfig callback error = " + JSON.stringify(error));
} else { } else {
console.log("getIfaceConfig callback mode = " + value.mode); console.log("getIfaceConfig callback mode = " + JSON.stringify(value.mode));
console.log("getIfaceConfig callback ipAddr = " + value.ipAddr); console.log("getIfaceConfig callback ipAddr = " + JSON.stringify(value.ipAddr));
console.log("getIfaceConfig callback routeAddr = " + value.routeAddr); console.log("getIfaceConfig callback route = " + JSON.stringify(value.route));
console.log("getIfaceConfig callback gateAddr = " + value.gateAddr); console.log("getIfaceConfig callback gateway = " + JSON.stringify(value.gateway));
console.log("getIfaceConfig callback maskAddr = " + value.maskAddr); console.log("getIfaceConfig callback netMask = " + JSON.stringify(value.netMask));
console.log("getIfaceConfig callback dns0Addr = " + value.dns0Addr); console.log("getIfaceConfig callback dnsServers = " + JSON.stringify(value.dnsServers));
console.log("getIfaceConfig callback dns1Addr = " + value.dns1Addr); console.log("getIfaceConfig callback domain = " + JSON.stringify(value.domain));
} }
}); });
``` ```
...@@ -118,64 +174,90 @@ getIfaceConfig(iface: string): Promise\<InterfaceConfiguration> ...@@ -118,64 +174,90 @@ getIfaceConfig(iface: string): Promise\<InterfaceConfiguration>
Obtains the configuration of a network interface. This API uses a promise to return the result. Obtains the configuration of a network interface. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Ethernet
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ------------ | | -------- | --------------------------------------- | ---- | ------------ |
| iface | string | Yes | Name of the network interface.| | iface | string | Yes | Interface name.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------------------- | ---------------------------------- | | --------------------------------- | ---------------------------------- |
| Promise\<[InterfaceConfiguration](#interfaceconfiguration)> | Promise used to return the configuration. | | Promise\<[InterfaceConfiguration](#interfaceconfiguration)> | Promise used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
| 2201005 | The device information does not exist. |
**Example** **Example**
```js ```js
ethernet.getIfaceConfig("eth0").then((data) => { ethernet.getIfaceConfig("eth0").then((data) => {
console.log("getIfaceConfig promiss mode = " + data.mode); console.log("getIfaceConfig promiss mode = " + JSON.stringify(data.mode));
console.log("getIfaceConfig promiss ipAddr = " + data.ipAddr); console.log("getIfaceConfig promiss ipAddr = " + JSON.stringify(data.ipAddr));
console.log("getIfaceConfig promiss routeAddr = " + data.routeAddr); console.log("getIfaceConfig promiss route = " + JSON.stringify(data.route));
console.log("getIfaceConfig promiss gateAddr = " + data.gateAddr); console.log("getIfaceConfig promiss gateway = " + JSON.stringify(data.gateway));
console.log("getIfaceConfig promiss maskAddr = " + data.maskAddr); console.log("getIfaceConfig promiss netMask = " + JSON.stringify(data.netMask));
console.log("getIfaceConfig promiss dns0Addr = " + data.dns0Addr); console.log("getIfaceConfig promiss dnsServers = " + JSON.stringify(data.dnsServers));
console.log("getIfaceConfig promiss dns1Addr = " + data.dns1Addr); console.log("getIfaceConfig promiss domain = " + JSON.stringify(data.domain));
}).catch((error) => { }).catch(error => {
console.log("getIfaceConfig promiss error = " + error); console.log("getIfaceConfig promiss error = " + JSON.stringify(error));
}); });
``` ```
## ethernet.isIfaceActive ## ethernet.isIfaceActive
isIfaceActive(iface?: string, callback: AsyncCallback\<number>): void isIfaceActive(iface: string, callback: AsyncCallback\<number>): void
Checks whether a network interface is active. This API uses an asynchronous callback to return the result. Checks whether a network interface is active. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Ethernet
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | -------------------------------------------------- | | -------- | --------------------------- | ---- | -------------------------------------------------- |
| iface | string | Yes | Name of the network interface. If this parameter is left empty, the API checks for any active network interface. | | iface | string | Yes | Interface name. If this parameter is left empty, the API checks for any active network interface. |
| callback | AsyncCallback\<number> | Yes | Callback used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.| | callback | AsyncCallback\<number> | Yes | Callback used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
| 2201005 | The device information does not exist. |
**Example** **Example**
```js ```js
ethernet.isIfaceActive("eth0", (error, value) => { ethernet.isIfaceActive("eth0", (error, value) => {
if (error) { if (error) {
console.log("whether2Activate callback error = " + error); console.log("whether2Activate callback error = " + JSON.stringify(error));
} else { } else {
console.log("whether2Activate callback = " + value); console.log("whether2Activate callback = " + JSON.stringify(value));
} }
}); });
``` ```
...@@ -185,15 +267,17 @@ isIfaceActive(iface: string): Promise\<number> ...@@ -185,15 +267,17 @@ isIfaceActive(iface: string): Promise\<number>
Checks whether a network interface is active. This API uses a promise to return the result. Checks whether a network interface is active. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Ethernet
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------------------------- | | ------ | ------ | ---- | -------------------------------------- |
| iface | string | Yes | Name of the network interface. If this parameter is left empty, the API checks for any active network interface.| | iface | string | Yes | Interface name. If this parameter is left empty, the API checks for any active network interface.|
**Return value** **Return value**
...@@ -201,13 +285,24 @@ Checks whether a network interface is active. This API uses a promise to return ...@@ -201,13 +285,24 @@ Checks whether a network interface is active. This API uses a promise to return
| ----------------| ------------------------------------------------------------------ | | ----------------| ------------------------------------------------------------------ |
| Promise\<number> | Promise used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.| | Promise\<number> | Promise used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
| 2201005 | The device information does not exist. |
**Example** **Example**
```js ```js
ethernet.isIfaceActive("eth0").then((data) => { ethernet.isIfaceActive("eth0").then((data) => {
console.log("isIfaceActive promiss = " + data); console.log("isIfaceActive promiss = " + JSON.stringify(data));
}).catch((error) => { }).catch(error => {
console.log("isIfaceActive promiss error = " + error); console.log("isIfaceActive promiss error = " + JSON.stringify(error));
}); });
``` ```
...@@ -215,30 +310,40 @@ ethernet.isIfaceActive("eth0").then((data) => { ...@@ -215,30 +310,40 @@ ethernet.isIfaceActive("eth0").then((data) => {
getAllActiveIfaces(callback: AsyncCallback\<Array\<string>>): void getAllActiveIfaces(callback: AsyncCallback\<Array\<string>>): void
Obtains all active network interfaces. This API uses an asynchronous callback to return the result. Obtains the list of all active network interfaces. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Ethernet
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------ | ---- | ------------------------------ | | -------- | ------------------------------------ | ---- | ------------------------------ |
| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return all the active network interface names obtained.| | callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
**Example** **Example**
```js ```js
ethernet.getAllActiveIfaces((error, value) => { ethernet.getAllActiveIfaces((error, value) => {
if (error) { if (error) {
console.log("getAllActiveIfaces callback error = " + error); console.log("getAllActiveIfaces callback error = " + JSON.stringify(error));
} else { } else {
console.log("getAllActiveIfaces callback value.length = " + value.length); console.log("getAllActiveIfaces callback value.length = " + JSON.stringify(value.length));
for (let i = 0; i < value.length; i++) { for (let i = 0; i < value.length; i++) {
console.log("getAllActiveIfaces callback = " + value[i]); console.log("getAllActiveIfaces callback = " + JSON.stringify(value[i]));
}
} }
}
}); });
``` ```
...@@ -246,30 +351,38 @@ ethernet.getAllActiveIfaces((error, value) => { ...@@ -246,30 +351,38 @@ ethernet.getAllActiveIfaces((error, value) => {
getAllActiveIfaces(): Promise\<Array\<string>> getAllActiveIfaces(): Promise\<Array\<string>>
Obtains all active network interfaces. This API uses a promise to return the result. Obtains the list of all active network interfaces. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core **Required permission**: ohos.permission.GET_NETWORK_INFO
**Parameters** **System capability**: SystemCapability.Communication.NetManager.Ethernet
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------------ | ----------------------------------------------- | | ------------------------------ | ----------------------------------------------- |
| Promise\<Array\<string>> | Promise used to return all the active network interface names obtained.| | Promise\<Array\<string>> | Promise used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
**Example** **Example**
```js ```js
ethernet.getAllActiveIfaces().then((data) => { ethernet.getAllActiveIfaces().then((data) => {
console.log("getAllActiveIfaces promiss data.length = " + data.length); console.log("getAllActiveIfaces promiss 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 = " + data[i]); console.log("getAllActiveIfaces promiss = " + JSON.stringify(data[i]));
} }
}).catch((error) => { }).catch(error => {
console.log("getAllActiveIfaces promiss error = " + error); console.log("getAllActiveIfaces promiss error = " + JSON.stringify(error));
}); });
``` ```
...@@ -277,22 +390,26 @@ ethernet.getAllActiveIfaces().then((data) => { ...@@ -277,22 +390,26 @@ ethernet.getAllActiveIfaces().then((data) => {
Defines the network configuration for the Ethernet connection. Defines the network configuration for the Ethernet connection.
**System capability**: SystemCapability.Communication.NetManager.Core **System API**: This is a system API.
| Name | Type | Mandatory | Description | **System capability**: SystemCapability.Communication.NetManager.Ethernet
| -------- | ------- | --------- | ----------- |
| mode | [IPSetMode](#ipsetmode) | Yes | Configuration mode of the Ethernet connection.| | Name | Type | Mandatory| Description |
| ipAddr | string | Yes | Static IP address of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in Dynamic Host Configuration Protocol (DHCP) mode.| | ------------ | ----------------------- | ---|------------------------------------------------------------ |
| route | string | Yes | Route of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| | mode | [IPSetMode](#ipsetmode) | Yes| Configuration mode of the Ethernet connection.|
| gateway | string | Yes | Gateway of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| | ipAddr | string | Yes| Static IP address of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in Dynamic Host Configuration Protocol (DHCP) mode.|
| netMask | string | Yes | Subnet mask of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| | route | string | Yes| Route of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.|
| dnsServers | string | Yes | DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).| | gateway | string | Yes| Gateway of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.|
| netMask | string | Yes| Subnet mask of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.|
| dnsServers | string | Yes| DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).|
## IPSetMode ## IPSetMode
Defines the configuration mode of the Ethernet connection. Defines the configuration mode of the Ethernet connection.
**System capability**: SystemCapability.Communication.NetManager.Core **System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Ethernet
| Name | Value | Description | | Name | Value | Description |
| ------------------------ | ---- | ---------------------- | | ------------------------ | ---- | ---------------------- |
......
# @ohos.net.policy (Network Policy Management)
The **policy** module provides APIs for managing network policies, through which you can control and manage the data volume used.
> **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.
## Modules to Import
```js
import policy from '@ohos.net.policy'
```
## policy.setBackgroundPolicy
setBackgroundPolicy(isAllowed: boolean, callback: AsyncCallback\<void>): void
Sets a background network policy. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| isAllowed | boolean | Yes | Whether applications running in the background are allowed to use mobile data.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (error, data) => {
this.callBack(error, data);
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
```
## policy.setBackgroundPolicy
setBackgroundPolicy(isAllowed: boolean): Promise\<void>
Sets a background network policy. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| isAllowed | boolean | Yes | Whether applications running in the background are allowed to use mobile data.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
**Example**
```js
policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.isBackgroundAllowed
isBackgroundAllowed(callback: AsyncCallback\<boolean>): void
Obtains the background network policy. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. If the operation is successful, **true** is returned, which means that applications running in the background are allowed to use mobile data. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.isBackgroundAllowed((error, data) => {
this.callBack(error, data);
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
```
## policy.isBackgroundAllowed
isBackgroundAllowed(): Promise\<boolean>;
Obtains the background network policy. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<boolean> | Promise used to return the result. If the operation is successful, **true** is returned, which means that applications running in the background are allowed to use mobile data. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.isBackgroundAllowed().then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.setPolicyByUid
setPolicyByUid(uid: number, policy: NetUidPolicy, callback: AsyncCallback\<void>): void
Sets an application-specific network policy. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes | Unique ID of the application.|
| policy | [NetUidPolicy](#netuidpolicy) | Yes| Application-specific network policy to set.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let param = {
uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy)
}
policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy), (error, data) => {
this.callBack(error, data);
});
```
## policy.setPolicyByUid
setPolicyByUid(uid: number, policy: NetUidPolicy): Promise\<void>;
Sets an application-specific network policy. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes | Unique ID of the application.|
| policy | [NetUidPolicy](#netuidpolicy) | Yes| Application-specific network policy to set.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let param = {
uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy)
}
policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.getPolicyByUid
getPolicyByUid(uid: number, callback: AsyncCallback\<NetUidPolicy>): void
Obtains an application-specific network policy by **uid**. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
| callback | AsyncCallback\<[NetUidPolicy](#netuidpolicy)> | Yes | Callback used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getPolicyByUid(Number.parseInt(this.firstParam), (error, data) => {
this.callBack(error, data);
});
```
## policy.getPolicyByUid
getPolicyByUid(uid: number): Promise\<NetUidPolicy>;
Obtains an application-specific network policy by **uid**. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<[NetUidPolicy](#netuidpolicy)> | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.getUidsByPolicy
getUidsByPolicy(policy: NetUidPolicy, callback: AsyncCallback\<Array\<number>>): void
Obtains the UID array of applications configured with a certain application-specific network policy. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| policy | [NetUidPolicy](#netuidpolicy) | Yes| Target application-specific network policy.|
| callback | AsyncCallback\<Array\<number>> | Yes | Callback used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getUidsByPolicy(Number.parseInt(this.currentNetUidPolicy), (error, data) => {
this.callBack(error, data);
});
```
## policy.getUidsByPolicy
function getUidsByPolicy(policy: NetUidPolicy): Promise\<Array\<number>>;
Obtains the UID array of applications configured with a certain application-specific network policy. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| policy | [NetUidPolicy](#netuidpolicy) | Yes| Target application-specific network policy.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<Array\<number>> | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.getNetQuotaPolicies
getNetQuotaPolicies(callback: AsyncCallback\<Array\<NetQuotaPolicy>>): void
Obtains the network quota policies. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<Array\<[NetQuotaPolicy](#netquotapolicy)>> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getNetQuotaPolicies((error, data) => {
this.callBack(error, data);
});
```
## policy.getNetQuotaPolicies
getNetQuotaPolicies(): Promise\<Array\<NetQuotaPolicy>>;
Obtains the network quota policies. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<Array\<[NetQuotaPolicy](#netquotapolicy)>> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getNetQuotaPolicies().then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.setNetQuotaPolicies
setNetQuotaPolicies(quotaPolicies: Array\<NetQuotaPolicy>, callback: AsyncCallback\<void>): void
Sets an array of network quota policies. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| quotaPolicies | Array\<[NetQuotaPolicy](#netquotapolicy)> | Yes| An array of network quota policies to set.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes),
limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction};
this.netQuotaPolicyList.push(param);
policy.setNetQuotaPolicies(this.netQuotaPolicyList, (error, data) => {
this.callBack(error, data);
});
```
## policy.setNetQuotaPolicies
setNetQuotaPolicies(quotaPolicies: Array\<NetQuotaPolicy>): Promise\<void>;
Sets an array of network quota policies. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| quotaPolicies | Array\<[NetQuotaPolicy](#netquotapolicy)> | Yes| An array of network quota policies to set.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes),
limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction};
this.netQuotaPolicyList.push(param);
policy.setNetQuotaPolicies(this.netQuotaPolicyList).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.restoreAllPolicies
restoreAllPolicies(iccid: string, callback: AsyncCallback\<void>): void
Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| iccid | string | Yes| SIM card ID.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
this.firstParam = iccid;
policy.restoreAllPolicies(this.firstParam, (error, data) => {
this.callBack(error, data);
});
```
## policy.restoreAllPolicies
restoreAllPolicies(iccid: string): Promise\<void>;
Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| iccid | string | Yes| SIM card ID.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
this.firstParam = iccid;
policy.restoreAllPolicies(this.firstParam).then(function(error, data){
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.isUidNetAllowed
isUidNetAllowed(uid: number, isMetered: boolean, callback: AsyncCallback\<boolean>): void
Checks whether an application is allowed to access metered networks. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
| isMetered | boolean | Yes| Whether the network is a metered network.|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that the application is allowed to access metered networks, and **false** means the opposite.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let param = {
uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean))
}
policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => {
this.callBack(error, data);
});
```
## policy.isUidNetAllowed
isUidNetAllowed(uid: number, isMetered: boolean): Promise\<boolean>;
Checks whether an application is allowed to access metered networks. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
| isMetered | boolean | Yes| Whether the network is a metered network.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<boolean> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let param = {
uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean))
}
policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.isUidNetAllowed
isUidNetAllowed(uid: number, iface: string, callback: AsyncCallback\<boolean>): void
Checks whether an application is allowed to access the given network. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
| iface | string | Yes| Name of the target network.|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that the application is allowed to access the given network, and **false** means the opposite.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let param = {
uid: Number.parseInt(this.firstParam), iface: this.secondParam
}
policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam, (error, data) => {
this.callBack(error, data);
});
```
## policy.isUidNetAllowed
isUidNetAllowed(uid: number, iface: string): Promise\<boolean>;
Checks whether an application is allowed to access the given network. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
| iface | string | Yes| Name of the target network.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<boolean> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let param = {
uid: Number.parseInt(this.firstParam), iface: this.secondParam
}
policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.setDeviceIdleAllowList
setDeviceIdleAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\<void>): void
Sets whether to add an application to the device idle allowlist. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
| isAllowed | boolean | Yes| Whether to add the application to the allowlist.|
| callback | callback: AsyncCallback\<void> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
}
policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => {
this.callBack(error, data);
});
```
## policy.setDeviceIdleAllowList
setDeviceIdleAllowList(uid: number, isAllowed: boolean): Promise\<void>;
Sets whether to add an application to the device idle allowlist. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
| isAllowed | boolean | Yes| Whether to add the application to the allowlist.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
}
policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.getDeviceIdleAllowList
getDeviceIdleAllowList(callback: AsyncCallback\<Array\<number>>): void
Obtains the UID array of applications that are on the device idle allowlist. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<Array\<number>> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getDeviceIdleAllowList((error, data) => {
this.callBack(error, data);
});
```
## policy.getDeviceIdleAllowList
getDeviceIdleAllowList(): Promise\<Array\<number>>;
Obtains the UID array of applications that are on the device idle allowlist. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<Array\<number>> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getDeviceIdleAllowList().then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.getBackgroundPolicyByUid
getBackgroundPolicyByUid(uid: number, callback: AsyncCallback\<NetBackgroundPolicy>): void
Obtains the background network policies configured for the given application. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
| callback | AsyncCallback\<[NetBackgroundPolicy](#netbackgroundpolicy)> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
this.firstParam = uid
policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam), (error, data) => {
this.callBack(error, data);
});
```
## policy.getBackgroundPolicyByUid
getBackgroundPolicyByUid(uid: number): Promise\<NetBackgroundPolicy>;
Obtains the background network policies configured for the given application. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<[NetBackgroundPolicy](#netbackgroundpolicy)> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
this.firstParam = uid
policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.resetPolicies
resetPolicies(iccid: string, callback: AsyncCallback\<void>): void
Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| iccid | string | Yes| SIM card ID.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
this.firstParam = iccid
policy.resetPolicies(this.firstParam, (error, data) => {
this.callBack(error, data);
});
```
## policy.resetPolicies
resetPolicies(iccid: string): Promise\<void>;
Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| iccid | string | Yes| SIM card ID.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) {
})
this.firstParam = iccid
policy.resetPolicies(this.firstParam).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.updateRemindPolicy
updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType, callback: AsyncCallback\<void>): void
Updates a reminder policy. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Yes| Network type.|
| iccid | string | Yes| SIM card ID.|
| remindType | [RemindType](#remindtype) | Yes| Reminder type.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let param = {
netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType
}
policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType), (error, data) => {
this.callBack(error, data);
});
```
## policy.updateRemindPolicy
updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType): Promise\<void>;
Updates a reminder policy. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Yes| Network type.|
| iccid | string | Yes| SIM card ID.|
| remindType | [RemindType](#remindtype) | Yes| Reminder type.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let param = {
netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType
}
policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType)).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.setPowerSaveAllowList
setPowerSaveAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\<void>): void
Sets whether to add an application to the power-saving allowlist. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
| isAllowed | boolean | Yes| Whether to add the application to the allowlist.|
| callback | callback: AsyncCallback\<void> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
}
policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => {
this.callBack(error, data);
});
```
## policy.setPowerSaveAllowList
setPowerSaveAllowList(uid: number, isAllowed: boolean): Promise\<void>;
Sets whether to add an application to the power-saving allowlist. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
| isAllowed | boolean | Yes| Whether to add the application to the allowlist.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
}
policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.getPowerSaveAllowList
getPowerSaveAllowList(callback: AsyncCallback\<Array\<number>>): void
Obtains the UID array of applications that are on the power-saving allowlist. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<Array\<number>> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getPowerSaveAllowList((error, data) => {
this.callBack(error, data);
});
```
## policy.getPowerSaveAllowList
getPowerSaveAllowList(): Promise\<Array\<number>>;
Obtains the UID array of applications that are on the device idle allowlist. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<Array\<number>> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getPowerSaveAllowList().then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.on
Functions as the handle to a network policy.
### on('netUidPolicyChange')
on(type: "netUidPolicyChange", callback: Callback\<{ uid: number, policy: NetUidPolicy }>): void
Subscribes to policy changes. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | netUidPolicyChange | Yes| Event type. The value **netUidPolicyChange** indicates a policy change event.|
| callback | Callback\<{ uid: number, policy: [NetUidPolicy](#netuidpolicy) }> | Yes | Callback used to return the result. It is called when the registered network policy changes.|
**Example**
```js
policy.on('netUidPolicyChange', (data) => {
this.log('on netUidPolicyChange: ' + JSON.stringify(data));
})
```
### on('netUidRuleChange')
on(type: "netUidRuleChange", callback: Callback\<{ uid: number, rule: NetUidRule }>): void
Subscribes to rule changes. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | netUidRuleChange | Yes| Event type. The value **netUidRuleChange** indicates a rule change event.|
| callback | Callback\<{ uid: number, rule: [NetUidRule](#netuidrule) }> | Yes | Callback used to return the result. It is called when the registered rule changes.|
**Example**
```js
policy.on('netUidRuleChange', (data) => {
this.log('on netUidRuleChange: ' + JSON.stringify(data));
})
```
### on('netMeteredIfacesChange')
on(type: "netMeteredIfacesChange", callback: Callback\<Array\<string>>): void
Subscribes to metered **iface** changes. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | netMeteredIfacesChange | Yes| Event type. The value **netMeteredIfacesChange** indicates a metered **iface** change event.|
| callback | Callback\<Array\<string>> | Yes | Callback used to return the result. It is called when the registered metered **iface** changes.|
**Example**
```js
policy.on('netMeteredIfacesChange', (data) => {
this.log('on netMeteredIfacesChange: ' + JSON.stringify(data));
})
```
### on('netQuotaPolicyChange')
on(type: "netQuotaPolicyChange", callback: Callback\<Array\<NetQuotaPolicy>>): void
Subscribes to network quota policy changes. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | netQuotaPolicyChange | Yes| Event type. The value **netQuotaPolicyChange** indicates a network quota policy change event.|
| callback | Callback\<Array\<[NetQuotaPolicy](#netquotapolicy)>> | Yes | Callback used to return the result. It is called when the registered network quota policy changes.|
**Example**
```js
policy.on('netQuotaPolicyChange', (data) => {
this.log('on netQuotaPolicyChange: ' + JSON.stringify(data));
})
```
### on('netBackgroundPolicyChange')
on(type: "netBackgroundPolicyChange", callback: Callback\<boolean>): void
Subscribes to background network policy changes. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | netBackgroundPolicyChange | Yes| Event type. The value **netBackgroundPolicyChange** indicates a background network policy change event.|
| callback | Callback\<boolean> | Yes | Callback used to return the result. It is called when the registered background network policy changes.|
**Example**
```js
policy.on('netBackgroundPolicyChange', (data) => {
this.log('on netBackgroundPolicyChange: ' + JSON.stringify(data));
})
```
## NetBackgroundPolicy
Enumerates the background network policies.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value | Description |
| ------------------------ | ---- | ---------------------- |
| NET_BACKGROUND_POLICY_NONE | 0 | Default policy.|
| NET_BACKGROUND_POLICY_ENABLE | 1 | Applications running in the background are allowed to access metered networks.|
| NET_BACKGROUND_POLICY_DISABLE | 2 | Applications running in the background are not allowed to access metered networks.|
| NET_BACKGROUND_POLICY_ALLOW_LIST | 3 | Only applications on the allowlist are allowed to access metered networks when they are running in the background.|
## NetQuotaPolicy
Defines a network quota policy.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Description |
| ----------------------- | ----------------------------------- | ------------------------------------------------------------ |
| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Network type.|
| iccid | string | Identifier of the SIM card on the metered cellular network. It is not used for Wi-Fi networks.|
| ident | string | Identifier of the SIM card on the metered cellular network. It is used for Wi-Fi networks. It is used together with **iccid**.|
| periodDuration | string | Start time of metering.|
| warningBytes | number | Data volume threshold for generating an alarm.|
| limitBytes | number | Data volume quota.|
| lastWarningRemind | string | Last time when an alarm was generated.|
| lastLimitRemind | string | Last time when the quota was exhausted.|
| metered | string | Whether the network is a metered network.|
| limitAction | [LimitAction](#limitaction) | Action to take when the data volume quota is reached.|
## LimitAction
Enumerates the actions that can be taken when the data volume quota is reached.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value| Description |
| ---------------------- | ----- | ------------ |
| LIMIT_ACTION_NONE | -1 | Default policy.|
| LIMIT_ACTION_DISABLE | 0 | Internet access is disabled.|
| LIMIT_ACTION_AUTO_BILL| 1 | Users will be automatically charged for the data volume they use.|
## NetUidRule
Enumerates the metered network rules.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value| Description |
| ---------------------- | ----- | ------------ |
| NET_RULE_NONE | 0 | Default rule.|
| NET_RULE_ALLOW_METERED_FOREGROUND | 1 | Applications running in the foreground are allowed to access metered networks.|
| NET_RULE_ALLOW_METERED | 2 | Applications are allowed to access metered networks.|
| NET_RULE_REJECT_METERED | 4 | Applications are not allowed to access metered networks.|
| NET_RULE_ALLOW_ALL | 32 | Applications are allowed to access all networks (metered or non-metered).|
| NET_RULE_REJECT_ALL | 64 | Applications are not allowed to access any networks (metered or non-metered).|
## RemindType
Enumerates the reminder types.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value| Description |
| ---------------------- | - | ------- |
| REMIND_TYPE_WARNING | 1 | Warning.|
| REMIND_TYPE_LIMIT | 2 | Limit.|
## NetUidPolicy
Enumerates the application-specific network policies.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value| Description |
| ---------------------- | ----- | ------------ |
| NET_POLICY_NONE | 0 | Default network policy.|
| NET_POLICY_ALLOW_METERED_BACKGROUND | 1 | Applications running in the background are allowed to access metered networks.|
| NET_POLICY_REJECT_METERED_BACKGROUND | 2 | Applications running in the background are not allowed to access metered networks.|
# @ohos.net.sharing (Network Sharing) # # @ohos.net.sharing (Network Sharing)
The **sharing** module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume. The **sharing** module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume.
> **NOTE**<br> > **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
...@@ -29,6 +30,15 @@ Checks whether network sharing is supported. This API uses an asynchronous callb ...@@ -29,6 +30,15 @@ Checks whether network sharing is supported. This API uses an asynchronous callb
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.| | callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2202011 | Cannot get network sharing configuration. |
**Example** **Example**
```js ```js
...@@ -56,6 +66,15 @@ Checks whether network sharing is supported. This API uses a promise to return t ...@@ -56,6 +66,15 @@ Checks whether network sharing is supported. This API uses a promise to return t
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<boolean> | Promise used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.| | Promise\<boolean> | Promise used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2202011 | Cannot get network sharing configuration. |
**Example** **Example**
```js ```js
...@@ -84,6 +103,14 @@ Checks whether network sharing is in progress. This API uses an asynchronous cal ...@@ -84,6 +103,14 @@ Checks whether network sharing is in progress. This API uses an asynchronous cal
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.| | callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**Example** **Example**
```js ```js
...@@ -99,10 +126,10 @@ isSharing(): Promise\<boolean> ...@@ -99,10 +126,10 @@ isSharing(): Promise\<boolean>
Checks whether network sharing is in progress. This API uses a promise to return the result. Checks whether network sharing is in progress. This API uses a promise to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System API**: This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.NetSharing **System capability**: SystemCapability.Communication.NetManager.NetSharing
**Return value** **Return value**
...@@ -111,6 +138,14 @@ Checks whether network sharing is in progress. This API uses a promise to return ...@@ -111,6 +138,14 @@ Checks whether network sharing is in progress. This API uses a promise to return
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<boolean> | Promise used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.| | Promise\<boolean> | Promise used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**Example** **Example**
```js ```js
...@@ -127,10 +162,10 @@ startSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void ...@@ -127,10 +162,10 @@ startSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void
Starts network sharing of a specified type. This API uses an asynchronous callback to return the result. Starts network sharing of a specified type. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System API**: This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.NetSharing **System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters** **Parameters**
...@@ -140,11 +175,27 @@ Starts network sharing of a specified type. This API uses an asynchronous callba ...@@ -140,11 +175,27 @@ Starts network sharing of a specified type. This API uses an asynchronous callba
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| | type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| | callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2202004 | Try to share an unavailable iface. |
| 2202005 | WiFi sharing failed. |
| 2202006 | Bluetooth sharing failed. |
| 2202009 | Network share enable forwarding error. |
| 2202011 | Cannot get network sharing configuration. |
**Example** **Example**
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => { let SHARING_WIFI=0;
sharing.startSharing(SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -173,11 +224,27 @@ Starts network sharing of a specified type. This API uses a promise to return th ...@@ -173,11 +224,27 @@ Starts network sharing of a specified type. This API uses a promise to return th
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2202004 | Try to share an unavailable iface. |
| 2202005 | WiFi sharing failed. |
| 2202006 | Bluetooth sharing failed. |
| 2202009 | Network share enable forwarding error. |
| 2202011 | Cannot get network sharing configuration. |
**Example** **Example**
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
sharing.startSharing(SharingIfaceType.SHARING_WIFI).then(() => { let SHARING_WIFI=0;
sharing.startSharing(SHARING_WIFI).then(() => {
console.log("start wifi sharing successful"); console.log("start wifi sharing successful");
}).catch(error => { }).catch(error => {
console.log("start wifi sharing failed"); console.log("start wifi sharing failed");
...@@ -203,11 +270,25 @@ Stops network sharing of a specified type. This API uses an asynchronous callbac ...@@ -203,11 +270,25 @@ Stops network sharing of a specified type. This API uses an asynchronous callbac
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| | type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| | callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2202005 | WiFi sharing failed. |
| 2202006 | Bluetooth sharing failed. |
| 2202011 | Cannot get network sharing configuration. |
**Example** **Example**
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => { let SHARING_WIFI=0;
sharing.stopSharing(SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -236,11 +317,25 @@ Stops network sharing of a specified type. This API uses a promise to return the ...@@ -236,11 +317,25 @@ Stops network sharing of a specified type. This API uses a promise to return the
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2202005 | WiFi sharing failed. |
| 2202006 | Bluetooth sharing failed. |
| 2202011 | Cannot get network sharing configuration. |
**Example** **Example**
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
sharing.stopSharing(SharingIfaceType.SHARING_WIFI).then(() => { let SHARING_WIFI=0;
sharing.stopSharing(SHARING_WIFI).then(() => {
console.log("stop wifi sharing successful"); console.log("stop wifi sharing successful");
}).catch(error => { }).catch(error => {
console.log("stop wifi sharing failed"); console.log("stop wifi sharing failed");
...@@ -265,6 +360,14 @@ Obtains the volume of mobile data traffic received via network sharing. This API ...@@ -265,6 +360,14 @@ Obtains the volume of mobile data traffic received via network sharing. This API
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<number> | Yes | Callback used to return the data volume, in KB.| | callback | AsyncCallback\<number> | Yes | Callback used to return the data volume, in KB.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**Example** **Example**
```js ```js
...@@ -292,6 +395,14 @@ Obtains the volume of mobile data traffic received via network sharing. This API ...@@ -292,6 +395,14 @@ Obtains the volume of mobile data traffic received via network sharing. This API
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<number> | Promise used to return the data volume, in KB.| | Promise\<number> | Promise used to return the data volume, in KB.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**Example** **Example**
```js ```js
...@@ -320,6 +431,14 @@ Obtains the volume of mobile data traffic sent via network sharing. This API use ...@@ -320,6 +431,14 @@ Obtains the volume of mobile data traffic sent via network sharing. This API use
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<number> | Yes | Callback used to return the data volume, in KB.| | callback | AsyncCallback\<number> | Yes | Callback used to return the data volume, in KB.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**Example** **Example**
```js ```js
...@@ -347,6 +466,14 @@ Obtains the volume of mobile data traffic sent via network sharing. This API use ...@@ -347,6 +466,14 @@ Obtains the volume of mobile data traffic sent via network sharing. This API use
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<number> | Promise used to return the data volume, in KB.| | Promise\<number> | Promise used to return the data volume, in KB.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**Example** **Example**
```js ```js
...@@ -375,6 +502,14 @@ Obtains the volume of mobile data traffic sent and received via network sharing. ...@@ -375,6 +502,14 @@ Obtains the volume of mobile data traffic sent and received via network sharing.
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<number> | Yes | Callback used to return the data volume, in KB.| | callback | AsyncCallback\<number> | Yes | Callback used to return the data volume, in KB.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**Example** **Example**
```js ```js
...@@ -402,6 +537,14 @@ Obtains the volume of mobile data traffic sent and received via network sharing. ...@@ -402,6 +537,14 @@ Obtains the volume of mobile data traffic sent and received via network sharing.
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<number> | Promise used to return the data volume, in KB.| | Promise\<number> | Promise used to return the data volume, in KB.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**Example** **Example**
```js ```js
...@@ -428,14 +571,25 @@ Obtains the names of NICs in the specified network sharing state. This API uses ...@@ -428,14 +571,25 @@ Obtains the names of NICs in the specified network sharing state. This API uses
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| | state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.|
| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return an array of NIC names.| | callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return an array of NIC names.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**Example** **Example**
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceState from '@ohos.net.sharing'
sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER, (error, data) => { let SHARING_BLUETOOTH=2;
sharing.getSharingIfaces(SHARING_BLUETOOTH, (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
...@@ -457,7 +611,7 @@ Obtains the names of NICs in the specified network sharing state. This API uses ...@@ -457,7 +611,7 @@ Obtains the names of NICs in the specified network sharing state. This API uses
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| | state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.|
**Return value** **Return value**
...@@ -465,11 +619,22 @@ Obtains the names of NICs in the specified network sharing state. This API uses ...@@ -465,11 +619,22 @@ Obtains the names of NICs in the specified network sharing state. This API uses
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<Array\<string>> | Promise used to return an array of NIC names.| | Promise\<Array\<string>> | Promise used to return an array of NIC names.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**Example** **Example**
```js ```js
import SharingIfaceState from '@ohos.net.sharing' import SharingIfaceState from '@ohos.net.sharing'
sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER).then(data => { let SHARING_BLUETOOTH=2;
sharing.getSharingIfaces(SHARING_BLUETOOTH).then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
...@@ -495,11 +660,22 @@ Obtains the network sharing state of the specified type. This API uses an asynch ...@@ -495,11 +660,22 @@ Obtains the network sharing state of the specified type. This API uses an asynch
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| | type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
| callback | AsyncCallback\<[SharingIfaceState](#sharingifacestate)> | Yes | Callback used to return the network sharing state.| | callback | AsyncCallback\<[SharingIfaceState](#sharingifacestate)> | Yes | Callback used to return the network sharing state.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**Example** **Example**
```js ```js
import SharingIfaceState from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
sharing.getSharingState(SharingIfaceType.SHARING_WIFI, (error, data) => { let SHARING_WIFI=0;
sharing.getSharingState(SHARING_WIFI, (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
...@@ -523,6 +699,16 @@ Obtains the network sharing state of the specified type. This API uses a promise ...@@ -523,6 +699,16 @@ Obtains the network sharing state of the specified type. This API uses a promise
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| | type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**Return value** **Return value**
| Type | Description | | Type | Description |
...@@ -533,7 +719,8 @@ Obtains the network sharing state of the specified type. This API uses a promise ...@@ -533,7 +719,8 @@ Obtains the network sharing state of the specified type. This API uses a promise
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
sharing.getSharingState(SharingIfaceType.SHARING_WIFI).then(data => { let SHARING_WIFI=0;
sharing.getSharingState(SHARING_WIFI).then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
...@@ -559,11 +746,22 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch ...@@ -559,11 +746,22 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| | type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return an array of regular expressions.| | callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return an array of regular expressions.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**Example** **Example**
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI, (error, data) => { let SHARING_WIFI=0;
sharing.getSharableRegexes(SHARING_WIFI, (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
...@@ -593,11 +791,22 @@ Obtains regular expressions of NICs of a specified type. This API uses a promise ...@@ -593,11 +791,22 @@ Obtains regular expressions of NICs of a specified type. This API uses a promise
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<Array\<string>> | Promise used to return an array of regular expressions.| | Promise\<Array\<string>> | Promise used to return an array of regular expressions.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**Example** **Example**
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI).then(data => { let SHARING_WIFI=0;
sharing.getSharableRegexes(SHARING_WIFI).then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
...@@ -621,14 +830,20 @@ Subscribes to network sharing state changes. This API uses an asynchronous callb ...@@ -621,14 +830,20 @@ Subscribes to network sharing state changes. This API uses an asynchronous callb
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| type | string | Yes | Event name.| | type | string | Yes | Event name.|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the network sharing state.| | callback | AsyncCallback\<boolean> | Yes | Callback invoked when the network sharing state changes.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
**Example** **Example**
```js ```js
sharing.on('sharingStateChange', (error, data) => { sharing.on('sharingStateChange', (data) => {
console.log(JSON.stringify(error)); console.log('on sharingStateChange: ' + JSON.stringify(data));
console.log(JSON.stringify(data));
}); });
``` ```
...@@ -649,13 +864,19 @@ Unsubscribes from network sharing state changes. This API uses an asynchronous c ...@@ -649,13 +864,19 @@ Unsubscribes from network sharing state changes. This API uses an asynchronous c
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| type | string | Yes | Event name.| | type | string | Yes | Event name.|
| callback | AsyncCallback\<boolean> | No | Callback used for unsubscription.| | callback | AsyncCallback\<boolean> | No | Callback invoked when the network sharing state changes.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
**Example** **Example**
```js ```js
sharing.off('sharingStateChange', (error, data) => { sharing.off('sharingStateChange', (data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -679,12 +900,18 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an ...@@ -679,12 +900,18 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an
| type | string | Yes | Event name.| | type | string | Yes | Event name.|
| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | Yes | Callback invoked when the network sharing state of the specified NIC changes.| | callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | Yes | Callback invoked when the network sharing state of the specified NIC changes.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
**Example** **Example**
```js ```js
sharing.on('interfaceSharingStateChange', (error, data) => { sharing.on('interfaceSharingStateChange', (data) => {
console.log(JSON.stringify(error)); console.log('on interfaceSharingStateChange: ' + JSON.stringify(data));
console.log(JSON.stringify(data));
}); });
``` ```
...@@ -705,13 +932,19 @@ Unsubscribes from network sharing status changes of a specified NIC. This API us ...@@ -705,13 +932,19 @@ Unsubscribes from network sharing status changes of a specified NIC. This API us
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| type | string | Yes | Event name.| | type | string | Yes | Event name.|
| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | No | Callback used for unsubscription.| | callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | No | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
**Example** **Example**
```js ```js
sharing.off('interfaceSharingStateChange', (error, data) => { sharing.off('interfaceSharingStateChange', (data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -735,12 +968,18 @@ Subscribes to upstream network changes. This API uses an asynchronous callback t ...@@ -735,12 +968,18 @@ Subscribes to upstream network changes. This API uses an asynchronous callback t
| type | string | Yes | Event name.| | type | string | Yes | Event name.|
| callback | AsyncCallback\<NetHandle> | Yes | Callback invoked when the upstream network changes.| | callback | AsyncCallback\<NetHandle> | Yes | Callback invoked when the upstream network changes.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
**Example** **Example**
```js ```js
sharing.on('sharingUpstreamChange', (error, data) => { sharing.on('sharingUpstreamChange', (data) => {
console.log(JSON.stringify(error)); console.log('on sharingUpstreamChange: ' + JSON.stringify(data));
console.log(JSON.stringify(data));
}); });
``` ```
...@@ -761,13 +1000,19 @@ Unsubscribes from upstream network changes. This API uses an asynchronous callba ...@@ -761,13 +1000,19 @@ Unsubscribes from upstream network changes. This API uses an asynchronous callba
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| type | string | Yes | Event name.| | type | string | Yes | Event name.|
| callback | AsyncCallback\<NetHandle> | No | Callback used for unsubscription.| | callback | AsyncCallback\<NetHandle> | No | Callback used for unsubscription from upstream network changes.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
**Example** **Example**
```js ```js
sharing.off('sharingUpstreamChange', (error, data) => { sharing.off('sharingUpstreamChange', (data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -788,7 +1033,7 @@ Enumerates the network sharing states of an NIC. ...@@ -788,7 +1033,7 @@ Enumerates the network sharing states of an NIC.
## SharingIfaceType ## SharingIfaceType
Enumerates the network sharing types of an NIC. Enumerates the network sharing types of an NIC.
**System API**: This is a system API. **System API**: This is a system API.
...@@ -797,5 +1042,5 @@ Enumerates the network sharing types of an NIC. ...@@ -797,5 +1042,5 @@ Enumerates the network sharing types of an NIC.
| Name | Value | Description | | Name | Value | Description |
| ------------------------ | ---- | ---------------------- | | ------------------------ | ---- | ---------------------- |
| SHARING_WIFI | 0 | Wi-Fi hotspot sharing.| | SHARING_WIFI | 0 | Wi-Fi hotspot sharing.|
| SHARING_USB | 1 | USB sharing (not supported currently).| | SHARING_USB | 1 | USB sharing.|
| SHARING_BLUETOOTH | 2 | Bluetooth sharing.| | SHARING_BLUETOOTH | 2 | Bluetooth sharing.|
...@@ -2,7 +2,8 @@ ...@@ -2,7 +2,8 @@
The **pointer** module provides APIs related to pointer attribute management. The **pointer** module provides APIs related to pointer attribute management.
> **NOTE**<br> > **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
...@@ -237,6 +238,8 @@ Obtains the mouse movement speed. This API uses a promise to return the result. ...@@ -237,6 +238,8 @@ Obtains the mouse movement speed. This API uses a promise to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.Pointer **System capability**: SystemCapability.MultimodalInput.Input.Pointer
**System API**: This is a system API.
**Return value** **Return value**
| Name | Description | | Name | Description |
...@@ -263,8 +266,6 @@ Obtains the mouse pointer style. This API uses an asynchronous callback to retur ...@@ -263,8 +266,6 @@ Obtains the mouse pointer style. This API uses an asynchronous callback to retur
**System capability**: SystemCapability.MultimodalInput.Input.Pointer **System capability**: SystemCapability.MultimodalInput.Input.Pointer
**System API**: This is a system API.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
...@@ -277,21 +278,23 @@ Obtains the mouse pointer style. This API uses an asynchronous callback to retur ...@@ -277,21 +278,23 @@ Obtains the mouse pointer style. This API uses an asynchronous callback to retur
```js ```js
import window from '@ohos.window'; import window from '@ohos.window';
window.getTopWindow((error, win) => { window.getLastWindow(this.context, (error, win) => {
win.getProperties((error, properties) => { if (error.code) {
let windowId = properties.id; console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
if (windowId < 0) { return;
console.log(`Invalid windowId`); }
return; let windowId = win.getWindowProperties().id;
} if (windowId < 0) {
try { console.log(`Invalid windowId`);
pointer.getPointerStyle(windowId, (error, style) => { return;
console.log(`Get pointer style success, style: ${JSON.stringify(style)}`); }
}); try {
} catch (error) { pointer.getPointerStyle(windowId, (error, style) => {
console.log(`Get pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); console.log(`Get pointer style success, style: ${JSON.stringify(style)}`);
} });
}); } catch (error) {
console.log(`Get pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
}); });
``` ```
...@@ -320,21 +323,23 @@ Obtains the mouse pointer style. This API uses a promise to return the result. ...@@ -320,21 +323,23 @@ Obtains the mouse pointer style. This API uses a promise to return the result.
```js ```js
import window from '@ohos.window'; import window from '@ohos.window';
window.getTopWindow((error, win) => { window.getLastWindow(this.context, (error, win) => {
win.getProperties((error, properties) => { if (error.code) {
let windowId = properties.id; console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
if (windowId < 0) { return;
console.log(`Invalid windowId`); }
return; let windowId = win.getWindowProperties().id;
} if (windowId < 0) {
try { console.log(`Invalid windowId`);
pointer.getPointerStyle(windowId).then((style) => { return;
console.log(`Get pointer style success, style: ${JSON.stringify(style)}`); }
}); try {
} catch (error) { pointer.getPointerStyle(windowId).then((style) => {
console.log(`Get pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); console.log(`Get pointer style success, style: ${JSON.stringify(style)}`);
} });
}); } catch (error) {
console.log(`Get pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
}); });
``` ```
...@@ -359,21 +364,23 @@ Sets the mouse pointer style. This API uses an asynchronous callback to return t ...@@ -359,21 +364,23 @@ Sets the mouse pointer style. This API uses an asynchronous callback to return t
```js ```js
import window from '@ohos.window'; import window from '@ohos.window';
window.getTopWindow((error, win) => { window.getLastWindow(this.context, (error, win) => {
win.getProperties((error, properties) => { if (error.code) {
let windowId = properties.id; console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
if (windowId < 0) { return;
console.log(`Invalid windowId`); }
return; let windowId = win.getWindowProperties().id;
} if (windowId < 0) {
try { console.log(`Invalid windowId`);
pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS, error => { return;
console.log(`Set pointer style success`); }
}); try {
} catch (error) { pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS, error => {
console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); console.log(`Set pointer style success`);
} });
}); } catch (error) {
console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
}); });
``` ```
## pointer.setPointerStyle<sup>9+</sup> ## pointer.setPointerStyle<sup>9+</sup>
...@@ -397,21 +404,23 @@ Sets the mouse pointer style. This API uses a promise to return the result. ...@@ -397,21 +404,23 @@ Sets the mouse pointer style. This API uses a promise to return the result.
```js ```js
import window from '@ohos.window'; import window from '@ohos.window';
window.getTopWindow((error, win) => { window.getLastWindow(this.context, (error, win) => {
win.getProperties((error, properties) => { if (error.code) {
let windowId = properties.id; console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
if (windowId < 0) { return;
console.log(`Invalid windowId`); }
return; let windowId = win.getWindowProperties().id;
} if (windowId < 0) {
try { console.log(`Invalid windowId`);
pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS).then(() => { return;
console.log(`Set pointer style success`); }
}); try {
} catch (error) { pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS).then(() => {
console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); console.log(`Set pointer style success`);
} });
}); } catch (error) {
console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
}); });
``` ```
## PointerStyle<sup>9+</sup> ## PointerStyle<sup>9+</sup>
...@@ -444,8 +453,8 @@ Enumerates mouse pointer styles. ...@@ -444,8 +453,8 @@ Enumerates mouse pointer styles.
| HAND_POINTING | 19 | Hand-shaped pointer |![Hand_Poniting.png](./figures/Hand_Pointing.png)| | HAND_POINTING | 19 | Hand-shaped pointer |![Hand_Poniting.png](./figures/Hand_Pointing.png)|
| HELP | 20 | Help |![Help.png](./figures/Help.png)| | HELP | 20 | Help |![Help.png](./figures/Help.png)|
| MOVE | 21 | Move |![Move.png](./figures/Move.png)| | MOVE | 21 | Move |![Move.png](./figures/Move.png)|
| RESIZE_LEFT_RIGHT | 22 | Left-and-right resizing|![Resize_Left_Right.png](./figures/Resize_Left_Right.png)| | RESIZE_LEFT_RIGHT | 22 | Left and right resizing|![Resize_Left_Right.png](./figures/Resize_Left_Right.png)|
| RESIZE_UP_DOWN | 23 | Up-and-down resizing|![Resize_Up_Down.png](./figures/Resize_Up_Down.png)| | RESIZE_UP_DOWN | 23 | Up and down resizing|![Resize_Up_Down.png](./figures/Resize_Up_Down.png)|
| SCREENSHOT_CHOOSE | 24 | Screenshot crosshair|![Screenshot_Cross.png](./figures/Screenshot_Cross.png)| | SCREENSHOT_CHOOSE | 24 | Screenshot crosshair|![Screenshot_Cross.png](./figures/Screenshot_Cross.png)|
| SCREENSHOT_CURSOR | 25 | Screenshot cursor |![Screenshot_Cursor.png](./figures/Screenshot_Cursor.png)| | SCREENSHOT_CURSOR | 25 | Screenshot cursor |![Screenshot_Cursor.png](./figures/Screenshot_Cursor.png)|
| TEXT_CURSOR | 26 | Text cursor |![Text_Cursor.png](./figures/Text_Cursor.png)| | TEXT_CURSOR | 26 | Text cursor |![Text_Cursor.png](./figures/Text_Cursor.png)|
......
...@@ -19,8 +19,9 @@ Since API version 9, the stage model allows an application to obtain a **Resourc ...@@ -19,8 +19,9 @@ Since API version 9, the stage model allows an application to obtain a **Resourc
For details about how to reference context in the stage model, see [Context in the Stage Model](../..//application-models/application-context-stage.md). For details about how to reference context in the stage model, see [Context in the Stage Model](../..//application-models/application-context-stage.md).
```ts ```ts
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
let context = this.context; let context = this.context;
let resourceManager = context.resourceManager; let resourceManager = context.resourceManager;
......
# @ohos.net.socket (Socket Connection) # # @ohos.net.socket (Socket Connection)
The **socket** module implements socket connection management and operation. > **NOTE**
>
> **NOTE**<br>
> 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.
## Modules to Import ## Modules to Import
...@@ -13,7 +12,7 @@ import socket from '@ohos.net.socket'; ...@@ -13,7 +12,7 @@ import socket from '@ohos.net.socket';
## socket.constructUDPSocketInstance ## socket.constructUDPSocketInstance
constructUDPSocketInstance\(\): UDPSocket constructUDPSocketInstance(): UDPSocket
Creates a **UDPSocket** object. Creates a **UDPSocket** object.
...@@ -22,7 +21,7 @@ Creates a **UDPSocket** object. ...@@ -22,7 +21,7 @@ Creates a **UDPSocket** object.
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------------------- | ---------------------- | | :--------------------------------- | :---------------------- |
| [UDPSocket](#udpsocket) | **UDPSocket** object.| | [UDPSocket](#udpsocket) | **UDPSocket** object.|
...@@ -39,7 +38,7 @@ Defines a **UDPSocket** connection. Before invoking UDPSocket APIs, you need to ...@@ -39,7 +38,7 @@ Defines a **UDPSocket** connection. Before invoking UDPSocket APIs, you need to
### bind ### bind
bind\(address: NetAddress, callback: AsyncCallback<void\>\): void bind(address: NetAddress, callback: AsyncCallback\<void\>): void
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result. Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result.
...@@ -54,6 +53,13 @@ Binds the IP address and port number. The port number can be specified or random ...@@ -54,6 +53,13 @@ Binds the IP address and port number. The port number can be specified or random
| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| | address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -70,7 +76,7 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ...@@ -70,7 +76,7 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
### bind ### bind
bind\(address: NetAddress\): Promise<void\> bind(address: NetAddress): Promise\<void\>
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result. Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result.
...@@ -84,11 +90,17 @@ Binds the IP address and port number. The port number can be specified or random ...@@ -84,11 +90,17 @@ Binds the IP address and port number. The port number can be specified or random
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | | ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| | address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------- | ----------------------------------------- | | :-------------- | :----------------------------------------- |
| Promise\<void\> | Promise used to return the result.| | Promise\<void\> | Promise used to return the result.|
**Example** **Example**
...@@ -106,7 +118,7 @@ promise .then(() => { ...@@ -106,7 +118,7 @@ promise .then(() => {
### send ### send
send\(options: UDPSendOptions, callback: AsyncCallback<void\>\): void send(options: UDPSendOptions, callback: AsyncCallback\<void\>): void
Sends data over a UDPSocket connection. This API uses an asynchronous callback to return the result. Sends data over a UDPSocket connection. This API uses an asynchronous callback to return the result.
...@@ -123,6 +135,13 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p ...@@ -123,6 +135,13 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).| | options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -146,7 +165,7 @@ udp.send({ ...@@ -146,7 +165,7 @@ udp.send({
### send ### send
send\(options: UDPSendOptions\): Promise<void\> send(options: UDPSendOptions): Promise\<void\>
Sends data over a UDPSocket connection. This API uses a promise to return the result. Sends data over a UDPSocket connection. This API uses a promise to return the result.
...@@ -162,10 +181,17 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p ...@@ -162,10 +181,17 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | | ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).| | options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------- | --------------------------------------------- | | :-------------- | :--------------------------------------------- |
| Promise\<void\> | Promise used to return the result.| | Promise\<void\> | Promise used to return the result.|
**Example** **Example**
...@@ -190,7 +216,7 @@ promise.then(() => { ...@@ -190,7 +216,7 @@ promise.then(() => {
### close ### close
close\(callback: AsyncCallback<void\>\): void close(callback: AsyncCallback\<void\>): void
Closes a UDPSocket connection. This API uses an asynchronous callback to return the result. Closes a UDPSocket connection. This API uses an asynchronous callback to return the result.
...@@ -220,7 +246,7 @@ udp.close(err => { ...@@ -220,7 +246,7 @@ udp.close(err => {
### close ### close
close\(\): Promise<void\> close(): Promise\<void\>
Closes a UDPSocket connection. This API uses a promise to return the result. Closes a UDPSocket connection. This API uses a promise to return the result.
...@@ -231,7 +257,7 @@ Closes a UDPSocket connection. This API uses a promise to return the result. ...@@ -231,7 +257,7 @@ Closes a UDPSocket connection. This API uses a promise to return the result.
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------- | ----------------------------------------- | | :-------------- | :----------------------------------------- |
| Promise\<void\> | Promise used to return the result.| | Promise\<void\> | Promise used to return the result.|
**Example** **Example**
...@@ -249,12 +275,12 @@ promise.then(() => { ...@@ -249,12 +275,12 @@ promise.then(() => {
### getState ### getState
getState\(callback: AsyncCallback<SocketStateBase\>\): void getState(callback: AsyncCallback\<SocketStateBase\>): void
Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result. Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/> >**NOTE**
>This API can be called only after [bind](#bind) is successfully called. >This API can be called only after **bind** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -266,6 +292,12 @@ Obtains the status of the UDPSocket connection. This API uses an asynchronous ca ...@@ -266,6 +292,12 @@ Obtains the status of the UDPSocket connection. This API uses an asynchronous ca
| -------- | ------------------------------------------------------ | ---- | ---------- | | -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result.| | callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -289,12 +321,12 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ...@@ -289,12 +321,12 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
### getState ### getState
getState\(\): Promise<SocketStateBase\> getState(): Promise\<SocketStateBase\>
Obtains the status of the UDPSocket connection. This API uses a promise to return the result. Obtains the status of the UDPSocket connection. This API uses a promise to return the result.
>**NOTE**<br/> >**NOTE**
>This API can be called only after [bind](#bind) is successfully called. >This API can be called only after **bind** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -303,8 +335,8 @@ Obtains the status of the UDPSocket connection. This API uses a promise to retur ...@@ -303,8 +335,8 @@ Obtains the status of the UDPSocket connection. This API uses a promise to retur
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------------------------- | ----------------------------------------- | | :----------------------------------------------- | :----------------------------------------- |
| Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.| | Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result.|
**Example** **Example**
...@@ -328,12 +360,12 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ...@@ -328,12 +360,12 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
### setExtraOptions ### setExtraOptions
setExtraOptions\(options: UDPExtraOptions, callback: AsyncCallback<void\>\): void setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\<void\>): void
Sets other properties of the UDPSocket connection. This API uses an asynchronous callback to return the result. Sets other attributes of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/> >**NOTE**
>This API can be called only after [bind](#bind) is successfully called. >This API can be called only after **bind** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -346,6 +378,12 @@ Sets other properties of the UDPSocket connection. This API uses an asynchronous ...@@ -346,6 +378,12 @@ Sets other properties of the UDPSocket connection. This API uses an asynchronous
| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).| | options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
...@@ -376,12 +414,12 @@ udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> { ...@@ -376,12 +414,12 @@ udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> {
### setExtraOptions ### setExtraOptions
setExtraOptions\(options: UDPExtraOptions\): Promise<void\> setExtraOptions(options: UDPExtraOptions): Promise\<void\>
Sets other properties of the UDPSocket connection. This API uses a promise to return the result. Sets other attributes of the UDPSocket connection. This API uses a promise to return the result.
>**NOTE**<br/> >**NOTE**
>This API can be called only after [bind](#bind) is successfully called. >This API can be called only after **bind** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -396,9 +434,16 @@ Sets other properties of the UDPSocket connection. This API uses a promise to re ...@@ -396,9 +434,16 @@ Sets other properties of the UDPSocket connection. This API uses a promise to re
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------- | --------------------------------------------------- | | :-------------- | :--------------------------------------------------- |
| Promise\<void\> | Promise used to return the result.| | Promise\<void\> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -424,9 +469,9 @@ promise.then(() => { ...@@ -424,9 +469,9 @@ promise.then(() => {
``` ```
### on\('message'\) ### on('message')
on\(type: 'message', callback: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void on(type: 'message', callback: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
Enables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result. Enables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
...@@ -437,7 +482,7 @@ Enables listening for message receiving events of the UDPSocket connection. This ...@@ -437,7 +482,7 @@ Enables listening for message receiving events of the UDPSocket connection. This
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event| | type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. | | callback | Callback\<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}\> | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -449,13 +494,13 @@ udp.on('message', value => { ...@@ -449,13 +494,13 @@ udp.on('message', value => {
``` ```
### off\('message'\) ### off('message')
off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/> >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -475,15 +520,15 @@ let callback = value =>{ ...@@ -475,15 +520,15 @@ 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');
``` ```
### on\('listening' | 'close'\) ### on('listening' | 'close')
on\(type: 'listening' | 'close', callback: Callback<void\>\): void on(type: 'listening' | 'close', callback: Callback\<void\>): void
Enables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result. Enables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
...@@ -509,13 +554,13 @@ udp.on('close', () => { ...@@ -509,13 +554,13 @@ udp.on('close', () => {
``` ```
### off\('listening' | 'close'\) ### off('listening' | 'close')
off\(type: 'listening' | 'close', callback?: Callback<void\>\): void off(type: 'listening' | 'close', callback?: Callback\<void\>): void
Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/> >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -535,22 +580,22 @@ let callback1 = () =>{ ...@@ -535,22 +580,22 @@ 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');
``` ```
### on\('error'\) ### on('error')
on\(type: 'error', callback: ErrorCallback\): void on(type: 'error', callback: ErrorCallback): void
Enables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result. Enables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
...@@ -563,7 +608,6 @@ Enables listening for error events of the UDPSocket connection. This API uses an ...@@ -563,7 +608,6 @@ Enables listening for error events of the UDPSocket connection. This API uses an
| type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event| | type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event|
| callback | ErrorCallback | Yes | Callback used to return the result. | | callback | ErrorCallback | Yes | Callback used to return the result. |
**Example** **Example**
```js ```js
...@@ -574,13 +618,13 @@ udp.on('error', err => { ...@@ -574,13 +618,13 @@ udp.on('error', err => {
``` ```
### off\('error'\) ### off('error')
off\(type: 'error', callback?: ErrorCallback\): void off(type: 'error', callback?: ErrorCallback): void
Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/> >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -600,7 +644,7 @@ let callback = err =>{ ...@@ -600,7 +644,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');
``` ```
...@@ -668,9 +712,15 @@ Defines information about the socket connection. ...@@ -668,9 +712,15 @@ Defines information about the socket connection.
| port | number | Yes | Port number. The value ranges from **0** to **65535**. | | port | number | Yes | Port number. The value ranges from **0** to **65535**. |
| size | number | Yes | Length of the server response message, in bytes. | | size | number | Yes | Length of the server response message, in bytes. |
## Description of UDP Error Codes
The UDP error code mapping is in the format of 2301000 + Linux kernel error code.
For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md).
## socket.constructTCPSocketInstance ## socket.constructTCPSocketInstance
constructTCPSocketInstance\(\): TCPSocket constructTCPSocketInstance(): TCPSocket
Creates a **TCPSocket** object. Creates a **TCPSocket** object.
...@@ -679,7 +729,7 @@ Creates a **TCPSocket** object. ...@@ -679,7 +729,7 @@ Creates a **TCPSocket** object.
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------------------- | ---------------------- | | :--------------------------------- | :---------------------- |
| [TCPSocket](#tcpsocket) | **TCPSocket** object.| | [TCPSocket](#tcpsocket) | **TCPSocket** object.|
**Example** **Example**
...@@ -695,7 +745,7 @@ Defines a TCPSocket connection. Before invoking TCPSocket APIs, you need to call ...@@ -695,7 +745,7 @@ Defines a TCPSocket connection. Before invoking TCPSocket APIs, you need to call
### bind ### bind
bind\(address: NetAddress, callback: AsyncCallback<void\>\): void bind(address: NetAddress, callback: AsyncCallback\<void\>): void
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result. Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result.
...@@ -710,6 +760,12 @@ Binds the IP address and port number. The port number can be specified or random ...@@ -710,6 +760,12 @@ Binds the IP address and port number. The port number can be specified or random
| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| | address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
...@@ -727,7 +783,7 @@ tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ...@@ -727,7 +783,7 @@ tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
### bind ### bind
bind\(address: NetAddress\): Promise<void\> bind(address: NetAddress): Promise\<void\>
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result. Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result.
...@@ -744,9 +800,16 @@ Binds the IP address and port number. The port number can be specified or random ...@@ -744,9 +800,16 @@ Binds the IP address and port number. The port number can be specified or random
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------- | ------------------------------------------------------- | | :-------------- | :------------------------------------------------------- |
| Promise\<void\> | Promise used to return the result.| | Promise\<void\> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -762,10 +825,13 @@ promise.then(() => { ...@@ -762,10 +825,13 @@ promise.then(() => {
### connect ### connect
connect\(options: TCPConnectOptions, callback: AsyncCallback<void\>\): void connect(options: TCPConnectOptions, callback: AsyncCallback\<void\>): void
Sets up a connection to the specified IP address and port number. This API uses an asynchronous callback to return the result. Sets up a connection to the specified IP address and port number. This API uses an asynchronous callback to return the result.
>**NOTE**
>This API can be called only after **bind** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -777,6 +843,13 @@ Sets up a connection to the specified IP address and port number. This API uses ...@@ -777,6 +843,13 @@ Sets up a connection to the specified IP address and port number. This API uses
| options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).| | options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -793,7 +866,7 @@ tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , time ...@@ -793,7 +866,7 @@ tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , time
### connect ### connect
connect\(options: TCPConnectOptions\): Promise<void\> connect(options: TCPConnectOptions): Promise\<void\>
Sets up a connection to the specified IP address and port number. This API uses a promise to return the result. Sets up a connection to the specified IP address and port number. This API uses a promise to return the result.
...@@ -810,9 +883,16 @@ Sets up a connection to the specified IP address and port number. This API uses ...@@ -810,9 +883,16 @@ Sets up a connection to the specified IP address and port number. This API uses
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------- | --------------------------------------------------------- | | :-------------- | :--------------------------------------------------------- |
| Promise\<void\> | Promise used to return the result.| | Promise\<void\> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -828,12 +908,12 @@ promise.then(() => { ...@@ -828,12 +908,12 @@ promise.then(() => {
### send ### send
send\(options: TCPSendOptions, callback: AsyncCallback<void\>\): void send(options: TCPSendOptions, callback: AsyncCallback\<void\>): void
Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result. Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/> >**NOTE**
>This API can be called only after [connect](#connect) is successfully called. >This API can be called only after **connect** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -846,6 +926,13 @@ Sends data over a TCPSocket connection. This API uses an asynchronous callback t ...@@ -846,6 +926,13 @@ Sends data over a TCPSocket connection. This API uses an asynchronous callback t
| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).| | options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -870,12 +957,12 @@ promise.then(() => { ...@@ -870,12 +957,12 @@ promise.then(() => {
### send ### send
send\(options: TCPSendOptions\): Promise<void\> send(options: TCPSendOptions): Promise\<void\>
Sends data over a TCPSocket connection. This API uses a promise to return the result. Sends data over a TCPSocket connection. This API uses a promise to return the result.
>**NOTE**<br/> >**NOTE**
>This API can be called only after [connect](#connect) is successfully called. >This API can be called only after **connect** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -890,9 +977,16 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re ...@@ -890,9 +977,16 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------- | ------------------------------------------------- | | :-------------- | :------------------------------------------------- |
| Promise\<void\> | Promise used to return the result.| | Promise\<void\> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -916,7 +1010,7 @@ promise1.then(() => { ...@@ -916,7 +1010,7 @@ promise1.then(() => {
### close ### close
close\(callback: AsyncCallback<void\>\): void close(callback: AsyncCallback\<void\>): void
Closes a TCPSocket connection. This API uses an asynchronous callback to return the result. Closes a TCPSocket connection. This API uses an asynchronous callback to return the result.
...@@ -930,6 +1024,11 @@ Closes a TCPSocket connection. This API uses an asynchronous callback to return ...@@ -930,6 +1024,11 @@ Closes a TCPSocket connection. This API uses an asynchronous callback to return
| -------- | --------------------- | ---- | ---------- | | -------- | --------------------- | ---- | ---------- |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 201 | Permission denied. |
**Example** **Example**
...@@ -947,7 +1046,7 @@ tcp.close(err => { ...@@ -947,7 +1046,7 @@ tcp.close(err => {
### close ### close
close\(\): Promise<void\> close(): Promise\<void\>
Closes a TCPSocket connection. This API uses a promise to return the result. Closes a TCPSocket connection. This API uses a promise to return the result.
...@@ -958,9 +1057,15 @@ Closes a TCPSocket connection. This API uses a promise to return the result. ...@@ -958,9 +1057,15 @@ Closes a TCPSocket connection. This API uses a promise to return the result.
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------- | ----------------------------------------- | | :-------------- | :----------------------------------------- |
| Promise\<void\> | Promise used to return the result.| | Promise\<void\> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -976,12 +1081,12 @@ promise.then(() => { ...@@ -976,12 +1081,12 @@ promise.then(() => {
### getRemoteAddress ### getRemoteAddress
getRemoteAddress\(callback: AsyncCallback<NetAddress\>\): void getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void
Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result. Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/> >**NOTE**
>This API can be called only after [connect](#connect) is successfully called. >This API can be called only after **connect** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -993,6 +1098,12 @@ Obtains the remote address of a socket connection. This API uses an asynchronous ...@@ -993,6 +1098,12 @@ Obtains the remote address of a socket connection. This API uses an asynchronous
| -------- | ------------------------------------------------- | ---- | ---------- | | -------- | ------------------------------------------------- | ---- | ---------- |
| callback | AsyncCallback<[NetAddress](#netaddress)> | Yes | Callback used to return the result.| | callback | AsyncCallback<[NetAddress](#netaddress)> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -1015,12 +1126,12 @@ promise.then(() => { ...@@ -1015,12 +1126,12 @@ promise.then(() => {
### getRemoteAddress ### getRemoteAddress
getRemoteAddress\(\): Promise<NetAddress\> getRemoteAddress(): Promise\<NetAddress\>
Obtains the remote address of a socket connection. This API uses a promise to return the result. Obtains the remote address of a socket connection. This API uses a promise to return the result.
>**NOTE**<br/> >**NOTE**
>This API can be called only after [connect](#connect) is successfully called. >This API can be called only after **connect** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -1029,9 +1140,15 @@ Obtains the remote address of a socket connection. This API uses a promise to re ...@@ -1029,9 +1140,15 @@ Obtains the remote address of a socket connection. This API uses a promise to re
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------------------------ | ------------------------------------------ | | :------------------------------------------ | :------------------------------------------ |
| Promise<[NetAddress](#netaddress)> | Promise used to return the result.| | Promise<[NetAddress](#netaddress)> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -1053,12 +1170,12 @@ promise1.then(() => { ...@@ -1053,12 +1170,12 @@ promise1.then(() => {
### getState ### getState
getState\(callback: AsyncCallback<SocketStateBase\>\): void getState(callback: AsyncCallback\<SocketStateBase\>): void
Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result. Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/> >**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. >This API can be called only after **bind** or **connect** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -1070,6 +1187,11 @@ Obtains the status of the TCPSocket connection. This API uses an asynchronous ca ...@@ -1070,6 +1187,11 @@ Obtains the status of the TCPSocket connection. This API uses an asynchronous ca
| -------- | ------------------------------------------------------ | ---- | ---------- | | -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result.| | callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 201 | Permission denied. |
**Example** **Example**
...@@ -1093,12 +1215,12 @@ promise.then(() => { ...@@ -1093,12 +1215,12 @@ promise.then(() => {
### getState ### getState
getState\(\): Promise<SocketStateBase\> getState(): Promise\<SocketStateBase\>
Obtains the status of the TCPSocket connection. This API uses a promise to return the result. Obtains the status of the TCPSocket connection. This API uses a promise to return the result.
>**NOTE**<br/> >**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. >This API can be called only after **bind** or **connect** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -1107,9 +1229,14 @@ Obtains the status of the TCPSocket connection. This API uses a promise to retur ...@@ -1107,9 +1229,14 @@ Obtains the status of the TCPSocket connection. This API uses a promise to retur
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------------------------- | ----------------------------------------- | | :----------------------------------------------- | :----------------------------------------- |
| Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.| | Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 201 | Permission denied. |
**Example** **Example**
...@@ -1132,12 +1259,12 @@ promise.then(() => { ...@@ -1132,12 +1259,12 @@ promise.then(() => {
### setExtraOptions ### setExtraOptions
setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): void setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void
Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result. Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/> >**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. >This API can be called only after **bind** or **connect** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -1150,6 +1277,13 @@ Sets other properties of the TCPSocket connection. This API uses an asynchronous ...@@ -1150,6 +1277,13 @@ Sets other properties of the TCPSocket connection. This API uses an asynchronous
| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| | options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -1181,12 +1315,12 @@ promise.then(() => { ...@@ -1181,12 +1315,12 @@ promise.then(() => {
### setExtraOptions ### setExtraOptions
setExtraOptions\(options: TCPExtraOptions\): Promise<void\> setExtraOptions(options: TCPExtraOptions): Promise\<void\>
Sets other properties of the TCPSocket connection. This API uses a promise to return the result. Sets other properties of the TCPSocket connection. This API uses a promise to return the result.
>**NOTE**<br/> >**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. >This API can be called only after **bind** or **connect** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -1201,9 +1335,15 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re ...@@ -1201,9 +1335,15 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------- | --------------------------------------------------- | | :-------------- | :--------------------------------------------------- |
| Promise\<void\> | Promise used to return the result.| | Promise\<void\> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
...@@ -1233,9 +1373,9 @@ promise.then(() => { ...@@ -1233,9 +1373,9 @@ promise.then(() => {
``` ```
### on\('message'\) ### on('message')
on\(type: 'message', callback: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
Enables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result. Enables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
...@@ -1258,13 +1398,13 @@ tcp.on('message', value => { ...@@ -1258,13 +1398,13 @@ tcp.on('message', value => {
``` ```
### off\('message'\) ### off('message')
off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void off(type: 'message', callback?: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/> >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -1284,15 +1424,15 @@ let callback = value =>{ ...@@ -1284,15 +1424,15 @@ 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');
``` ```
### on\('connect' | 'close'\) ### on('connect' | 'close')
on\(type: 'connect' | 'close', callback: Callback<void\>\): void on(type: 'connect' | 'close', callback: Callback\<void\>): void
Enables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result. Enables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
...@@ -1305,7 +1445,6 @@ Enables listening for connection or close events of the TCPSocket connection. Th ...@@ -1305,7 +1445,6 @@ Enables listening for connection or close events of the TCPSocket connection. Th
| type | string | Yes | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event| | type | string | Yes | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event|
| callback | Callback\<void\> | Yes | Callback used to return the result. | | callback | Callback\<void\> | Yes | Callback used to return the result. |
**Example** **Example**
```js ```js
...@@ -1319,13 +1458,13 @@ tcp.on('close', data => { ...@@ -1319,13 +1458,13 @@ tcp.on('close', data => {
``` ```
### off\('connect' | 'close'\) ### off('connect' | 'close')
off\(type: 'connect' | 'close', callback?: Callback<void\>\): void off(type: 'connect' | 'close', callback?: Callback\<void\>): void
Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/> >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -1345,22 +1484,22 @@ let callback1 = () =>{ ...@@ -1345,22 +1484,22 @@ 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');
``` ```
### on\('error'\) ### on('error')
on\(type: 'error', callback: ErrorCallback\): void on(type: 'error', callback: ErrorCallback): void
Enables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result. Enables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
...@@ -1383,13 +1522,13 @@ tcp.on('error', err => { ...@@ -1383,13 +1522,13 @@ tcp.on('error', err => {
``` ```
### off\('error'\) ### off('error')
off\(type: 'error', callback?: ErrorCallback\): void off(type: 'error', callback?: ErrorCallback): void
Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/> >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -1409,7 +1548,7 @@ let callback = err =>{ ...@@ -1409,7 +1548,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');
``` ```
...@@ -1452,7 +1591,13 @@ Defines other properties of the TCPSocket connection. ...@@ -1452,7 +1591,13 @@ Defines other properties of the TCPSocket connection.
| receiveBufferSize | number | No | Size of the receive buffer, in bytes. | | receiveBufferSize | number | No | Size of the receive buffer, in bytes. |
| sendBufferSize | number | No | Size of the send buffer, in bytes. | | sendBufferSize | number | No | Size of the send buffer, in bytes. |
| reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. | | reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. |
| socketTimeout | number | No | Timeout duration of the TCPSocket connection, in ms. | | socketTimeout | number | No | Timeout duration of the UDPSocket connection, in ms. |
## Description of TCP Error Codes
The TCP error code mapping is in the format of 2301000 + Linux kernel error code.
For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md).
## socket.constructTLSSocketInstance<sup>9+</sup> ## socket.constructTLSSocketInstance<sup>9+</sup>
...@@ -1465,7 +1610,7 @@ Creates a **TLSSocket** object. ...@@ -1465,7 +1610,7 @@ Creates a **TLSSocket** object.
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------------------- | ---------------------- | | :--------------------------------- | :---------------------- |
| [TLSSocket](#tlssocket9) | **TLSSocket** object.| | [TLSSocket](#tlssocket9) | **TLSSocket** object.|
**Example** **Example**
...@@ -1480,7 +1625,7 @@ Defines a TLSSocket connection. Before invoking TLSSocket APIs, you need to call ...@@ -1480,7 +1625,7 @@ Defines a TLSSocket connection. Before invoking TLSSocket APIs, you need to call
### bind<sup>9+</sup> ### bind<sup>9+</sup>
bind\(address: NetAddress, callback: AsyncCallback<void\>\): void bind(address: NetAddress, callback: AsyncCallback\<void\>): void
Binds the IP address and port number. This API uses an asynchronous callback to return the result. Binds the IP address and port number. This API uses an asynchronous callback to return the result.
...@@ -1518,7 +1663,7 @@ tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ...@@ -1518,7 +1663,7 @@ tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
### bind<sup>9+</sup> ### bind<sup>9+</sup>
bind\(address: NetAddress\): Promise<void\> bind(address: NetAddress): Promise\<void\>
Binds the IP address and port number. This API uses a promise to return the result. Binds the IP address and port number. This API uses a promise to return the result.
...@@ -1535,7 +1680,7 @@ Binds the IP address and port number. This API uses a promise to return the resu ...@@ -1535,7 +1680,7 @@ Binds the IP address and port number. This API uses a promise to return the resu
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------- | ------------------------------------------------------- | | :-------------- | :------------------------------------------------------- |
| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.| | Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes** **Error codes**
...@@ -1560,7 +1705,7 @@ promise.then(() => { ...@@ -1560,7 +1705,7 @@ promise.then(() => {
### getState<sup>9+</sup> ### getState<sup>9+</sup>
getState\(callback: AsyncCallback<SocketStateBase\>\): void getState(callback: AsyncCallback\<SocketStateBase\>): void
Obtains the status of the TLSSocket connection. This API uses an asynchronous callback to return the result. Obtains the status of the TLSSocket connection. This API uses an asynchronous callback to return the result.
...@@ -1600,7 +1745,7 @@ tls.getState((err, data) => { ...@@ -1600,7 +1745,7 @@ tls.getState((err, data) => {
### getState<sup>9+</sup> ### getState<sup>9+</sup>
getState\(\): Promise<SocketStateBase\> getState(): Promise\<SocketStateBase\>
Obtains the status of the TLSSocket connection. This API uses a promise to return the result. Obtains the status of the TLSSocket connection. This API uses a promise to return the result.
...@@ -1609,7 +1754,7 @@ Obtains the status of the TLSSocket connection. This API uses a promise to retur ...@@ -1609,7 +1754,7 @@ Obtains the status of the TLSSocket connection. This API uses a promise to retur
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------------------------- | ----------------------------------------- | | :----------------------------------------------- | :----------------------------------------- |
| Promise\<[SocketStateBase](#socketstatebase)> | Promise used to return the result. If the operation fails, an error message is returned.| | Promise\<[SocketStateBase](#socketstatebase)> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes** **Error codes**
...@@ -1639,7 +1784,7 @@ promise.then(() => { ...@@ -1639,7 +1784,7 @@ promise.then(() => {
### setExtraOptions<sup>9+</sup> ### setExtraOptions<sup>9+</sup>
setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): void setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void
Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses an asynchronous callback to return the result. Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses an asynchronous callback to return the result.
...@@ -1691,7 +1836,7 @@ tls.setExtraOptions({ ...@@ -1691,7 +1836,7 @@ tls.setExtraOptions({
### setExtraOptions<sup>9+</sup> ### setExtraOptions<sup>9+</sup>
setExtraOptions\(options: TCPExtraOptions\): Promise<void\> setExtraOptions(options: TCPExtraOptions): Promise\<void\>
Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses a promise to return the result. Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses a promise to return the result.
...@@ -1706,7 +1851,7 @@ Sets other properties of the TCPSocket connection after successful binding of th ...@@ -1706,7 +1851,7 @@ Sets other properties of the TCPSocket connection after successful binding of th
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------- | --------------------------------------------------- | | :-------------- | :--------------------------------------------------- |
| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.| | Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes** **Error codes**
...@@ -1746,7 +1891,7 @@ promise.then(() => { ...@@ -1746,7 +1891,7 @@ promise.then(() => {
### connect<sup>9+</sup> ### connect<sup>9+</sup>
connect(options: TLSConnectOptions, callback: AsyncCallback\<void>): void connect(options: TLSConnectOptions, callback: AsyncCallback\<void\>): void
Sets up a TLSSocket connection, and creates and initializes a TLS session after successful binding of the local IP address and port number of the TLSSocket connection. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. This API uses an asynchronous callback to return the result. Sets up a TLSSocket connection, and creates and initializes a TLS session after successful binding of the local IP address and port number of the TLSSocket connection. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. This API uses an asynchronous callback to return the result.
...@@ -1767,7 +1912,6 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after ...@@ -1767,7 +1912,6 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after
| 2303104 | Interrupted system call. | | 2303104 | Interrupted system call. |
| 2303109 | Bad file number. | | 2303109 | Bad file number. |
| 2303111 | Resource temporarily unavailable try again. | | 2303111 | Resource temporarily unavailable try again. |
| 2303113 | System permission denied. |
| 2303188 | Socket operation on non-socket. | | 2303188 | Socket operation on non-socket. |
| 2303191 | Protocol wrong type for socket. | | 2303191 | Protocol wrong type for socket. |
| 2303198 | Address already in use. | | 2303198 | Address already in use. |
...@@ -1784,7 +1928,7 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after ...@@ -1784,7 +1928,7 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after
```js ```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { tlsTwoWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
...@@ -1795,14 +1939,14 @@ let options = { ...@@ -1795,14 +1939,14 @@ let options = {
ALPNProtocols: ["spdy/1", "http/1.1"], ALPNProtocols: ["spdy/1", "http/1.1"],
address: { address: {
address: "192.168.xx.xxx", address: "192.168.xx.xxx",
port: xxxx, port: 8080,
family: 1, family: 1,
}, },
secureOptions: { secureOptions: {
key: "xxxx", key: "xxxx",
cert: "xxxx", cert: "xxxx",
ca: ["xxxx"], ca: ["xxxx"],
passwd: "xxxx", password: "xxxx",
protocols: [socket.Protocol.TLSv12], protocols: [socket.Protocol.TLSv12],
useRemoteCipherPrefer: true, useRemoteCipherPrefer: true,
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
...@@ -1810,12 +1954,12 @@ let options = { ...@@ -1810,12 +1954,12 @@ let options = {
}, },
}; };
tlsTwoWay.connect(options, (err, data) => { tlsTwoWay.connect(options, (err, data) => {
console.error(err); console.error("connect callback error"+err);
console.log(data); console.log(JSON.stringify(data));
}); });
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { tlsOneWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
...@@ -1825,7 +1969,7 @@ tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { ...@@ -1825,7 +1969,7 @@ tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
let oneWayOptions = { let oneWayOptions = {
address: { address: {
address: "192.168.xxx.xxx", address: "192.168.xxx.xxx",
port: xxxx, port: 8080,
family: 1, family: 1,
}, },
secureOptions: { secureOptions: {
...@@ -1834,14 +1978,14 @@ let oneWayOptions = { ...@@ -1834,14 +1978,14 @@ let oneWayOptions = {
}, },
}; };
tlsOneWay.connect(oneWayOptions, (err, data) => { tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err); console.error("connect callback error"+err);
console.log(data); console.log(JSON.stringify(data));
}); });
``` ```
### connect<sup>9+</sup> ### connect<sup>9+</sup>
connect(options: TLSConnectOptions): Promise\<void> connect(options: TLSConnectOptions): Promise\<void\>
Sets up a TLSSocket connection, and creates and initializes a TLS session after successful binding of the local IP address and port number of the TLSSocket connection. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. Both two-way and one-way authentication modes are supported. This API uses a promise to return the result. Sets up a TLSSocket connection, and creates and initializes a TLS session after successful binding of the local IP address and port number of the TLSSocket connection. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. Both two-way and one-way authentication modes are supported. This API uses a promise to return the result.
...@@ -1857,7 +2001,7 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after ...@@ -1857,7 +2001,7 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after
| Type | Description | | Type | Description |
| ------------------------------------------- | ----------------------------- | | ------------------------------------------- | ----------------------------- |
| Promise\<void> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.| | Promise\<void\> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes** **Error codes**
...@@ -1867,7 +2011,6 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after ...@@ -1867,7 +2011,6 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after
| 2303104 | Interrupted system call. | | 2303104 | Interrupted system call. |
| 2303109 | Bad file number. | | 2303109 | Bad file number. |
| 2303111 | Resource temporarily unavailable try again. | | 2303111 | Resource temporarily unavailable try again. |
| 2303113 | System permission denied. |
| 2303188 | Socket operation on non-socket. | | 2303188 | Socket operation on non-socket. |
| 2303191 | Protocol wrong type for socket. | | 2303191 | Protocol wrong type for socket. |
| 2303198 | Address already in use. | | 2303198 | Address already in use. |
...@@ -1884,7 +2027,7 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after ...@@ -1884,7 +2027,7 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after
```js ```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { tlsTwoWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
...@@ -1895,14 +2038,14 @@ let options = { ...@@ -1895,14 +2038,14 @@ let options = {
ALPNProtocols: ["spdy/1", "http/1.1"], ALPNProtocols: ["spdy/1", "http/1.1"],
address: { address: {
address: "xxxx", address: "xxxx",
port: xxxx, port: 8080,
family: 1, family: 1,
}, },
secureOptions: { secureOptions: {
key: "xxxx", key: "xxxx",
cert: "xxxx", cert: "xxxx",
ca: ["xxxx"], ca: ["xxxx"],
passwd: "xxxx", password: "xxxx",
protocols: [socket.Protocol.TLSv12], protocols: [socket.Protocol.TLSv12],
useRemoteCipherPrefer: true, useRemoteCipherPrefer: true,
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
...@@ -1910,13 +2053,13 @@ let options = { ...@@ -1910,13 +2053,13 @@ let options = {
}, },
}; };
tlsTwoWay.connect(options).then(data => { tlsTwoWay.connect(options).then(data => {
console.log(data); console.log(JSON.stringify(data));
}).catch(err => { }).catch(err => {
console.error(err); console.error(err);
}); });
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { tlsOneWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
...@@ -1926,7 +2069,7 @@ tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { ...@@ -1926,7 +2069,7 @@ tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
let oneWayOptions = { let oneWayOptions = {
address: { address: {
address: "192.168.xxx.xxx", address: "192.168.xxx.xxx",
port: xxxx, port: 8080,
family: 1, family: 1,
}, },
secureOptions: { secureOptions: {
...@@ -1935,7 +2078,7 @@ let oneWayOptions = { ...@@ -1935,7 +2078,7 @@ let oneWayOptions = {
}, },
}; };
tlsOneWay.connect(oneWayOptions).then(data => { tlsOneWay.connect(oneWayOptions).then(data => {
console.log(data); console.log(JSON.stringify(data));
}).catch(err => { }).catch(err => {
console.error(err); console.error(err);
}); });
...@@ -1943,7 +2086,7 @@ tlsOneWay.connect(oneWayOptions).then(data => { ...@@ -1943,7 +2086,7 @@ tlsOneWay.connect(oneWayOptions).then(data => {
### getRemoteAddress<sup>9+</sup> ### getRemoteAddress<sup>9+</sup>
getRemoteAddress\(callback: AsyncCallback<NetAddress\>\): void getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void
Obtains the remote address of a TLSSocket connection. This API uses an asynchronous callback to return the result. Obtains the remote address of a TLSSocket connection. This API uses an asynchronous callback to return the result.
...@@ -1953,7 +2096,7 @@ Obtains the remote address of a TLSSocket connection. This API uses an asynchron ...@@ -1953,7 +2096,7 @@ Obtains the remote address of a TLSSocket connection. This API uses an asynchron
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ---------- | | -------- | ------------------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. If the operation is successful, the remote address is returned. If the operation fails, an error message is returned.| | callback | AsyncCallback\<[NetAddress](#netaddress)\> | Yes | Callback used to return the result. If the operation is successful, the remote address is returned. If the operation fails, an error message is returned.|
**Error codes** **Error codes**
...@@ -1976,7 +2119,7 @@ tls.getRemoteAddress((err, data) => { ...@@ -1976,7 +2119,7 @@ tls.getRemoteAddress((err, data) => {
### getRemoteAddress<sup>9+</sup> ### getRemoteAddress<sup>9+</sup>
getRemoteAddress\(\): Promise\<NetAddress> getRemoteAddress(): Promise\<NetAddress\>
Obtains the remote address of a TLSSocket connection. This API uses a promise to return the result. Obtains the remote address of a TLSSocket connection. This API uses a promise to return the result.
...@@ -1985,7 +2128,7 @@ Obtains the remote address of a TLSSocket connection. This API uses a promise to ...@@ -1985,7 +2128,7 @@ Obtains the remote address of a TLSSocket connection. This API uses a promise to
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------------------------ | ------------------------------------------ | | :------------------------------------------ | :------------------------------------------ |
| Promise\<[NetAddress](#netaddress)> | Promise used to return the result. If the operation fails, an error message is returned.| | Promise\<[NetAddress](#netaddress)> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes** **Error codes**
...@@ -2008,7 +2151,7 @@ promise.then(() => { ...@@ -2008,7 +2151,7 @@ promise.then(() => {
### getCertificate<sup>9+</sup> ### getCertificate<sup>9+</sup>
getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void
Obtains the local digital certificate after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result. Obtains the local digital certificate after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result.
...@@ -2018,7 +2161,7 @@ Obtains the local digital certificate after a TLSSocket connection is establishe ...@@ -2018,7 +2161,7 @@ Obtains the local digital certificate after a TLSSocket connection is establishe
| Name | Type | Mandatory| Description| | Name | Type | Mandatory| Description|
| -------- | ----------------------------------------| ---- | ---------------| | -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | Yes | Callback used to return the result. If the operation is successful, the local certificate is returned. If the operation fails, an error message is returned.| | callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | Yes | Callback used to return the result. If the operation is successful, the local certificate is returned. If the operation fails, an error message is returned.|
**Error codes** **Error codes**
...@@ -2042,7 +2185,7 @@ tls.getCertificate((err, data) => { ...@@ -2042,7 +2185,7 @@ tls.getCertificate((err, data) => {
### getCertificate<sup>9+</sup> ### getCertificate<sup>9+</sup>
getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)> getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\>
Obtains the local digital certificate after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result. Obtains the local digital certificate after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result.
...@@ -2050,9 +2193,9 @@ Obtains the local digital certificate after a TLSSocket connection is establishe ...@@ -2050,9 +2193,9 @@ Obtains the local digital certificate after a TLSSocket connection is establishe
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------- | -------------------- | | -------------- | -------------------- |
| Promise\<[X509CertRawData](#x509certrawdata9)> | Promise used to return the result. If the operation fails, an error message is returned.| | Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes** **Error codes**
...@@ -2074,7 +2217,7 @@ tls.getCertificate().then(data => { ...@@ -2074,7 +2217,7 @@ tls.getCertificate().then(data => {
### getRemoteCertificate<sup>9+</sup> ### getRemoteCertificate<sup>9+</sup>
getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void
Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.
...@@ -2084,7 +2227,7 @@ Obtains the digital certificate of the server after a TLSSocket connection is es ...@@ -2084,7 +2227,7 @@ Obtains the digital certificate of the server after a TLSSocket connection is es
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ----------------------------------------| ---- | ---------------| | -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| | callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Error codes** **Error codes**
...@@ -2107,7 +2250,7 @@ tls.getRemoteCertificate((err, data) => { ...@@ -2107,7 +2250,7 @@ tls.getRemoteCertificate((err, data) => {
### getRemoteCertificate<sup>9+</sup> ### getRemoteCertificate<sup>9+</sup>
getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)> getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\>
Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses a promise to return the result. Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses a promise to return the result.
...@@ -2117,7 +2260,7 @@ Obtains the digital certificate of the server after a TLSSocket connection is es ...@@ -2117,7 +2260,7 @@ Obtains the digital certificate of the server after a TLSSocket connection is es
| Type | Description | | Type | Description |
| -------------- | -------------------- | | -------------- | -------------------- |
| Promise\<[X509CertRawData](#x509certrawdata9)> | Promise used to return the result. If the operation fails, an error message is returned.| | Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes** **Error codes**
...@@ -2138,7 +2281,7 @@ tls.getRemoteCertificate().then(data => { ...@@ -2138,7 +2281,7 @@ tls.getRemoteCertificate().then(data => {
### getProtocol<sup>9+</sup> ### getProtocol<sup>9+</sup>
getProtocol(callback: AsyncCallback\<string>): void getProtocol(callback: AsyncCallback\<string\>): void
Obtains the communication protocol version after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. Obtains the communication protocol version after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.
...@@ -2148,7 +2291,7 @@ Obtains the communication protocol version after a TLSSocket connection is estab ...@@ -2148,7 +2291,7 @@ Obtains the communication protocol version after a TLSSocket connection is estab
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------------------------| ---- | ---------------| | -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<string> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| | callback | AsyncCallback\<string\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Error codes** **Error codes**
...@@ -2172,7 +2315,7 @@ tls.getProtocol((err, data) => { ...@@ -2172,7 +2315,7 @@ tls.getProtocol((err, data) => {
### getProtocol<sup>9+</sup> ### getProtocol<sup>9+</sup>
getProtocol():Promise\<string> getProtocol():Promise\<string\>
Obtains the communication protocol version after a TLSSocket connection is established. This API uses a promise to return the result. Obtains the communication protocol version after a TLSSocket connection is established. This API uses a promise to return the result.
...@@ -2182,7 +2325,7 @@ Obtains the communication protocol version after a TLSSocket connection is estab ...@@ -2182,7 +2325,7 @@ Obtains the communication protocol version after a TLSSocket connection is estab
| Type | Description | | Type | Description |
| -------------- | -------------------- | | -------------- | -------------------- |
| Promise\<string> | Promise used to return the result. If the operation fails, an error message is returned.| | Promise\<string\> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes** **Error codes**
...@@ -2204,7 +2347,7 @@ tls.getProtocol().then(data => { ...@@ -2204,7 +2347,7 @@ tls.getProtocol().then(data => {
### getCipherSuite<sup>9+</sup> ### getCipherSuite<sup>9+</sup>
getCipherSuite(callback: AsyncCallback\<Array\<string>>): void getCipherSuite(callback: AsyncCallback\<Array\<string\>\>): void
Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.
...@@ -2214,7 +2357,7 @@ Obtains the cipher suite negotiated by both communication parties after a TLSSoc ...@@ -2214,7 +2357,7 @@ Obtains the cipher suite negotiated by both communication parties after a TLSSoc
| Name | Type | Mandatory| Description| | Name | Type | Mandatory| Description|
| -------- | ----------------------------------------| ---- | ---------------| | -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| | callback | AsyncCallback\<Array\<string\>\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Error codes** **Error codes**
...@@ -2239,7 +2382,7 @@ tls.getCipherSuite((err, data) => { ...@@ -2239,7 +2382,7 @@ tls.getCipherSuite((err, data) => {
### getCipherSuite<sup>9+</sup> ### getCipherSuite<sup>9+</sup>
getCipherSuite(): Promise\<Array\<string>> getCipherSuite(): Promise\<Array\<string\>\>
Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses a promise to return the result. Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses a promise to return the result.
...@@ -2249,7 +2392,7 @@ Obtains the cipher suite negotiated by both communication parties after a TLSSoc ...@@ -2249,7 +2392,7 @@ Obtains the cipher suite negotiated by both communication parties after a TLSSoc
| Type | Description | | Type | Description |
| ---------------------- | --------------------- | | ---------------------- | --------------------- |
| Promise\<Array\<string>> | Promise used to return the result. If the operation fails, an error message is returned.| | Promise\<Array\<string\>\> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes** **Error codes**
...@@ -2264,7 +2407,7 @@ Obtains the cipher suite negotiated by both communication parties after a TLSSoc ...@@ -2264,7 +2407,7 @@ Obtains the cipher suite negotiated by both communication parties after a TLSSoc
```js ```js
tls.getCipherSuite().then(data => { tls.getCipherSuite().then(data => {
console.log(data); console.log('getCipherSuite success:' + JSON.stringify(data));
}).catch(err => { }).catch(err => {
console.error(err); console.error(err);
}); });
...@@ -2272,7 +2415,7 @@ tls.getCipherSuite().then(data => { ...@@ -2272,7 +2415,7 @@ tls.getCipherSuite().then(data => {
### getSignatureAlgorithms<sup>9+</sup> ### getSignatureAlgorithms<sup>9+</sup>
getSignatureAlgorithms(callback: AsyncCallback\<Array\<string>>): void getSignatureAlgorithms(callback: AsyncCallback\<Array\<string\>\>): void
Obtains the signing algorithm negotiated by both communication parties after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result. Obtains the signing algorithm negotiated by both communication parties after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result.
...@@ -2282,7 +2425,7 @@ Obtains the signing algorithm negotiated by both communication parties after a T ...@@ -2282,7 +2425,7 @@ Obtains the signing algorithm negotiated by both communication parties after a T
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------------------------| ---- | ---------------| | -------- | -------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return the result. | | callback | AsyncCallback\<Array\<string\>\> | Yes | Callback used to return the result. |
**Error codes** **Error codes**
...@@ -2305,7 +2448,7 @@ tls.getSignatureAlgorithms((err, data) => { ...@@ -2305,7 +2448,7 @@ tls.getSignatureAlgorithms((err, data) => {
### getSignatureAlgorithms<sup>9+</sup> ### getSignatureAlgorithms<sup>9+</sup>
getSignatureAlgorithms(): Promise\<Array\<string>> getSignatureAlgorithms(): Promise\<Array\<string\>\>
Obtains the signing algorithm negotiated by both communication parties after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result. Obtains the signing algorithm negotiated by both communication parties after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result.
...@@ -2315,7 +2458,7 @@ Obtains the signing algorithm negotiated by both communication parties after a T ...@@ -2315,7 +2458,7 @@ Obtains the signing algorithm negotiated by both communication parties after a T
| Type | Description | | Type | Description |
| ---------------------- | -------------------- | | ---------------------- | -------------------- |
| Promise\<Array\<string>> | Promise used to return the result.| | Promise\<Array\<string\>\> | Promise used to return the result.|
**Error codes** **Error codes**
...@@ -2328,7 +2471,7 @@ Obtains the signing algorithm negotiated by both communication parties after a T ...@@ -2328,7 +2471,7 @@ Obtains the signing algorithm negotiated by both communication parties after a T
```js ```js
tls.getSignatureAlgorithms().then(data => { tls.getSignatureAlgorithms().then(data => {
console.log(data); console.log("getSignatureAlgorithms success" + data);
}).catch(err => { }).catch(err => {
console.error(err); console.error(err);
}); });
...@@ -2336,7 +2479,7 @@ tls.getSignatureAlgorithms().then(data => { ...@@ -2336,7 +2479,7 @@ tls.getSignatureAlgorithms().then(data => {
### send<sup>9+</sup> ### send<sup>9+</sup>
send(data: string, callback: AsyncCallback\<void>): void send(data: string, callback: AsyncCallback\<void\>): void
Sends a message to the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. Sends a message to the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.
...@@ -2347,7 +2490,7 @@ Sends a message to the server after a TLSSocket connection is established. This ...@@ -2347,7 +2490,7 @@ Sends a message to the server after a TLSSocket connection is established. This
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -----------------------------| ---- | ---------------| | -------- | -----------------------------| ---- | ---------------|
| data | string | Yes | Data content of the message to send. | | data | string | Yes | Data content of the message to send. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Error codes** **Error codes**
...@@ -2374,7 +2517,7 @@ tls.send("xxxx", (err) => { ...@@ -2374,7 +2517,7 @@ tls.send("xxxx", (err) => {
### send<sup>9+</sup> ### send<sup>9+</sup>
send(data: string): Promise\<void> send(data: string): Promise\<void\>
Sends a message to the server after a TLSSocket connection is established. This API uses a promise to return the result. Sends a message to the server after a TLSSocket connection is established. This API uses a promise to return the result.
...@@ -2401,7 +2544,7 @@ Sends a message to the server after a TLSSocket connection is established. This ...@@ -2401,7 +2544,7 @@ Sends a message to the server after a TLSSocket connection is established. This
| Type | Description | | Type | Description |
| -------------- | -------------------- | | -------------- | -------------------- |
| Promise\<void> | Promise used to return the result. If the operation fails, an error message is returned.| | Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
**Example** **Example**
...@@ -2415,7 +2558,7 @@ tls.send("xxxx").then(() =>{ ...@@ -2415,7 +2558,7 @@ tls.send("xxxx").then(() =>{
### close<sup>9+</sup> ### close<sup>9+</sup>
close(callback: AsyncCallback\<void>): void close(callback: AsyncCallback\<void\>): void
Closes a TLSSocket connection. This API uses an asynchronous callback to return the result. Closes a TLSSocket connection. This API uses an asynchronous callback to return the result.
...@@ -2425,7 +2568,7 @@ Closes a TLSSocket connection. This API uses an asynchronous callback to return ...@@ -2425,7 +2568,7 @@ Closes a TLSSocket connection. This API uses an asynchronous callback to return
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -----------------------------| ---- | ---------------| | -------- | -----------------------------| ---- | ---------------|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Error codes** **Error codes**
...@@ -2450,7 +2593,7 @@ tls.close((err) => { ...@@ -2450,7 +2593,7 @@ tls.close((err) => {
### close<sup>9+</sup> ### close<sup>9+</sup>
close(): Promise\<void> close(): Promise\<void\>
Closes a TLSSocket connection. This API uses a promise to return the result. Closes a TLSSocket connection. This API uses a promise to return the result.
...@@ -2460,7 +2603,7 @@ Closes a TLSSocket connection. This API uses a promise to return the result. ...@@ -2460,7 +2603,7 @@ Closes a TLSSocket connection. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| -------------- | -------------------- | | -------------- | -------------------- |
| Promise\<void> | Promise used to return the result. If the operation fails, an error message is returned.| | Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes** **Error codes**
...@@ -2491,7 +2634,7 @@ Defines TLS connection options. ...@@ -2491,7 +2634,7 @@ Defines TLS connection options.
| -------------- | ------------------------------------- | --- |-------------- | | -------------- | ------------------------------------- | --- |-------------- |
| address | [NetAddress](#netaddress) | Yes | Gateway address. | | address | [NetAddress](#netaddress) | Yes | Gateway address. |
| secureOptions | [TLSSecureOptions](#tlssecureoptions9) | Yes| TLS security options.| | secureOptions | [TLSSecureOptions](#tlssecureoptions9) | Yes| TLS security options.|
| ALPNProtocols | Array\<string> | Yes| Application Layer Protocol Negotiation (ALPN) protocols. | | ALPNProtocols | Array\<string\> | No| Application Layer Protocol Negotiation (ALPN) protocols. |
## TLSSecureOptions<sup>9+</sup> ## TLSSecureOptions<sup>9+</sup>
...@@ -2501,11 +2644,11 @@ Defines TLS security options. The CA certificate is mandatory, and other paramet ...@@ -2501,11 +2644,11 @@ Defines TLS security options. The CA certificate is mandatory, and other paramet
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------------------- | ------------------------------------------------------ | --- |----------------------------------- | | --------------------- | ------------------------------------------------------ | --- |----------------------------------- |
| ca | string \| Array\<string> | Yes| CA certificate of the server, which is used to authenticate the digital certificate of the server.| | ca | string \| Array\<string\> | Yes| CA certificate of the server, which is used to authenticate the digital certificate of the server.|
| cert | string | No| Digital certificate of the local client. | | cert | string | No| Digital certificate of the local client. |
| key | string | No| Private key of the local digital certificate. | | key | string | No| Private key of the local digital certificate. |
| passwd | string | No| Password for reading the private key. | | password | string | No| Password for reading the private key. |
| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)> | No| TLS protocol version. | | protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)\> | No| TLS protocol version. |
| useRemoteCipherPrefer | boolean | No| Whether to use the remote cipher suite preferentially. | | useRemoteCipherPrefer | boolean | No| Whether to use the remote cipher suite preferentially. |
| signatureAlgorithms | string | No| Signing algorithm used during communication. | | signatureAlgorithms | string | No| Signing algorithm used during communication. |
| cipherSuite | string | No| Cipher suite used during communication. | | cipherSuite | string | No| Cipher suite used during communication. |
......
# @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 the 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 the 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 data type 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,8 +84,8 @@ export default { ...@@ -85,8 +84,8 @@ export default {
``` ```
> **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:
> >
> ``` > ```
> { > {
......
# Network State # @system.network (Network State)
> **NOTE**<br> > **NOTE**
> - 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 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 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 [FetchResponse](#fetchresponse). | | 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.|
One of the following error codes will be returned if the operation fails. 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. The return value is [FetchResponse](#fetchresponse). | | 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.|
One of the following error codes will be returned if the listening fails. 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**
...@@ -122,7 +122,9 @@ export default { ...@@ -122,7 +122,9 @@ export default {
## NetworkResponse ## NetworkResponse
| Name | 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.usbV9 (USB Management) # @ohos.usbV9 (USB)
The **usb** 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 USB 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.
> **NOTE**<br> > **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs provided by this module are no longer maintained since API version 9. You are advised to use [`@ohos.usbManager`](js-apis-usbManager.md) instead. >
> The APIs provided by this module are no longer maintained since API version 9. You are advised to use [`@ohos.usbManager`](js-apis-usbManager.md).
## Modules to Import ## Modules to Import
...@@ -30,7 +32,7 @@ Obtains the list of USB devices connected to the host. If no device is connected ...@@ -30,7 +32,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:
[ [
...@@ -87,7 +89,7 @@ console.log(`devicesList = ${JSON.stringify(devicesList)}`); ...@@ -87,7 +89,7 @@ console.log(`devicesList = ${JSON.stringify(devicesList)}`);
connectDevice(device: USBDevice): Readonly&lt;USBDevicePipe&gt; connectDevice(device: USBDevice): Readonly&lt;USBDevicePipe&gt;
Connects to a USB device based on the device list obtained by using **getDevices()**. Connects to the USB device based on the device information returned by **getDevices()**.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and device information, and then call [usb.requestRight](#usbrequestright) to request the device access permission. Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and device information, and then call [usb.requestRight](#usbrequestright) to request the device access permission.
...@@ -119,13 +121,12 @@ For details about the error codes, see [USB Error Codes](../errorcodes/errorcode ...@@ -119,13 +121,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
...@@ -134,7 +135,7 @@ hasRight(deviceName: string): boolean ...@@ -134,7 +135,7 @@ hasRight(deviceName: string): boolean
Checks whether the application has the permission to access the device. Checks whether the application has the permission to access the device.
The value **true** is returned if the device access permission is available; the value **false** is returned otherwise. Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise.
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
...@@ -183,7 +184,7 @@ Requests the temporary permission for the application to access a USB device. Th ...@@ -183,7 +184,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 +212,7 @@ Removes the permission for the application to access a USB device. ...@@ -211,7 +212,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 +247,7 @@ Adds the permission for the application to access a USB device. ...@@ -246,7 +247,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 +456,9 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ...@@ -455,8 +456,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 +494,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ...@@ -492,7 +494,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 +581,7 @@ Converts the USB function list in the numeric mask format to a string in Device ...@@ -579,7 +581,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 +610,7 @@ Sets the current USB function list in Device mode. ...@@ -608,7 +610,7 @@ Sets the current USB function list in Device mode.
**Example** **Example**
```js ```js
let funcs = HDC; let funcs = usb.HDC;
let ret = usb.setCurrentFunctions(funcs); let ret = usb.setCurrentFunctions(funcs);
``` ```
...@@ -711,7 +713,12 @@ Sets the role types supported by a specified port, which can be **powerRole** (f ...@@ -711,7 +713,12 @@ Sets the role types supported by a specified port, which can be **powerRole** (f
**Example** **Example**
```js ```js
let ret = usb.getSupportedModes(0); let portId = 1;
usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => {
console.info('usb setPortRoles successfully.');
}).catch(err => {
console.error('usb setPortRoles failed: ' + err.code + ' message: ' + err.message);
});
``` ```
## USBEndpoint ## USBEndpoint
...@@ -722,14 +729,14 @@ Represents the USB endpoint from which data is sent or received. You can obtain ...@@ -722,14 +729,14 @@ Represents the USB endpoint from which data is sent or received. You can obtain
| Name | Type | Mandatory |Description | | Name | Type | Mandatory |Description |
| ------------- | ------------------------------------------- | ------------- |------------- | | ------------- | ------------------------------------------- | ------------- |------------- |
| address | number | Yes | Endpoint address. | | address | number | Yes|Endpoint address. |
| attributes | number | Yes | Endpoint attributes. | | attributes | number | Yes|Endpoint attributes. |
| interval | number | Yes | Endpoint interval. | | interval | number | Yes|Endpoint interval. |
| maxPacketSize | number | Yes | Maximum size of data packets on the endpoint. | | maxPacketSize | number | Yes|Maximum size of data packets on the endpoint. |
| direction | [USBRequestDirection](#usbrequestdirection) | Yes | Endpoint direction. | | direction | [USBRequestDirection](#usbrequestdirection) | Yes|Endpoint direction. |
| number | number | Yes | Endpoint number. | | number | number | Yes|Endpoint number. |
| type | number | Yes | Endpoint type. | | type | number | Yes|Endpoint type. |
| interfaceId | number | Yes | Unique ID of the interface to which the endpoint belongs.| | interfaceId | number | Yes|Unique ID of the interface to which the endpoint belongs.|
## USBInterface ## USBInterface
...@@ -739,13 +746,13 @@ Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **U ...@@ -739,13 +746,13 @@ Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **U
| Name | Type | Mandatory |Description | | Name | Type | Mandatory |Description |
| ---------------- | ---------------------------------------- | ------------- |--------------------- | | ---------------- | ---------------------------------------- | ------------- |--------------------- |
| id | number | Yes | Unique ID of the USB interface. | | id | number | Yes|Unique ID of the USB interface. |
| protocol | number | Yes | Interface protocol. | | protocol | number | Yes|Interface protocol. |
| clazz | number | Yes | Device type. | | clazz | number | Yes|Device type. |
| subClass | number | Yes | Device subclass. | | subClass | number | Yes|Device subclass. |
| alternateSetting | number | Yes | Settings for alternating between descriptors of the same USB interface.| | alternateSetting | number | Yes|Settings for alternating between descriptors of the same USB interface.|
| name | string | Yes | Interface name. | | name | string | Yes|Interface name. |
| endpoints | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Yes | Endpoints that belong to the USB interface. | | endpoints | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Yes|Endpoints that belong to the USB interface. |
## USBConfig ## USBConfig
...@@ -755,13 +762,13 @@ Represents the USB configuration. One [USBDevice](#usbdevice) can contain multip ...@@ -755,13 +762,13 @@ Represents the USB configuration. One [USBDevice](#usbdevice) can contain multip
| Name | Type | Mandatory |Description | | Name | Type | Mandatory |Description |
| -------------- | ------------------------------------------------ | --------------- |--------------- | | -------------- | ------------------------------------------------ | --------------- |--------------- |
| id | number | Yes | Unique ID of the USB configuration. | | id | number | Yes|Unique ID of the USB configuration. |
| attributes | number | Yes | Configuration attributes. | | attributes | number | Yes|Configuration attributes. |
| maxPower | number | Yes | Maximum power consumption, in mA. | | maxPower | number | Yes|Maximum power consumption, in mA. |
| name | string | Yes | Configuration name, which can be left empty. | | name | string | Yes|Configuration name, which can be left empty. |
| isRemoteWakeup | boolean | Yes | Support for remote wakeup.| | isRemoteWakeup | boolean | Yes|Support for remote wakeup.|
| isSelfPowered | boolean | Yes | Support for independent power supplies.| | isSelfPowered | boolean | Yes| Support for independent power supplies.|
| interfaces | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Yes | Supported interface attributes. | | interfaces | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Yes|Supported interface attributes. |
## USBDevice ## USBDevice
...@@ -771,19 +778,19 @@ Represents the USB device information. ...@@ -771,19 +778,19 @@ Represents the USB device information.
| Name | Type | Mandatory |Description | | Name | Type | Mandatory |Description |
| ---------------- | ------------------------------------ | ---------- |---------- | | ---------------- | ------------------------------------ | ---------- |---------- |
| busNum | number | Yes | Bus address. | | busNum | number | Yes|Bus address. |
| devAddress | number | Yes | Device address. | | devAddress | number | Yes|Device address. |
| serial | string | Yes | Sequence number. | | serial | string | Yes|Sequence number. |
| name | string | Yes | Device name. | | name | string | Yes|Device name. |
| manufacturerName | string | Yes | Device manufacturer. | | manufacturerName | string | Yes| Device manufacturer. |
| productName | string | Yes | Product name. | | productName | string | Yes|Product name. |
| version | string | Yes | Version number. | | version | string | Yes|Version number. |
| vendorId | number | Yes | Vendor ID. | | vendorId | number | Yes|Vendor ID. |
| productId | number | Yes | Product ID. | | productId | number | Yes|Product ID. |
| clazz | number | Yes | Device class. | | clazz | number | Yes|Device class. |
| subClass | number | Yes | Device subclass. | | subClass | number | Yes|Device subclass. |
| protocol | number | Yes | Device protocol code. | | protocol | number | Yes|Device protocol code. |
| configs | Array&lt;[USBConfig](#usbconfig)&gt; | Yes | Device configuration descriptor information.| | configs | Array&lt;[USBConfig](#usbconfig)&gt; | Yes|Device configuration descriptor information.|
## USBDevicePipe ## USBDevicePipe
...@@ -804,12 +811,12 @@ Represents control transfer parameters. ...@@ -804,12 +811,12 @@ Represents control transfer parameters.
| Name | Type | Mandatory |Description | | Name | Type | Mandatory |Description |
| ------- | ----------------------------------------------- | ---------------- |---------------- | | ------- | ----------------------------------------------- | ---------------- |---------------- |
| request | number | Yes | Request type. | | request | number | Yes |Request type. |
| target | [USBRequestTargetType](#usbrequesttargettype) | Yes | Request target type. | | target | [USBRequestTargetType](#usbrequesttargettype) | Yes |Request target type. |
| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes | Control request type. | | reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes |Control request type. |
| value | number | Yes | Request parameter value. | | value | number | Yes |Request parameter value. |
| index | number | Yes | Index of the request parameter value.| | index | number | Yes |Index of the request parameter value.|
| data | Uint8Array | Yes | Buffer for writing or reading data. | | data | Uint8Array | Yes |Buffer for writing or reading data. |
## USBPort ## USBPort
...@@ -821,9 +828,9 @@ Represents a USB port. ...@@ -821,9 +828,9 @@ Represents a USB port.
| Name | Type | Mandatory |Description | | Name | Type | Mandatory |Description |
| -------------- | ------------------------------- | ------------------- |------------------------ | | -------------- | ------------------------------- | ------------------- |------------------------ |
| id | number | Yes | Unique identifier of a USB port. | | id | number | Yes |Unique identifier of a USB port. |
| supportedModes | [PortModeType](#portmodetype) | Yes | Numeric mask combination for the supported mode list.| | supportedModes | [PortModeType](#portmodetype) | Yes |Numeric mask combination for the supported mode list.|
| status | [USBPortStatus](#usbportstatus) | Yes | USB port role. | | status | [USBPortStatus](#usbportstatus) | Yes |USB port role. |
## USBPortStatus ## USBPortStatus
...@@ -835,9 +842,9 @@ Enumerates USB port roles. ...@@ -835,9 +842,9 @@ Enumerates USB port roles.
| Name | Type| Mandatory |Description | | Name | Type| Mandatory |Description |
| ---------------- | -------- | ---------------- |---------------------- | | ---------------- | -------- | ---------------- |---------------------- |
| currentMode | number | Yes | Current USB mode. | | currentMode | number | Yes|Current USB mode. |
| currentPowerRole | number | Yes | Current power role. | | currentPowerRole | number | Yes |Current power role. |
| currentDataRole | number | Yes | Current data role.| | currentDataRole | number | Yes |Current data role.|
## USBRequestTargetType ## USBRequestTargetType
...@@ -845,12 +852,12 @@ Enumerates request target types. ...@@ -845,12 +852,12 @@ Enumerates request target types.
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Value | Description | | Name | Value | Description |
| ---------------------------- | ----- | ----------- | | ---------------------------- | ---- | ------ |
| USB_REQUEST_TARGET_DEVICE | 0 | Device | | USB_REQUEST_TARGET_DEVICE | 0 | Device|
| USB_REQUEST_TARGET_INTERFACE | 1 | Interface | | USB_REQUEST_TARGET_INTERFACE | 1 | Interface|
| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint | | USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint|
| USB_REQUEST_TARGET_OTHER | 3 | Other | | USB_REQUEST_TARGET_OTHER | 3 | Other|
## USBControlRequestType ## USBControlRequestType
......
...@@ -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)}`); cconsole.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);
......
# @ohos.net.webSocket (WebSocket Connection) # # @ohos.net.webSocket (WebSocket Connection)
The **webSocket** module implements WebSocket connection management and operation. > **NOTE**
>
> **NOTE**<br>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -17,7 +16,7 @@ If an error occurs in any of the preceding processes, the client will receive a ...@@ -17,7 +16,7 @@ If an error occurs in any of the preceding processes, the client will receive a
import webSocket from '@ohos.net.webSocket'; import webSocket from '@ohos.net.webSocket';
``` ```
## Complete Example ## Examples
```js ```js
import webSocket from '@ohos.net.webSocket'; import webSocket from '@ohos.net.webSocket';
...@@ -37,7 +36,7 @@ ws.on('open', (err, value) => { ...@@ -37,7 +36,7 @@ ws.on('open', (err, value) => {
}); });
ws.on('message', (err, value) => { ws.on('message', (err, value) => {
console.log("on message, message:" + value); console.log("on message, message:" + value);
// When receiving the bye message (the actual message name may differ) from the server, the client proactively disconnects from the server. // When receiving the `bye` message (the actual message name may differ) from the server, the client proactively disconnects from the server.
if (value === 'bye') { if (value === 'bye') {
ws.close((err, value) => { ws.close((err, value) => {
if (!err) { if (!err) {
...@@ -49,7 +48,7 @@ ws.on('message', (err, value) => { ...@@ -49,7 +48,7 @@ ws.on('message', (err, value) => {
} }
}); });
ws.on('close', (err, value) => { ws.on('close', (err, value) => {
console.log("on close, code is " + value['code'] + ", reason is " + value['reason']); console.log("on close, code is " + value.code + ", reason is " + value.reason);
}); });
ws.on('error', (err) => { ws.on('error', (err) => {
console.log("on error, error:" + JSON.stringify(err)); console.log("on error, error:" + JSON.stringify(err));
...@@ -65,13 +64,13 @@ ws.connect(defaultIpAddress, (err, value) => { ...@@ -65,13 +64,13 @@ ws.connect(defaultIpAddress, (err, value) => {
## webSocket.createWebSocket ## webSocket.createWebSocket
createWebSocket\(\): WebSocket createWebSocket(): WebSocket
Creates a WebSocket connection. You can use this API to create or close a WebSocket connection, send data over it, or enable or disable listening for the **open**, **close**, **message**, and **error** events. Creates a WebSocket connection. You can use this API to create or close a WebSocket connection, send data over it, or enable or disable listening for the **open**, **close**, **message**, and **error** events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :---------------------------------- | :----------------------------------------------------------- | | :---------------------------------- | :----------------------------------------------------------- |
...@@ -90,11 +89,11 @@ Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call ...@@ -90,11 +89,11 @@ Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call
### connect ### connect
connect\(url: string, callback: AsyncCallback<boolean\>\): void connect(url: string, callback: AsyncCallback\<boolean\>): void
Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result. Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -105,6 +104,12 @@ Initiates a WebSocket request to establish a WebSocket connection to a given URL ...@@ -105,6 +104,12 @@ Initiates a WebSocket request to establish a WebSocket connection to a given URL
| url | string | Yes | URL for establishing a WebSocket connection.| | url | string | Yes | URL for establishing a WebSocket connection.|
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
...@@ -123,11 +128,11 @@ ws.connect(url, (err, value) => { ...@@ -123,11 +128,11 @@ ws.connect(url, (err, value) => {
### connect ### connect
connect\(url: string, options: WebSocketRequestOptions, callback: AsyncCallback<boolean\>\): void connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\<boolean\>): void
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result. Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -139,6 +144,12 @@ Initiates a WebSocket request carrying specified options to establish a WebSocke ...@@ -139,6 +144,12 @@ Initiates a WebSocket request carrying specified options to establish a WebSocke
| options | WebSocketRequestOptions | Yes | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).| | options | WebSocketRequestOptions | Yes | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).|
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
...@@ -162,11 +173,11 @@ ws.connect(url, { ...@@ -162,11 +173,11 @@ ws.connect(url, {
### connect ### connect
connect\(url: string, options?: WebSocketRequestOptions\): Promise<boolean\> connect(url: string, options?: WebSocketRequestOptions): Promise\<boolean\>
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result. Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -177,12 +188,19 @@ Initiates a WebSocket request carrying specified options to establish a WebSocke ...@@ -177,12 +188,19 @@ Initiates a WebSocket request carrying specified options to establish a WebSocke
| url | string | Yes | URL for establishing a WebSocket connection. | | url | string | Yes | URL for establishing a WebSocket connection. |
| options | WebSocketRequestOptions | No | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).| | options | WebSocketRequestOptions | No | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :----------------- | :-------------------------------- | | :----------------- | :-------------------------------- |
| Promise\<boolean\> | Promise used to return the result.| | Promise\<boolean\> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -199,11 +217,11 @@ promise.then((value) => { ...@@ -199,11 +217,11 @@ promise.then((value) => {
### send ### send
send\(data: string | ArrayBuffer, callback: AsyncCallback<boolean\>\): void send(data: string | ArrayBuffer, callback: AsyncCallback\<boolean\>): void
Sends data through a WebSocket connection. This API uses an asynchronous callback to return the result. Sends data through a WebSocket connection. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -211,9 +229,16 @@ Sends data through a WebSocket connection. This API uses an asynchronous callbac ...@@ -211,9 +229,16 @@ Sends data through a WebSocket connection. This API uses an asynchronous callbac
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ------------ | | -------- | ------------------------ | ---- | ------------ |
| data | string \| ArrayBuffer <sup>8+</sup> | Yes | Data to send.| | data | string \| ArrayBuffer | Yes | Data to send.<br>Only the string type is supported for API version 6 or earlier. Both the string and ArrayBuffer types are supported for API version 8 or later.|
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -233,11 +258,11 @@ ws.connect(url, (err, value) => { ...@@ -233,11 +258,11 @@ ws.connect(url, (err, value) => {
### send ### send
send\(data: string | ArrayBuffer\): Promise<boolean\> send(data: string | ArrayBuffer): Promise\<boolean\>
Sends data through a WebSocket connection. This API uses a promise to return the result. Sends data through a WebSocket connection. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -245,14 +270,21 @@ Sends data through a WebSocket connection. This API uses a promise to return the ...@@ -245,14 +270,21 @@ Sends data through a WebSocket connection. This API uses a promise to return the
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------ | | ------ | ------ | ---- | ------------ |
| data | string \| ArrayBuffer <sup>8+</sup> | Yes | Data to send.| | data | string \| ArrayBuffer | Yes | Data to send.<br>Only the string type is supported for API version 6 or earlier. Both the string and ArrayBuffer types are supported for API version 8 or later.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :----------------- | :-------------------------------- | | :----------------- | :-------------------------------- |
| Promise\<boolean\> | Promise used to return the result.| | Promise\<boolean\> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -271,11 +303,11 @@ ws.connect(url, (err, value) => { ...@@ -271,11 +303,11 @@ ws.connect(url, (err, value) => {
### close ### close
close\(callback: AsyncCallback<boolean\>\): void close(callback: AsyncCallback\<boolean\>): void
Closes a WebSocket connection. This API uses an asynchronous callback to return the result. Closes a WebSocket connection. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -285,6 +317,13 @@ Closes a WebSocket connection. This API uses an asynchronous callback to return ...@@ -285,6 +317,13 @@ Closes a WebSocket connection. This API uses an asynchronous callback to return
| -------- | ------------------------ | ---- | ---------- | | -------- | ------------------------ | ---- | ---------- |
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result.| | callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -302,11 +341,11 @@ ws.close((err, value) => { ...@@ -302,11 +341,11 @@ ws.close((err, value) => {
### close ### close
close\(options: WebSocketCloseOptions, callback: AsyncCallback<boolean\>\): void close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void
Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses an asynchronous callback to return the result. Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -317,6 +356,13 @@ Closes a WebSocket connection carrying specified options such as **code** and ** ...@@ -317,6 +356,13 @@ Closes a WebSocket connection carrying specified options such as **code** and **
| options | WebSocketCloseOptions | Yes | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).| | options | WebSocketCloseOptions | Yes | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).|
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -337,11 +383,11 @@ ws.close({ ...@@ -337,11 +383,11 @@ ws.close({
### close ### close
close\(options?: WebSocketCloseOptions\): Promise<boolean\> close(options?: WebSocketCloseOptions): Promise\<boolean\>
Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses a promise to return the result. Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -351,12 +397,19 @@ Closes a WebSocket connection carrying specified options such as **code** and ** ...@@ -351,12 +397,19 @@ Closes a WebSocket connection carrying specified options such as **code** and **
| ------- | --------------------- | ---- | ----------------------------------------------------- | | ------- | --------------------- | ---- | ----------------------------------------------------- |
| options | WebSocketCloseOptions | No | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).| | options | WebSocketCloseOptions | No | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :----------------- | :-------------------------------- | | :----------------- | :-------------------------------- |
| Promise\<boolean\> | Promise used to return the result.| | Promise\<boolean\> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example** **Example**
```js ```js
...@@ -374,9 +427,9 @@ promise.then((value) => { ...@@ -374,9 +427,9 @@ promise.then((value) => {
``` ```
### on\('open'\) ### on('open')
on\(type: 'open', callback: AsyncCallback<Object\>\): void on(type: 'open', callback: AsyncCallback\<Object\>): void
Enables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result. Enables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
...@@ -400,13 +453,13 @@ ws.on('open', (err, value) => { ...@@ -400,13 +453,13 @@ ws.on('open', (err, value) => {
``` ```
### off\('open'\) ### off('open')
off\(type: 'open', callback?: AsyncCallback<Object\>\): void off(type: 'open', callback?: AsyncCallback\<Object\>): void
Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result. Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -431,14 +484,14 @@ ws.off('open', callback1); ...@@ -431,14 +484,14 @@ ws.off('open', callback1);
``` ```
### on\('message'\) ### on('message')
on\(type: 'message', callback: AsyncCallback<string | ArrayBuffer\>\): void on(type: 'message', callback: AsyncCallback\<string | ArrayBuffer\>): void
Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented. Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). >The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8).
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -449,7 +502,6 @@ Enables listening for the **message** events of a WebSocket connection. This API ...@@ -449,7 +502,6 @@ Enables listening for the **message** events of a WebSocket connection. This API
| type | string | Yes | Event type.<br />**message**: event indicating that a message has been received from the server.| | type | string | Yes | Event type.<br />**message**: event indicating that a message has been received from the server.|
| callback | AsyncCallback\<string \| ArrayBuffer <sup>8+</sup>\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<string \| ArrayBuffer <sup>8+</sup>\> | Yes | Callback used to return the result. |
**Example** **Example**
```js ```js
...@@ -460,14 +512,14 @@ ws.on('message', (err, value) => { ...@@ -460,14 +512,14 @@ ws.on('message', (err, value) => {
``` ```
### off\('message'\) ### off('message')
off\(type: 'message', callback?: AsyncCallback<string | ArrayBuffer\>\): void off(type: 'message', callback?: AsyncCallback\<string | ArrayBuffer\>): void
Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented. Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). >The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8).
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -487,9 +539,9 @@ ws.off('message'); ...@@ -487,9 +539,9 @@ ws.off('message');
``` ```
### on\('close'\) ### on('close')
on\(type: 'close', callback: AsyncCallback<\{ code: number, reason: string \}\>\): void on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): void
Enables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result. Enables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
...@@ -500,25 +552,25 @@ Enables listening for the **close** events of a WebSocket connection. This API u ...@@ -500,25 +552,25 @@ Enables listening for the **close** events of a WebSocket connection. This API u
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------- | ---- | ------------------------------ | | -------- | ----------------------------------------------- | ---- | ------------------------------ |
| type | string | Yes | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.| | type | string | Yes | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.|
| callback | AsyncCallback<{ code: number, reason: string }> | Yes | Callback used to return the result. | | callback | AsyncCallback\<{ code: number, reason: string }\> | Yes | Callback used to return the result.<br>**close** indicates the close error code and **reason** indicates the error code description.|
**Example** **Example**
```js ```js
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
ws.on('close', (err, value) => { ws.on('close', (err, value) => {
console.log("on close, code is " + value['code'] + ", reason is " + value['reason']); console.log("on close, code is " + value.code + ", reason is " + value.reason);
}); });
``` ```
### off\('close'\) ### off('close')
off\(type: 'close', callback?: AsyncCallback<\{ code: number, reason: string \}\>\): void off(type: 'close', callback?: AsyncCallback\<{ code: number, reason: string }\>): void
Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result. Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -528,8 +580,7 @@ Disables listening for the **close** events of a WebSocket connection. This API ...@@ -528,8 +580,7 @@ Disables listening for the **close** events of a WebSocket connection. This API
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------- | ---- | ------------------------------ | | -------- | ----------------------------------------------- | ---- | ------------------------------ |
| type | string | Yes | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.| | type | string | Yes | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.|
| callback | AsyncCallback<{ code: number, reason: string }> | No | Callback used to return the result. | | callback | AsyncCallback\<{ code: number, reason: string }\> | No | Callback used to return the result.<br>**close** indicates the close error code and **reason** indicates the error code description.|
**Example** **Example**
...@@ -539,9 +590,9 @@ ws.off('close'); ...@@ -539,9 +590,9 @@ ws.off('close');
``` ```
### on\('error'\) ### on('error')
on\(type: 'error', callback: ErrorCallback\): void on(type: 'error', callback: ErrorCallback): void
Enables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result. Enables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
...@@ -554,7 +605,6 @@ Enables listening for the **error** events of a WebSocket connection. This API u ...@@ -554,7 +605,6 @@ Enables listening for the **error** events of a WebSocket connection. This API u
| type | string | Yes | Event type.<br />**error**: event indicating the WebSocket connection has encountered an error.| | type | string | Yes | Event type.<br />**error**: event indicating the WebSocket connection has encountered an error.|
| callback | ErrorCallback | Yes | Callback used to return the result. | | callback | ErrorCallback | Yes | Callback used to return the result. |
**Example** **Example**
```js ```js
...@@ -565,13 +615,13 @@ ws.on('error', (err) => { ...@@ -565,13 +615,13 @@ ws.on('error', (err) => {
``` ```
### off\('error'\) ### off('error')
off\(type: 'error', callback?: ErrorCallback\): void off(type: 'error', callback?: ErrorCallback): void
Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result. Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -621,8 +671,8 @@ You can customize the result codes sent to the server. The result codes in the f ...@@ -621,8 +671,8 @@ You can customize the result codes sent to the server. The result codes in the f
| Value | Description | | Value | Description |
| :-------- | :----------------- | | :-------- | :----------------- |
| 1000 | Normally closed | | 1000 | Normally closed. |
| 1001 | Connection closed by the server | | 1001 | Connection closed by the server. |
| 1002 | Incorrect protocol | | 1002 | Incorrect protocol. |
| 1003 | Data unable to be processed| | 1003 | Data unable to be processed.|
| 1004~1015 | Reserved | | 1004~1015 | Reserved. |
...@@ -47,6 +47,12 @@ ...@@ -47,6 +47,12 @@
- [File Management Error Codes](errorcode-filemanagement.md) - [File Management Error Codes](errorcode-filemanagement.md)
- Network Management - Network Management
- [Upload and Download Error Codes](errorcode-request.md) - [Upload and Download Error Codes](errorcode-request.md)
- [HTTP Error Codes](errorcode-net-http.md)
- [Socket Error Codes](errorcode-net-socket.md)
- [Network Connection Management Error Codes](errorcode-net-connection.md)
- [Ethernet Connection Error Codes](errorcode-net-ethernet.md)
- [Network Sharing Error Codes](errorcode-net-sharing.md)
- [Policy Management Error Codes](errorcode-net-policy.md)
- Connectivity - Connectivity
- [NFC Error Codes](errorcode-nfc.md) - [NFC Error Codes](errorcode-nfc.md)
- [RPC Error Codes](errorcode-rpc.md) - [RPC Error Codes](errorcode-rpc.md)
......
# Network Connection Management Error Codes
## 2100001 Invalid Parameter Value
**Error Message**
Invalid parameter value.
**Description**
This error code is reported if the parameter value is invalid.
**Cause**
The input parameter value is not within the valid value range.
**Procedure**
Check whether the input parameter value is within the valid value range.
## 2100002 Service Connection Failure
**Error Message**
Operation failed. Cannot connect to service.
**Description**
This error code is reported if a service connection failure occurs.
**Cause**
The service is abnormal.
**Procedure**
Check whether system services are running properly.
## 2100003 System Internal Error
**Error Message**
System internal error.
**Description**
This error code is reported if a system internal error occurs.
**Cause**
1. The memory is abnormal.
2. A null pointer is present.
**Procedure**
1. Check whether the memory space is sufficient. If not, clear the memory and try again.
2. Check whether the system is normal. If not, try again later or restart the device.
## 2101007 Callback Already Exists
**Error Message**
The same callback exists.
**Description**
This error code is reported if the same callback already exists.
**Cause**
The **callback** object has been registered for activating a network or listening to network status changes.
**Procedure**
1. Check whether the **callback** object has been registered.
2. If the **callback** object has been registered, use the registered **callback** object.
## 2101008 Callback Not Exist
**Error Message**
The callback is not exists.
**Description**
This error code is reported if a **callback** object to be unregistered does not exist.
**Cause**
The **callback** object has not been registered for activating a network or listening to network status changes.
**Procedure**
Before unregistering a **callback** object, make sure that it has been registered for activating a network or listening to network status changes.
## 2101022 Number of Requests Exceeding the Maximum
**Error Message**
The number of requests exceeded the maximum.
**Description**
This error code is reported if the number of network requests exceeds the maximum.
**Cause**
The number of requests for activating a network or listening to network status changes has reached the maximum value.
**Procedure**
Locate the fault based on the "Over the max request number" log record.
# Ethernet Connection Error Codes
## 2200001 Invalid Parameter Value
**Error Message**
Invalid parameter value.
**Description**
This error code is reported if the parameter value is invalid.
**Cause**
The input parameter value is not within the valid value range.
**Procedure**
Check whether the input parameter value is within the valid value range.
## 2200002 Service Connection Failure
**Error Message**
Operation failed. Cannot connect to service.
**Description**
This error code is reported if a service connection failure occurs.
**Cause**
The service is abnormal.
**Procedure**
Check whether system services are running properly.
## 2200003 System Internal Error
**Error Message**
System internal error.
**Description**
This error code is reported if a system internal error occurs.
**Cause**
1. The memory is abnormal.
2. A null pointer is present.
**Procedure**
1. Check whether the memory space is sufficient. If not, clear the memory and try again.
2. Check whether the system is normal. If not, try again later or restart the device.
## 2201005 Device Information Not Exist
**Error Message**
The device information does not exist.
**Description**
This error code is reported if the device information does not exist.
**Cause**
The device to set or obtain does not exist.
**Procedure**
```bash
> hdc shell ifconfig
```
Check whether the device, for example, **eth0** or **eth1**, exists.
## 2201006 Device Not Connected
**Error Message**
Device disconnected.
**Description**
This error code is reported if the device is not connected.
**Cause**
The network interface card (NIC) is faulty.
**Procedure**
View the Ethernet service and netsys logs to check for the connection status information reported by the kernel.
## 2201007 Failed to Write the User Configuration
**Error Message**
Failed to write the user configuration.
**Description**
This error code is reported if an error occurs while writing data to the user configuration file.
**Cause**
The system reports an error.
**Procedure**
A system internal error occurs. You are advised to locate the fault based on logs.
# HTTP Error Codes
## 2300001 Protocol Not Supported
**Error Message**
Unsupported protocol.
**Description**
This error code is reported if the input protocol version is not supported by the server.
**Cause**
The input protocol version is not supported by the server.
**Solution**
Specify a protocol version supported by the server.
## 2300003 Incorrect URL Format
**Error Message**
URL using bad/illegal format or missing URL.
**Description**
This error code is reported if the URL format is incorrect.
**Cause**
The format of the input URL is incorrect.
**Solution**
Specify a URL of the correct format.
## 2300005 Failed to Resolve the Domain Name of the Proxy Server
**Error Message**
Couldn't resolve proxy name.
**Description**
This error code is reported if the domain name of the proxy server cannot be resolved.
**Cause**
This error code is reported if the URL of the proxy server is incorrect.
**Solution**
Specify a URL of the correct format.
## 2300006 Failed to Resolve the Domain Name of the Host
**Error Message**
Couldn't resolve host name.
**Description**
This error code is reported if the domain name of the host cannot be resolved.
**Cause**
1. The input URL is incorrect.
2. The network connection is abnormal.
**Solution**
1. Specify a URL of the correct format.
2. Rectify network connection faults.
## 2300007 Failed to Connect to the Server
**Error Message**
Couldn't connect to server.
**Description**
This error code is reported if the server connection failed.
**Cause**
The format of the input URL is incorrect.
**Solution**
Specify a URL of the correct format.
## 2300008 Invalid Data Returned by the Server
**Error Message**
Weird server reply.
**Description**
This error code is reported if the data returned by the server is invalid.
**Cause**
The server encounters an error and returns data in non-HTTP format.
**Solution**
Check the server implementation.
## 2300009 Access to Remote Resources Denied
**Error Message**
Access denied to remote resource.
**Description**
This error code is reported if the access to remote resources is denied by the server.
**Cause**
The access to the specified resource is denied by the server.
**Solution**
Check whether access to the requested resource is allowed.
## 2300016 HTT2 Framing Layer Error
**Error Message**
Error in the HTTP2 framing layer.
**Description**
This error code is reported if an error occurs on the HTTP2 framing layer.
**Cause**
HTTP2 is not supported by the server.
**Solution**
Capture and analyze packets to check whether HTTP2 is supported by the server.
## 2300018 Incomplete Data Returned by the Server
**Error Message**
Transferred a partial file.
**Description**
This error code is reported if data returned by the server is incomplete.
**Cause**
This problem is probable due to server implementation.
**Solution**
Check the server implementation.
## 2300023 Failed to Write Received Data to a Disk or Application
**Error Message**
Failed writing received data to disk/application.
**Description**
This error code is reported if an error occurs while writing received data to the disk or application.
**Cause**
The application does not have the data write permission.
**Solution**
Check the permissions granted to the application.
## 2300025 Failed to Upload Data
**Error Message**
Upload failed.
**Description**
This error code is reported if data upload fails.
**Cause**
The file is too large or the network is faulty. The server may reject the **STOR** command if FTP is used.
**Solution**
Check the file size and network status.
## 2300026 Failed to Open or Read Local Data from a File or Application
**Error Message**
Failed to open/read local data from file/application.
**Description**
This error code is reported if an error occurs while opening or reading local data from a file or application.
**Cause**
The application does not have the data read permission.
**Solution**
Check the permissions granted to the application.
## 2300027 Insufficient Memory
**Error Message**
Out of memory.
**Description**
This error code is reported if the memory is insufficient.
**Cause**
This error code is reported if the memory is insufficient.
**Solution**
Check the system memory.
## 2300028 Operation Timeout
**Error Message**
Timeout was reached.
**Description**
This error code is reported if the operation times out.
**Cause**
The TCP connection or the read/write operation times out.
**Solution**
Rectify network faults.
## 2300047 Maximum Redirections Reached
**Error Message**
Number of redirects hit maximum amount.
**Description**
This error code is reported if the number of redirections reaches the maximum.
**Cause**
Redirection is performed too frequently.
**Solution**
Check the server implementation.
## 2300052 No Content Returned by the Server
**Error Message**
Server returned nothing (no headers, no data).
**Description**
This error code is reported if no content is returned by the server.
**Cause**
This problem is probable due to server implementation.
**Solution**
Check the server implementation.
## 2300055 Failed to Send Network Data
**Error Message**
Failed sending data to the peer.
**Description**
This error code is reported if an error occurs while sending network data to the peer end.
**Cause**
This problem is probable due to a network fault.
**Solution**
Rectify network faults.
## 2300056 Failed to Receive Network Data
**Error Message**
Failure when receiving data from the peer.
**Description**
This error code is reported if an error occurs while receiving network data from the peer end.
**Cause**
This problem is probable due to a network fault.
**Solution**
Rectify network faults.
## 2300058 Local SSL Certificate Error
**Error Message**
Problem with the local SSL certificate.
**Description**
This error code is reported if the local SSL certificate is incorrect.
**Cause**
The format of the SSL certificate is incorrect.
**Solution**
Check the format of the SSL certificate.
## 2300059 Failed to Use the Specified SSL Cipher Algorithm
**Error Message**
Couldn't use specified SSL cipher.
**Description**
This error code is reported if the specified SSL cipher algorithm cannot be used.
**Cause**
The system does not support the cipher algorithm negotiated between the client and server.
**Solution**
Capture and analyze packets to check whether the cipher algorithm is supported.
## 2300060 Incorrect SSL Certificate or SSH Key of the Remote Server
**Error Message**
SSL peer certificate or SSH remote key was not OK.
**Description**
This error code is reported if the SSL certificate or SSH key of the remote server is incorrect.
**Cause**
It is probable that the server identity verification fails because the certificate has expired.
**Solution**
Check whether the certificate is valid.
## 2300061 Unrecognized or Incorrect HTTP Encoding Format
**Error Message**
Unrecognized or bad HTTP Content or Transfer-Encoding.
**Description**
This error code is reported if the HTTP encoding format cannot be identified or is incorrect.
**Cause**
The HTTP encoding format is incorrect.
**Solution**
Check the server implementation. Currently, only gzip encoding is supported.
## 2300063 Maximum File Size Exceeded
**Error Message**
Maximum file size exceeded.
**Description**
This error code is reported if the maximum file size is exceeded.
**Cause**
The downloaded file is too large.
**Solution**
Check the server implementation.
## 2300070 Insufficient Server Disk Space
**Error Message**
Remote disk full or allocation exceeded.
**Description**
This error code is reported if the server disk space is insufficient.
**Cause**
The server disk is full.
**Solution**
Check the server disk space.
## 2300073 Uploaded File Already Exists
**Error Message**
Remote file already exists.
**Description**
This error code is reported if the server finds that the uploaded file already exists.
**Cause**
The uploaded file already exists.
**Solution**
Check the server for files that already exist.
## 2300077 No SSL CA Certificate or Access Permission
**Error Message**
Problem with the SSL CA cert (path? access rights?).
**Description**
This error code is reported if the SSL CA certificate does not exist or the access permission is not available.
**Cause**
The SSL CA certificate is not available or the access permission is not granted.
**Solution**
Check whether the SSL CA certificate exists or the access permission is granted.
## 2300078 URL Requested File Not Found
**Error Message**
Remote file not found.
**Description**
This error code is reported if the file requested by the specified URL does not exist.
**Cause**
The file requested by the specified URL does not exist.
**Solution**
Check whether the file requested by the specified URL exists.
## 2300094 Identity Verification Failed
**Error Message**
An authentication function returned an error.
**Description**
This error code is reported if identity verification fails.
**Cause**
The specified identity verification field does not match that on the server.
**Solution**
Check whether the specified identity verification field matches that on the server.
## 2300999 Unknown Error
**Error Message**
Unknown Other Error.
**Description**
This error code is reported if an unknown error occurs.
**Cause**
An unknown error occurs.
**Solution**
Try again or contact technical support.
# Policy Management Error Codes
## 2100001 Invalid Parameter Value
**Error Message**
Invalid parameter value.
**Description**
Invalid parameter value
**Cause**
The input parameter value is not within the valid value range.
**Procedure**
Check whether the input parameter value is within the valid value range.
## 2100002 Service Connection Failure
**Error Message**
Operation failed. Cannot connect to service.
**Description**
This error code is reported if a service connection failure occurs.
**Cause**
The service is abnormal.
**Procedure**
Check whether system services are running properly.
## 2100003 System Internal Error
**Error Message**
System internal error.
**Description**
This error code is reported if a system internal error occurs.
**Cause**
1. The memory is abnormal.
2. A null pointer is present.
**Procedure**
1. Check whether the memory space is sufficient. If not, clear the memory and try again.
2. Check whether the system is normal. If not, try again later or restart the device.
# Network Sharing Error Codes
## 2200001 Invalid Parameter Value
**Error Message**
Invalid parameter value.
**Description**
This error code is reported if the parameter value is invalid.
**Cause**
The input parameter value is not within the valid value range.
**Procedure**
Check whether the input parameter value is within the valid value range.
## 2200002 Service Connection Failure
**Error Message**
Operation failed. Cannot connect to service.
**Description**
This error code is reported if a service connection failure occurs.
**Cause**
The service is abnormal.
**Procedure**
Check whether system services are running properly.
## 2200003 System Internal Error
**Error Message**
System internal error.
**Description**
This error code is reported if a system internal error occurs.
**Cause**
1. The memory is abnormal.
2. A null pointer is present.
**Procedure**
1. Check whether the memory space is sufficient. If not, clear the memory and try again.
2. Check whether the system is normal. If not, try again later or restart the device.
## 2202004 Shared Iface Unavailable
**Error Message**
Try to share an unavailable iface.
**Description**
This error code is reported if an Iface is used.
**Cause**
The specified Iface does not exist or the Iface name is incorrect.
**Procedure**
1. Check whether the shared Iface is available.
```bash
> ifconfig -a
```
2. Check whether the Iface name is correct.
## 2202005 Wi-Fi Sharing Failure
**Error Message**
WiFi sharing failed.
**Description**
This error code is reported if Wi-Fi sharing fails.
**Cause**
No connected network is available and therefore the attempt to obtain the default network fails.
**Procedure**
Check whether the network connection is normal.
## 2202006 Bluetooth Sharing Failure
**Error Message**
Bluetooth sharing failed.
**Description**
This error code is reported if Bluetooth sharing fails.
**Cause**
1. Bluetooth is disabled.
2. No connected network is available and therefore the attempt to obtain the default network fails.
**Procedure**
1. Touch the Bluetooth icon to turn on Bluetooth mode.
2. Check whether the network connection is normal.
## 2202009 Failed to Enable Forwarding for Network Sharing
**Error Message**
Network share enable forwarding error.
**Description**
This error code is reported if an error occurs while enabling forwarding for network sharing.
**Cause**
The Iptables rule setting fails and therefore an error occurs while combining Iptables commands fails.
**Procedure**
Enable the debug log function, and check whether Iptables commands are correctly combined.
## 2202011 Failed to Obtain the Network Sharing Configuration
**Error Message**
Cannot get network sharing configuration.
**Description**
This error code is reported if an error occurs while obtaining the network sharing configuration.
**Cause**
The configuration file directory is incorrect.
**Procedure**
Specify a correct configuration file directory.
# Socket Error Codes
## 2301001 Operation Not Allowed
**Error Message**
Operation not permitted.
**Description**
This error code is reported if an operation is not allowed.
**Cause**
The operation is illegal.
**Procedure**
Check the operation procedure.
## 2301002 File Not Exist
**Error Message**
No such file or directory.
**Description**
This error code is reported if the requested file does not exist.
**Cause**
The requested file does not exist.
**Procedure**
Check the file name or file path.
## 2301003 Process Not Exist
**Error Message**
No such process.
**Description**
This error code is reported if a process does not exist.
**Cause**
The process does not exist.
**Procedure**
Check the process information.
## 2301004 System Call Interrupted
**Error Message**
Interrupted system call.
**Description**
This error code is reported if the system call is interrupted.
**Cause**
The system call is interrupted.
**Procedure**
Rectify system call errors.
**Description of TCP/UDP error codes:**
> Mapping format of other TCP/UDP Socket error codes: 2301000 + Linux kernel error code (errno). For details, see Linux kernel error codes.
## 2300002 System Internal Error
**Error Message**
System internal error.
**Description**
This error code is reported if a system internal error occurs.
**Cause**
1. The memory is abnormal.
2. A null pointer is present.
**Procedure**
1. Check whether the memory space is sufficient. If not, clear the memory and try again.
2. Check whether the system is normal. If not, try again later or restart the device.
## 2303104 System Call Interrupted
**Error Message**
Interrupted system call.
**Description**
This error code is reported if the system call is interrupted.
**Cause**
Calling the **connect** function may result in a long blocking time. In such a case, the system generates an interrupt signal and returns an **EINTR** error.
**Procedure**
Call the **connect** function to try network connection again.
## 2303109 Error File Number
**Error Message**
Bad file number.
**Description**
This error code is reported if an operation is performed on a locally closed socket.
**Cause**
The socket FD may be closed.
**Procedure**
Check whether the socket is closed unexpectedly.
## 2303111 Requested Resource Temporarily Unavailable
**Error Message**
Resource temporarily unavailable try again.
**Description**
This error code is reported if the requested system resource is temporarily unavailable.
**Cause**
The system resources are in use.
**Procedure**
Try again later.
## 2303188 Socket Operations on Non-Sockets
**Error Message**
Socket operation on non-socket.
**Description**
This error code is reported if a socket descriptor is not specified for the **socket** parameter.
**Cause**
A socket descriptor is not specified for the **socket** parameter.
**Procedure**
Check whether the descriptor is correctly obtained.
## 2303191 Incorrect Socket Protocol Type
**Error Message**
Protocol wrong type for socket.
**Description**
This error code is reported if the type of the specified socket protocol is incorrect.
**Cause**
The **socket** function is called with an unsupported socket protocol type.
For example, the protocol type cannot be set to **SOCK_STREAM socket** for the the Internet UDP protocol.
**Procedure**
Check whether the socket protocol type is correct.
## 2303198 Network Address Already In Use
**Error Message**
Address already in use.
**Description**
This error code is reported if a network address has been used.
**Cause**
The probable cause can be any of the following: The application attempts to bind a socket to an IP address/port that has been used for an existing socket. The socket is not properly closed. The socket is still being closed.
**Procedure**
Try another network address.
## 2303199 Failed to Assign the Requested Address
**Error Message**
Cannot assign requested address.
**Description**
This error code is reported if the requested address is invalid in its context.
**Cause**
The remote address or port is invalid for the remote server.
**Procedure**
Check whether the address or port is correct.
## 2303210 Connection Timeout
**Error Message**
Connection timed out.
**Description**
This error code is reported if the connection to the remote server cannot be set up for a long time.
**Cause**
It is probable that a server breakdown has occurred.
**Procedure**
Contact the peer end to rectify the fault.
## 2303501 Null SSL
**Error Message**
SSL is null.
**Description**
This error code is reported if the SSL is null.
**Cause**
The returned error information is null when an internal function fails to be executed.
**Procedure**
Call the function again.
## 2303502 TLS Reading Error
**Error Message**
Error in tls reading.
**Description**
This error code is reported if an error occurs while reading data on the TLS socket.
**Cause**
The underlying socket is blocked.
**Procedure**
Perform data receiving again.
## 2303503 TLS Writing Error
**Error Message**
Error in tls writing.
**Description**
This error code is reported if an error occurs while writing data on the TLS socket.
**Cause**
When the send buffer is full, the underlying socket sends an **EWOUDLBLOCK** error, which means that the server does not read the data sent from the client.
**Procedure**
Rectify the fault on the server side.
## 2303504 x509 Failed to Look Up the x509 Certificate
**Error Message**
Error looking up x509.
**Description**
An error occurred when verifying the x509 certificate.
**Cause**
The local certificate does not match the server certificate.
**Procedure**
Check whether the local CA matches the server certificate.
## 2303505 TLS System Call Error
**Error Message**
Error occurred in the tls system call.
**Description**
This error code is reported if the TLS system call fails because of fatal I/O errors.
**Cause**
Network communication fails because of network faults.
**Procedure**
For details, see the Linux kernel error codes (errno).
## 2303506 Failed to Close TLS Connections
**Error Message**
Error clearing tls connection.
**Description**
This error code is reported if the TLS/SSL connection to be closed has been disabled.
**Cause**
The TLS/SSL connection to be closed has been disabled.
**Procedure**
Initiate a new TLS/SSL connection.
...@@ -74,6 +74,7 @@ Before using the Docker environment, perform the following operations: ...@@ -74,6 +74,7 @@ Before using the Docker environment, perform the following operations:
> >
> You do not need to obtain the source code for the HPM-based Docker environment. > You do not need to obtain the source code for the HPM-based Docker environment.
3. Perform subsequent operations as a user who has the root permission or has been granted the permission to use Docker.
## Standalone Docker Environment<a name="section2858536103611"></a> ## Standalone Docker Environment<a name="section2858536103611"></a>
......
...@@ -7,20 +7,17 @@ HiTraceMeter is the OpenHarmony subsystem that provides APIs to implement call c ...@@ -7,20 +7,17 @@ HiTraceMeter is the OpenHarmony subsystem that provides APIs to implement call c
## Basic Concepts ## Basic Concepts
The HiTraceMeter subsystem consists of three parts: The HiTraceMeter subsystem consists of three parts:
- JS/C++ HiTraceMeter APIs for application logging - JS/C++ HiTraceMeter APIs for application logging
- hitrace CLI tool for data collection - hitrace CLI tool for data collection
- smartperf tool for graphical data analysis - smartperf tool for graphical data analysis
Wherein, HiTraceMeter APIs and the hitrace CLI tool run on the device side, and the smartperf tool runs on the PC side. Wherein, HiTraceMeter APIs and the hitrace CLI tool run on the device side, and the smartperf tool runs on the PC side. HiTraceMeter APIs are provided in C++ and JS for event logging, which aims to generate the trace data necessary for performance tracing and analysis during the development process.
HiTraceMeter APIs are provided in C++ and JS for event logging, which aims to generate the trace data necessary for performance tracing and analysis during the development process.
The hitrace CLI tool is used to collect trace data. It captures trace data flows and saves the data as a text file. The hitrace CLI tool is used to collect trace data. It captures trace data flows and saves the data as a text file.
The smartperf tool allows you to perform data analysis manually or use the analysis script for automated data analysis. If you want to get the data analysis done automatically, you need to supply the data file generated by the hitrace CLI tool as the input for the smartperf tool. The smartperf tool allows you to perform data analysis manually or use the analysis script for automated data analysis. If you want to get the data analysis done automatically, you need to supply the data file generated by the hitrace CLI tool as the input for the smartperf tool.
Traces data is classified by trace tag or trace category. Generally, one device subsystem corresponds to one tag. The tag is passed as the **Tag** parameter to event logging APIs. When you use the hitrace CLI tool to collect trace data, only the trace data specified by the **Tag** parameter is collected. Trace data of applications is fixedly labeled as **APP Tag**, and therefore, no **Tag** parameter needs to be passed to JS APIs. The following is a list of trace tags supported by HiTraceMeter. You can view the tags in [hitrace_meter.h](https://gitee.com/openharmony/hiviewdfx_hitrace/blob/master/interfaces/native/innerkits/include/hitrace_meter/hitrace_meter.h). Traces data is classified by trace tag or trace category. Generally, one device subsystem corresponds to one tag. The tag is passed as the **Tag** parameter to event logging APIs. When you use the hitrace CLI tool to collect trace data, only the trace data specified by the **Tag** parameter is collected. Trace data of applications is fixedly labeled as **APP Tag**, and therefore, no **Tag** parameter needs to be passed to JS APIs. The following is a list of trace tags supported by HiTraceMeter. You can view the tags in [hitrace_meter.h](https://gitee.com/openharmony/hiviewdfx_hitrace/blob/master/interfaces/native/innerkits/include/hitrace_meter/hitrace_meter.h).
```cpp ```cpp
constexpr uint64_t HITRACE_TAG_NEVER = 0; // This tag is never enabled. constexpr uint64_t HITRACE_TAG_NEVER = 0; // This tag is never enabled.
...@@ -73,7 +70,7 @@ constexpr uint64_t HITRACE_TAG_NOT_READY = (1ULL << 63); // Reserved for initial ...@@ -73,7 +70,7 @@ constexpr uint64_t HITRACE_TAG_NOT_READY = (1ULL << 63); // Reserved for initial
constexpr uint64_t HITRACE_TAG_VALID_MASK = ((HITRACE_TAG_LAST - 1) | HITRACE_TAG_LAST); constexpr uint64_t HITRACE_TAG_VALID_MASK = ((HITRACE_TAG_LAST - 1) | HITRACE_TAG_LAST);
``` ```
## Implementation Principle ## Implementation Principles
HiTraceMeter provides the hitrace CLI tool for capturing trace data in user mode and kernel mode, and provides C++ (innerkits) and JS (kits) APIs for event logging in user mode. Through extending kernel's ftrace functionality, HiTraceMeter can use the trace_marker node of ftrace to write the data, which is written into the user space by event logging APIs, to the kernel buffer. The following figure shows the basic HiTraceMeter architecture. HiTraceMeter provides the hitrace CLI tool for capturing trace data in user mode and kernel mode, and provides C++ (innerkits) and JS (kits) APIs for event logging in user mode. Through extending kernel's ftrace functionality, HiTraceMeter can use the trace_marker node of ftrace to write the data, which is written into the user space by event logging APIs, to the kernel buffer. The following figure shows the basic HiTraceMeter architecture.
...@@ -109,7 +106,7 @@ Only C++ APIs are now open for system developers. If you're developing a JS app, ...@@ -109,7 +106,7 @@ Only C++ APIs are now open for system developers. If you're developing a JS app,
**Table 1** Sync APIs **Table 1** Sync APIs
| API | Function |Parameter Description | | Sync trace | Function |Parameter Description |
| :----------------------------------------------------------- | ------------- |------------- | | :----------------------------------------------------------- | ------------- |------------- |
| void StartTrace(uint64_t label, const std::string& value, float limit = -1); | Starts a synchronous trace.|**label**: trace category.<br>**value**: trace data that indicates the specific status, such as the memory size and queue length.| | void StartTrace(uint64_t label, const std::string& value, float limit = -1); | Starts a synchronous trace.|**label**: trace category.<br>**value**: trace data that indicates the specific status, such as the memory size and queue length.|
| void FinishTrace(uint64_t label); | Stops a synchronous trace.|**label**: trace category.| | void FinishTrace(uint64_t label); | Stops a synchronous trace.|**label**: trace category.|
...@@ -119,7 +116,7 @@ Only C++ APIs are now open for system developers. If you're developing a JS app, ...@@ -119,7 +116,7 @@ Only C++ APIs are now open for system developers. If you're developing a JS app,
**Table 2** Async APIs **Table 2** Async APIs
| API | Function |Parameter Description | | Async trace | Function |Parameter Description |
| ------------------------------------------------------------ | ------------- |------------- | | ------------------------------------------------------------ | ------------- |------------- |
| void StartAsyncTrace(uint64_t label, const std::string& value, int32_t taskId, float limit = -1); | Starts an asynchronous trace.| **label**: trace category.<br>**value**: trace data that indicates the specific status, such as the memory size and queue length.<br>**taskId**: ID used to indicate the association of APIs in an asynchronous trace.| | void StartAsyncTrace(uint64_t label, const std::string& value, int32_t taskId, float limit = -1); | Starts an asynchronous trace.| **label**: trace category.<br>**value**: trace data that indicates the specific status, such as the memory size and queue length.<br>**taskId**: ID used to indicate the association of APIs in an asynchronous trace.|
| void FinishAsyncTrace(uint64_t label, const std::string& value, int32_t taskId); | Stops an asynchronous trace.| **label**: trace category.<br>**value**: trace data that indicates the specific status, such as the memory size and queue length.<br>**taskId**: ID used to indicate the association of APIs in an asynchronous trace.| | void FinishAsyncTrace(uint64_t label, const std::string& value, int32_t taskId); | Stops an asynchronous trace.| **label**: trace category.<br>**value**: trace data that indicates the specific status, such as the memory size and queue length.<br>**taskId**: ID used to indicate the association of APIs in an asynchronous trace.|
...@@ -130,9 +127,9 @@ The trace data of **StartAsyncTrace** and **FinishAsyncTrace** is matched based ...@@ -130,9 +127,9 @@ The trace data of **StartAsyncTrace** and **FinishAsyncTrace** is matched based
**Table 3** Counter APIs **Table 3** Counter APIs
| API | Function |Parameter Description | | Counter Trace | Function |Parameter Description |
| ------------------------------------------------------------ | --------- |--------- | | ------------------------------------------------------------ | --------- |--------- |
| void CountTrace(uint64_t label, const std::string& name, int64_t); | Performs a count trace.|**label**: trace category.<br>**name**: trace name displayed in the IDE.| | void CountTrace(uint64_t label, const std::string& name, int64_t); | Count trace.|**label**: trace category.<br>**name**: trace name displayed in the IDE.|
## How to Develop ## How to Develop
...@@ -147,33 +144,8 @@ The trace data of **StartAsyncTrace** and **FinishAsyncTrace** is matched based ...@@ -147,33 +144,8 @@ The trace data of **StartAsyncTrace** and **FinishAsyncTrace** is matched based
#include "hitrace_meter.h"// Header file for defining APIs #include "hitrace_meter.h"// Header file for defining APIs
``` ```
3. When calling an API, pass the trace value as an input parameter. After the hitrace command is executed in the shell, the trace data is automatically captured. The captured data includes the function call process and the memory and time consumed during this process. You can use the data to analyze the call process to identify performance problems. 3. When calling an API, pass the trace value as an input parameter. The trace tags currently supported are listed in **hitrace_meter.h**. Assume that the trace tag is **OHOS** and trace data of **func1** and **func2** needs to be captured. After the hitrace command is executed in the shell, the trace data is automatically captured. The captured data includes the function call process and the memory and time consumed during this process. You can use the data to analyze the call process to identify performance problems.
```cpp
CountTrace(label, "count number", 2000); // Integer trace
StartTrace(label, "func1Trace", -1); // Trace start point of func1Start
FinishTrace(label); // Trace end point of func1Trace
StartAsyncTrace(label, "asyncTrace1", 1234); // Start point of asyncTrace1
FinishAsyncTrace(label, "asyncTrace2", 3456); // End point of asyncTrace2
```
4. On completion of HiTraceMeter building and deployment, start a trace. After you run the application in the shell on the device, trace data will be captured automatically.
```
hdc_std shell hitrace -t 10 ohos > .\myapp_demo.ftrace
```
You can open the captured data by clicking **Open trace file** in the smartperf tool or dragging the data to the graphics area. For details, see [smartperf](https://toscode.gitee.com/openharmony-sig/smartperf).
## Development Example
You can access a full list of trace tags supported by HiTraceMeter in **hitrace_meter.h**. The following uses the **OHOS** tag as an example to illustrate how to obtain the trace data of the **func1** and **func2** functions.
```cpp ```cpp
#include "hitrace_meter.h" // Include hitrace_meter.h #include "hitrace_meter.h" // Include hitrace_meter.h
...@@ -192,11 +164,21 @@ int main() ...@@ -192,11 +164,21 @@ int main()
FinishTrace (label); // Trace end point of func2Trace FinishTrace (label); // Trace end point of func2Trace
sleep(1); sleep(1);
FinishTrace(label); // Trace end point of func1Trace FinishTrace(label); // Trace end point of func1Trace
StartAsyncTrace(label, "asyncTrace1", 1234); // Trace start point of asyncTrace1
FinishAsyncTrace(label, "asyncTrace1", 1234); // Trace end point of asyncTrace2
return 0; return 0;
} }
``` ```
4. On completion of HiTraceMeter building and deployment, start a trace. After you run the application in the shell on the device, trace data will be captured automatically.
```
hdc_std shell hitrace -t 10 ohos > .\myapp_demo.ftrace
```
You can open the captured data by clicking **Open trace file** in the smartperf tool or dragging the data to the graphics area. For details, see [smartperf](https://toscode.gitee.com/openharmony-sig/smartperf).
## Verification ## Verification
...@@ -313,7 +295,7 @@ Examples: ...@@ -313,7 +295,7 @@ Examples:
hitrace -l hitrace -l
``` ```
Or, Alternatively, run the following command:
``` ```
hitrace --list_categories hitrace --list_categories
...@@ -356,6 +338,6 @@ Examples: ...@@ -356,6 +338,6 @@ Examples:
# References # Reference
For details about HiTraceMeter, see [hiviewdfx_hitrace: A Lightweight Distributed Tracing](https://gitee.com/openharmony/hiviewdfx_hitrace). For details about HiTraceMeter, see [hiviewdfx_hitrace: A Lightweight Distributed Tracing](https://gitee.com/openharmony/hiviewdfx_hitrace).
...@@ -36,6 +36,8 @@ foundation/communication/ ...@@ -36,6 +36,8 @@ foundation/communication/
4. Call **conn.register()** to subscribe to network status changes of the specified network. 4. Call **conn.register()** to subscribe to network status changes of the specified network.
5. When the network is available, the callback will be invoked to return the **netAvailable** event.
6. Call **conn.unregister()** to unsubscribe from the network status changes if required. 6. Call **conn.unregister()** to unsubscribe from the network status changes if required.
``` ```
...@@ -43,9 +45,9 @@ foundation/communication/ ...@@ -43,9 +45,9 @@ foundation/communication/
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
let netCap = { let netCap = {
// Set the network type to cellular network. // Set the network type to CELLULAR.
bearerTypes: [connection.NetBearType.BEARER_CELLULAR], bearerTypes: [connection.NetBearType.BEARER_CELLULAR],
// Set the network capability to Internet. // Set the network capability to INTERNET.
networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET], networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET],
}; };
let netSpec = { let netSpec = {
...@@ -55,7 +57,7 @@ foundation/communication/ ...@@ -55,7 +57,7 @@ foundation/communication/
let timeout = 10 * 1000; let timeout = 10 * 1000;
// Create a NetConnection object. // Create a NetConnection object.
let conn = connection.createNetConnection(netSpec, timeout); let conn = connection.createNetConnection(netSpec, timeout);
// Subscribe to the netAvailable event. When the network is available, the callback will be invoked to report the event. // Subscribe to the netAvailable event.
conn.on('netAvailable', (data=> { conn.on('netAvailable', (data=> {
console.log("net is available, netId is " + data.netId); console.log("net is available, netId is " + data.netId);
})); }));
...@@ -67,16 +69,12 @@ foundation/communication/ ...@@ -67,16 +69,12 @@ foundation/communication/
### Sharing a Network ### Sharing a Network
1. Import the network sharing namespace from **@ohos.net.sharing**. 1. Import the **sharing** namespace from **@ohos.net.sharing**.
2. Set the network sharing type. 2. Set the network sharing type.
3. Start network sharing. 3. Start network sharing.
4. Stop network sharing. 4. Stop network sharing.
``` ```
// Import the network sharing namespace. // Import the connection namespace.
import sharing from '@ohos.net.sharing'; import sharing from '@ohos.net.sharing';
// Set the network sharing type. // Set the network sharing type.
this.sharingType = 0; // The value 0 indicates Wi-Fi, 1 indicates USB, and 2 indicates Bluetooth. this.sharingType = 0; // The value 0 indicates Wi-Fi, 1 indicates USB, and 2 indicates Bluetooth.
...@@ -92,33 +90,30 @@ sharing.stopSharing(this.sharingType,(err)=>{ ...@@ -92,33 +90,30 @@ sharing.stopSharing(this.sharingType,(err)=>{
### Initiating a Network Request ### Initiating a Network Request
1. Import the HTTP namespace from **@ohos.net.http.d.ts**. 1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Call **createHttp()** to create an **HttpRequest** object. 2. Call **createHttp()** to create an **HttpRequest** object.
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.
3. Call **httpRequest.on()** to subscribe to an HTTP response header. This method returns a response earlier than the request. You can subscribe to HTTP response header events based on service requirements.
4. Call **httpRequest.request()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request. 4. Call **httpRequest.request()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
5. Parse the returned result based on service requirements. 5. Parse the returned result based on service requirements.
6. Call **off()** to unsubscribe from HTTP response header events.
6. Call **httpRequest.destroy()** to release resources after the request is processed. 7. Call **httpRequest.destroy()** to release resources after the request is processed.
``` ```
// 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 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();
// Subscribe to the HTTP response header, which is returned earlier than the response to httpRequest. // 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.
httpRequest.on('headersReceive', (data) => { // on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
console.info('header: ' + data.header); httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
}); });
httpRequest.request( httpRequest.request(
// Set the URL for the httpRequest. You must specify the URL address, and set httpRequestOptions as required. You can specify the parameters for GET 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: 'POST', // Optional. The default value is GET. method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add header fields based on service requirements. // You can add header fields based on service requirements.
header: { header: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
...@@ -127,21 +122,28 @@ httpRequest.request( ...@@ -127,21 +122,28 @@ httpRequest.request(
extraData: { extraData: {
"data": "data to send", "data": "data to send",
}, },
connectTimeout: 60000, // This parameter is optional. The default value is 60000, that is, 60s. expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
readTimeout: 60000, // This parameter is optional. The default value is 60000, that is, 60s. usingCache: true, // Optional. The default value is true.
},(err, data) => { 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.
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) => {
if (!err) { if (!err) {
// data.result carries 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 carries 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:' + data.header); console.info('header:' + JSON.stringify(data.header));
console.info('header:' + data.cookies); console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
} else { } else {
console.info('error:' + err); console.info('error:' + JSON.stringify(err));
// Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy();
} }
// Call destroy() to release resources after HttpRequest is complete.
httpRequest.destroy();
} }
); );
``` ```
...@@ -150,8 +152,6 @@ httpRequest.request( ...@@ -150,8 +152,6 @@ httpRequest.request(
**Network Management Subsystem** **Network Management Subsystem**
[communication_netmanager_base](https://gitee.com/openharmony/communication_netmanager_base) [communication_netmanager_base](https://gitee.com/openharmony/communication_netmanager_base/blob/master/README_zh.md)
[communication_netmanager_ext](https://gitee.com/openharmony/communication_netmanager_ext/blob/master/README_zh.md)
[communication_netmanager_ext](https://gitee.com/openharmony/communication_netmanager_ext) [communication_netstack](https://gitee.com/openharmony/communication_netstack/blob/master/README_zh.md)
[communication_netstack](https://gitee.com/openharmony/communication_netstack)
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册