diff --git a/en/application-dev/connectivity/http-request.md b/en/application-dev/connectivity/http-request.md index da1a7e1c517f284037a41a88e2167b6d1d2406aa..a266e285245c932534873440fc777fd86ccd480d 100644 --- a/en/application-dev/connectivity/http-request.md +++ b/en/application-dev/connectivity/http-request.md @@ -1,6 +1,6 @@ # 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**. @@ -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). -| API | Description | -| ----------------------------------------- | --------------------------------------------------------- | -| createHttp() | Creates an HTTP request. | -| request() | Initiates an HTTP request to a given URL. | -| destroy() | Destroys an HTTP request. | +| API | Description | +| ----------------------------------------- | ----------------------------------- | +| createHttp() | Creates an HTTP request. | +| request() | Initiates an HTTP request to a given URL. | +| request2()10+ | 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. | -| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events. | +| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events.| +| once\('headersReceive'\)8+ | Registers a one-time observer for HTTP Response Header events.| +| on\('dataReceive'\)10+ | Registers an observer for events indicating receiving of HTTP streaming responses. | +| off\('dataReceive'\)10+ | Unregisters the observer for events indicating receiving of HTTP streaming responses. | +| on\('dataEnd'\)10+ | Registers an observer for events indicating completion of receiving HTTP streaming responses. | +| off\('dataEnd'\)10+ | Unregisters the observer for events indicating completion of receiving HTTP streaming responses.| +| on\('dataProgress'\)10+ | Registers an observer for events indicating progress of receiving HTTP streaming responses. | +| off\('dataProgress'\)10+ | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.| ## How to Develop -1. Import the required HTTP module. -2. Create an **HttpRequest** object. -3. (Optional) Listen for HTTP Response Header events. -4. Initiate an HTTP request to a given URL. -5. (Optional) Process the HTTP Response Header event and the return result of the HTTP request. +1. Import the **http** namespace from **@ohos.net.http.d.ts**. +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. +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. +6. Call **off()** to unsubscribe from HTTP response header events. +7. Call **httpRequest.destroy()** to release resources after the request is processed. ```js +// Import the http namespace. 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(); - -// 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) will be replaced by on('headersReceive', Callback) in API version 8. 8+ +// 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. +// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8. httpRequest.on('headersReceive', (header) => { console.info('header: ' + JSON.stringify(header)); }); - 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", { 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: { 'Content-Type': 'application/json' }, @@ -55,21 +64,33 @@ httpRequest.request( extraData: { "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. + 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) { - // data.result contains the HTTP response. Parse the response based on service requirements. - console.info('Result:' + data.result); - console.info('code:' + data.responseCode); - // data.header contains the HTTP response header. Parse the content based on service requirements. + // data.result carries the HTTP response. Parse the response based on service requirements. + console.info('Result:' + JSON.stringify(data.result)); + console.info('code:' + JSON.stringify(data.responseCode)); + // data.header carries the HTTP response header. Parse the content based on service requirements. console.info('header:' + JSON.stringify(data.header)); - console.info('cookies:' + data.cookies); // 8+ + console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ } else { 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(); } } ); ``` + +## 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) diff --git a/en/application-dev/connectivity/socket-connection.md b/en/application-dev/connectivity/socket-connection.md index da5bea318e2b60da5641b9cf01ee73c926802c16..68e3433597881d891c87abd60b6f81abfc876028 100644 --- a/en/application-dev/connectivity/socket-connection.md +++ b/en/application-dev/connectivity/socket-connection.md @@ -1,46 +1,83 @@ # 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 -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. | -| constructTCPSocketInstance() | Creates a **TCPSocket** object. | -| bind() | Binds the IP address and port number. | +| constructUDPSocketInstance() | Creates a **UDPSocket** object.| +| constructTCPSocketInstance() | Creates a **TCPSocket** object.| +| bind() | Binds the IP address and port number.| | send() | Sends data.| -| close() | Closes a Socket connection. | -| getState() | Obtains the Socket connection status. | -| 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. | -| on(type: 'message') | Enables listening for **message** events of the Socket connection. | -| off(type: 'message') | Disables listening for **message** events of the Socket connection. | -| on(type: 'close') | Enables listening for **close** events of the Socket connection. | -| off(type: 'close') | Disables listening for **close** events of the Socket connection. | -| on(type: 'error') | Enables listening for **error** events of the Socket connection. | -| off(type: 'error') | Disables listening for **error** events of the Socket connection. | -| on(type: 'listening') | Enables listening for **listening** events of the UDPSocket connection. | -| off(type: 'listening') | Disables listening for **listening** events of the UDPSocket connection. | -| on(type: 'connect') | Enables listening for **connect** events of the TCPSocket connection. | -| off(type: 'connect') | Disables listening for **connect** events of the TCPSocket connection. | +| close() | Closes a Socket connection.| +| getState() | Obtains the Socket connection status.| +| 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.| +| on(type: 'message') | Subscribes to **message** events of the Socket connection.| +| off(type: 'message') | Unsubscribes from **message** events of the Socket connection.| +| on(type: 'close') | Subscribes to **close** events of the Socket connection.| +| off(type: 'close') | Unsubscribes from **close** events of the Socket connection.| +| on(type: 'error') | Subscribes to **error** events of the Socket connection.| +| off(type: 'error') | Unsubscribes from **error** events of the Socket connection.| +| on(type: 'listening') | Subscribes to **listening** events of the UDP Socket connection. | +| off(type: 'listening') | Unsubscribes from **listening** events of the UDP Socket connection. | +| on(type: 'connect') | Subscribes to **connect** events of the TCP Socket connection. | +| off(type: '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: '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: 'close') | Unsubscribes from **close** events of the TLS Socket connection.| +| off(type: 'error') | Unsubscribes from **error** events of the TLS Socket connection.| +| off(type: 'message') | Unsubscribes from **message** events of the TLS Socket connection.| +| on(type: 'close') | Subscribes to **close** events of the TLS Socket connection.| +| on(type: 'error') | Subscribes to **error** events of the TLS Socket connection.| +| on(type: '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. -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. @@ -48,15 +85,15 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th 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 import socket from '@ohos.net.socket' - + // Create a TCPSocket object. let tcp = socket.constructTCPSocketInstance(); - - // Enable listening for TCPSocket events. + + // Subscribe to TCP Socket connection events. tcp.on('message', value => { console.log("on message") let buffer = value.message @@ -73,7 +110,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th tcp.on('close', () => { console.log("on close") }); - + // Bind the local IP address and port number. let bindAddress = { address: '192.168.xx.xx', @@ -86,6 +123,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th return; } console.log('bind success'); + // Set up a connection to the specified IP address and port number. let connectAddress = { address: '192.168.xx.xx', @@ -100,6 +138,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th return; } console.log('connect success'); + // Send data. tcp.send({ data: 'Hello, server!' @@ -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(() => { tcp.close((err) => { console.log('close socket.') @@ -122,3 +162,167 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th tcp.off('close'); }, 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) diff --git a/en/application-dev/device/pointerstyle-guidelines.md b/en/application-dev/device/pointerstyle-guidelines.md index 06a904a5c5ed3a52dba9bf93bc0fa5a9e8a48690..bcc09093eed4440a0c5e62c5d4cfe37a3f954c87 100644 --- a/en/application-dev/device/pointerstyle-guidelines.md +++ b/en/application-dev/device/pointerstyle-guidelines.md @@ -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. ```js +import pointer from '@ohos.multimodalInput.pointer'; import window from '@ohos.window'; // 1. Enable the color pickup function. // 2. Obtain the window ID. -window.getTopWindow((error, windowClass) => { - windowClass.getProperties((error, data) => { - var windowId = data.id; - if (windowId < 0) { - console.log(`Invalid windowId`); - return; - } - try { - // 3. Set the mouse pointer to the color picker style. - pointer.setPointerStyle(windowId, pointer.PointerStyle.COLOR_SUCKER).then(() => { - 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)}`); - } - }); +window.getLastWindow(this.context, (error, windowClass) => { + if (error.code) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error)); + return; + } + var windowId = windowClass.getWindowProperties().id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + // 3. Set the mouse pointer to the color picker style. + pointer.setPointerStyle(windowId, pointer.PointerStyle.COLOR_SUCKER).then(() => { + 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. -window.getTopWindow((error, windowClass) => { - windowClass.getProperties((error, data) => { - var windowId = data.id; - if (windowId < 0) { - console.log(`Invalid windowId`); - return; - } - try { - // 5. Set the mouse pointer to the default style. - pointer.setPointerStyle(windowId, pointer.PointerStyle.DEFAULT).then(() => { - 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)}`); - } - }); +window.getLastWindow(this.context, (error, windowClass) => { + if (error.code) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error)); + return; + } + var windowId = windowClass.getWindowProperties().id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + // 5. Set the mouse pointer to the default style. + pointer.setPointerStyle(windowId, pointer.PointerStyle.DEFAULT).then(() => { + 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`)}`); + } }); ``` diff --git a/en/application-dev/dfx/errormanager-guidelines.md b/en/application-dev/dfx/errormanager-guidelines.md index a43d7c1fcec9042c6d8cbeb1287cebdddd3915d1..4679cfcfc78893590fe73eab770e49fc68a1a828 100644 --- a/en/application-dev/dfx/errormanager-guidelines.md +++ b/en/application-dev/dfx/errormanager-guidelines.md @@ -12,11 +12,11 @@ Application error management APIs are provided by the **errorManager** module. F | 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.| -| unregisterErrorObserver(observerId: number, callback: AsyncCallback\): void | Unregisters an observer in callback mode. The number passed to this API is the SN of the registered observer. | -| unregisterErrorObserver(observerId: number): Promise\ | Unregisters an observer in promise mode. The number passed to this API 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.| +| off(type: "error", observerId: number, callback: AsyncCallback\): 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): Promise\ | 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 @@ -36,7 +36,7 @@ When an asynchronous callback is used, the return value can be processed directl ## Development Example ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import errorManager from '@ohos.app.ability.errorManager'; let registerId = -1; @@ -45,15 +45,16 @@ let callback = { console.log(errMsg); } } -export default class MainAbility extends Ability { + +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("[Demo] MainAbility onCreate") + console.log("[Demo] EntryAbility onCreate") registerId = errorManager.on("error", callback); globalThis.abilityWant = want; } onDestroy() { - console.log("[Demo] MainAbility onDestroy") + console.log("[Demo] EntryAbility onDestroy") errorManager.off("error", registerId, (result) => { console.log("[Demo] result " + result.code + ";" + result.message) }); @@ -61,7 +62,7 @@ export default class MainAbility extends Ability { onWindowStageCreate(windowStage) { // Main window is created for this ability. - console.log("[Demo] MainAbility onWindowStageCreate") + console.log("[Demo] EntryAbility onWindowStageCreate") windowStage.loadContent("pages/index", (err, data) => { if (err.code) { @@ -74,17 +75,17 @@ export default class MainAbility extends Ability { onWindowStageDestroy() { // Main window is destroyed to release UI resources. - console.log("[Demo] MainAbility onWindowStageDestroy") + console.log("[Demo] EntryAbility onWindowStageDestroy") } onForeground() { // Ability is brought to the foreground. - console.log("[Demo] MainAbility onForeground") + console.log("[Demo] EntryAbility onForeground") } onBackground() { // Ability is brought back to the background. - console.log("[Demo] MainAbility onBackground") + console.log("[Demo] EntryAbility onBackground") } }; ``` diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index 02cebd741ce26bd61dd4a4282efcf2cc6d89ad08..2a85da3460cf4dff87a3076686a8b31ae136f65a 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -1,12 +1,12 @@ # @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. -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. + 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. > **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. > -> - 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 @@ -42,7 +42,7 @@ Obtains the localized script for the specified country. **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 | | ------ | ---------------------- | @@ -81,7 +81,7 @@ Obtains the localized script for the specified language. **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 | | ------ | ---------------------- | @@ -112,7 +112,7 @@ Obtains the list of system languages. For details about languages, see [Instanti **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 | | ------ | ---------------------- | @@ -149,7 +149,7 @@ Obtains the list of countries and regions supported for the specified language. **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 | | ------ | ---------------------- | @@ -187,7 +187,7 @@ Checks whether the system language matches the specified region. **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 | | ------ | ---------------------- | @@ -218,7 +218,7 @@ Obtains the system language. For details about languages, see [Instantiating the **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 | | ------ | ---------------------- | @@ -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. -**System API**: This is a system API. +This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -253,7 +253,7 @@ Sets the system language. Currently, this API does not support real-time updatin **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 | | ------ | ---------------------- | @@ -284,7 +284,7 @@ Obtains the system region. For details about system regions, see [Instantiating **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 | | ------ | ---------------------- | @@ -305,7 +305,7 @@ static setSystemRegion(region: string): void Sets the system region. -**System API**: This is a system API. +This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -319,7 +319,7 @@ Sets the system region. **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 | | ------ | ---------------------- | @@ -350,7 +350,7 @@ Obtains the system locale. For details about system locales, see [Instantiating **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 | | ------ | ---------------------- | @@ -371,7 +371,7 @@ static setSystemLocale(locale: string): void Sets the system locale. -**System API**: This is a system API. +This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -385,7 +385,7 @@ Sets the system locale. **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 | | ------ | ---------------------- | @@ -416,7 +416,7 @@ Checks whether the 24-hour clock is used. **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 | | ------ | ---------------------- | @@ -437,7 +437,7 @@ static set24HourClock(option: boolean): void Sets the 24-hour clock. -**System API**: This is a system API. +This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -451,7 +451,7 @@ Sets the 24-hour clock. **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 | | ------ | ---------------------- | @@ -473,7 +473,7 @@ static addPreferredLanguage(language: string, index?: number): void 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 @@ -488,7 +488,7 @@ Adds a preferred language to the specified position on the preferred language li **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 | | ------ | ---------------------- | @@ -512,7 +512,7 @@ static removePreferredLanguage(index: number): void 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 @@ -526,7 +526,7 @@ Deletes a preferred language from the specified position on the preferred langua **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 | | ------ | ---------------------- | @@ -547,7 +547,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod static getPreferredLanguageList(): Array<string> -Obtains the preferred language list. +Obtains the list of preferred languages. **System capability**: SystemCapability.Global.I18n @@ -555,11 +555,11 @@ Obtains the preferred language list. | Type | Description | | ------------------- | --------- | -| Array<string> | Preferred language list.| +| Array<string> | List of preferred languages.| **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 | | ------ | ---------------------- | @@ -590,7 +590,7 @@ Obtains the first language in the preferred language list. **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 | | ------ | ---------------------- | @@ -621,7 +621,7 @@ Obtains the preferred language of an application. **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 | | ------ | ---------------------- | @@ -642,7 +642,7 @@ static setUsingLocalDigit(flag: boolean): void 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 @@ -652,11 +652,11 @@ Specifies whether to enable use of local digits. | 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** -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 | | ------ | ---------------------- | @@ -687,7 +687,7 @@ Checks whether use of local digits is enabled. **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 | | ------ | ---------------------- | @@ -1059,7 +1059,7 @@ Creates a **PhoneNumberFormat** object. | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------- | | 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** ```js @@ -1149,7 +1149,7 @@ Obtains the home location of a phone number. ``` -## PhoneNumberFormatOptions8+ +## PhoneNumberFormatOptions9+ Defines the options for this PhoneNumberFormat object. @@ -1194,7 +1194,7 @@ Creates an **IndexUtil** object. **Example** ```js - let indexUtil= I18n.getInstance("zh-CN"); + let indexUtil = I18n.getInstance("zh-CN"); ``` @@ -1267,7 +1267,7 @@ Obtains the index of a text object. **Example** ```js - let indexUtil= I18n.getInstance("zh-CN"); + let indexUtil = I18n.getInstance("zh-CN"); let index = indexUtil.getIndex("hi"); // index = "H" ``` @@ -1382,7 +1382,7 @@ Puts the [BreakIterator](#breakiterator8) object to the first text boundary, whi **Example** ```js - let iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); let firstPos = iterator.first(); // firstPos = 0 ``` @@ -1689,7 +1689,7 @@ Obtains the list of time zone city IDs supported by the system. 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 @@ -2363,7 +2363,7 @@ This API is supported since API version 8 and is deprecated since API version 9. getPreferredLanguageList(): Array<string> -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. @@ -2373,7 +2373,7 @@ This API is supported since API version 8 and is deprecated since API version 9. | Type | Description | | ------------------- | --------- | -| Array<string> | Preferred language list.| +| Array<string> | List of preferred languages.| **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index 623695f1cc4c167bd984a408b5c2dde85ff42cf5..22b2225382e82166356b37003483c7c27a1400e0 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -67,7 +67,7 @@ Creates a **Locale** object. | 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).| -| options9+ | [LocaleOptions](#localeoptions6) | No | Options for creating the **Locale** object. | +| options9+ | [LocaleOptions](#localeoptions9) | No | Options for creating the **Locale** object. | **Example** ```js @@ -159,7 +159,7 @@ Minimizes information of the **Locale** object. If the script and locale informa ``` -## LocaleOptions6+ +## LocaleOptions9+ Represents the locale options. @@ -206,7 +206,7 @@ Creates a **DateTimeOptions** object for the specified locale. | Name | Type | Mandatory | Description | | -------------------- | ------------------------------------ | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [DateTimeOptions](#datetimeoptions6) | No | Options for creating a **DateTimeFormat** object. | +| options9+ | [DateTimeOptions](#datetimeoptions9) | No | Options for creating a **DateTimeFormat** object. | **Example** ```js @@ -298,7 +298,7 @@ Obtains the formatting options for **DateTimeFormat** object. | Type | Description | | ------------------------------------ | ----------------------------- | -| [DateTimeOptions](#datetimeoptions6) | Formatting options for **DateTimeFormat** objects.| +| [DateTimeOptions](#datetimeoptions9) | Formatting options for **DateTimeFormat** objects.| **Example** ```js @@ -310,7 +310,7 @@ Obtains the formatting options for **DateTimeFormat** object. ``` -## DateTimeOptions6+ +## DateTimeOptions9+ Provides the options for the **DateTimeFormat** object. @@ -370,7 +370,7 @@ Creates a **NumberFormat** object for the specified locale. | Name | Type | Mandatory | Description | | -------------------- | -------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [NumberOptions](#numberoptions6) | No | Options for creating a **NumberFormat** object. | +| options9+ | [NumberOptions](#numberoptions9) | No | Options for creating a **NumberFormat** object. | **Example** ```js @@ -420,7 +420,7 @@ Obtains the options of the **NumberFormat** object. | Type | Description | | -------------------------------- | --------------------------- | -| [NumberOptions](#numberoptions6) | Formatting options for **NumberFormat** objects.| +| [NumberOptions](#numberoptions9) | Formatting options for **NumberFormat** objects.| **Example** @@ -433,7 +433,7 @@ Obtains the options of the **NumberFormat** object. ``` -## NumberOptions6+ +## NumberOptions9+ Defines the device capability. @@ -493,7 +493,7 @@ Creates a **Collator** object. | Name | Type | Mandatory | Description | | -------------------- | ------------------------------------ | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [CollatorOptions](#collatoroptions8) | No | Options for creating a **Collator** object. | +| options9+ | [CollatorOptions](#collatoroptions9) | No | Options for creating a **Collator** object. | **Example** ```js @@ -544,7 +544,7 @@ Returns properties reflecting the locale and collation options of a **Collator** | Type | Description | | ------------------------------------ | ----------------- | -| [CollatorOptions](#collatoroptions8) | Properties of the **Collator** object.| +| [CollatorOptions](#collatoroptions9) | Properties of the **Collator** object.| **Example** ```js @@ -556,7 +556,7 @@ Returns properties reflecting the locale and collation options of a **Collator** ``` -## CollatorOptions8+ +## CollatorOptions9+ Represents the properties of a **Collator** object. @@ -604,7 +604,7 @@ Creates a **PluralRules** object to obtain the singular-plural type of numbers. | Name | Type | Mandatory | Description | | -------------------- | ---------------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [PluralRulesOptions](#pluralrulesoptions8) | No | Options for creating a **PluralRules** object. | +| options9+ | [PluralRulesOptions](#pluralrulesoptions9) | No | Options for creating a **PluralRules** object. | **Example** ```js @@ -647,7 +647,7 @@ Obtains a string that represents the singular-plural type of the specified numbe ``` -## PluralRulesOptions8+ +## PluralRulesOptions9+ Represents the properties of a **PluralRules** object. @@ -695,7 +695,7 @@ Creates a **RelativeTimeFormat** object. | Name | Type | Mandatory | Description | | -------------------- | ---------------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions8) | No | Options for creating a **RelativeTimeFormat** object. | +| options9+ | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions9) | No | Options for creating a **RelativeTimeFormat** object. | **Example** ```js @@ -787,7 +787,7 @@ Obtains the formatting options for **RelativeTimeFormat** objects. ``` -## RelativeTimeFormatInputOptions8+ +## RelativeTimeFormatInputOptions9+ Represents the properties of a **RelativeTimeFormat** object. diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index d5a5f1585a5ae153694833b611861cc49325c4e7..adb1c8ee47ae8dc076f5b2c2f00b2c2ca92a2cd5 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -1,8 +1,8 @@ # @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**
+> **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. ## Modules to Import @@ -10,6 +10,40 @@ The **connection** module provides basic network management capabilities. You ca ```js 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 @@ -25,14 +59,22 @@ Obtains the default active data network. This API uses an asynchronous callback | 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** ```js -connection.getDefaultNet(function (error, netHandle) { +connection.getDefaultNet(function (error, data) { 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 | --------------------------------- | ------------------------------------- | | 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** ```js -connection.getDefaultNet().then(function (netHandle) { - console.log(JSON.stringify(netHandle)) +connection.getDefaultNet().then(function (data) { + console.log(JSON.stringify(data)) }) ``` ## connection.getDefaultNetSync9+ -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. @@ -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.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **Example** ```js let netHandle = connection.getDefaultNetSync(); ``` +## connection.getGlobalHttpProxy10+ -## connection.hasDefaultNet +getGlobalHttpProxy(callback: AsyncCallback\): void -hasDefaultNet(callback: AsyncCallback\): 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.getGlobalHttpProxy10+ + +getGlobalHttpProxy(): Promise\; + +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.setGlobalHttpProxy10+ + +setGlobalHttpProxy(httpProxy: HttpProxy, callback: AsyncCallback\): 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 **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** indicates that the default data network is activated.| +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------------------------ | ---- | ---------------- | +| httpProxy | [HttpProxy](#httpproxy) | Yes | Global HTTP proxy configuration of the network.| +| callback | AsyncCallback\ | 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** ```js -connection.hasDefaultNet(function (error, has) { - console.log(JSON.stringify(error)) - console.log('has: ' + has) +let exclusionStr="192.168,baidu.com" +let exclusionArray = exclusionStr.split(','); +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.setGlobalHttpProxy10+ + +setGlobalHttpProxy(httpProxy: HttpProxy): Promise\; + +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\ | 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.getAppNet9+ -hasDefaultNet(): Promise\ +getAppNet(callback: AsyncCallback\): 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.getAppNet9+ + +getAppNet(): Promise\; + +Obtains information about the network bound to an application. This API uses a promise to return the result. **System capability**: SystemCapability.Communication.NetManager.Core **Return value** -| Type | Description | -| ----------------- | ----------------------------------------------- | -| Promise\ | Promise used to return the result. The value **true** indicates that the default data network is activated.| +| Type | Description | +| --------------------------------- | ------------------------------------- | +| 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.SetAppNet9+ + +setAppNet(netHandle: NetHandle, callback: AsyncCallback\): 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\ | 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** ```js -connection.hasDefaultNet().then(function (has) { - console.log('has: ' + has) +connection.getDefaultNet(function (error, netHandle) { + connection.setAppNet(netHandle, (error, data) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) + }); +}) +``` + +## connection.SetAppNet9+ + +setAppNet(netHandle: NetHandle): Promise\; + +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\ | 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) { getAllNets(callback: AsyncCallback<Array<NetHandle>>): 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 @@ -146,23 +458,30 @@ Obtains the list of all active data networks. This API uses an asynchronous call | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Array<[NetHandle](#nethandle)>> | Yes| Callback used to return the result.| +| callback | AsyncCallback<Array<[NetHandle](#nethandle)>> | 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** ```js -connection.getAllNets(function (error, nets) { +connection.getAllNets(function (error, data) { console.log(JSON.stringify(error)) - console.log(JSON.stringify(nets)) + console.log(JSON.stringify(data)) }); ``` - ## connection.getAllNets getAllNets(): Promise<Array<NetHandle>> -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 @@ -174,11 +493,19 @@ Obtains the list of all active data networks. This API uses a promise to return | -------- | -------- | | Promise<Array<[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** ```js -connection.getAllNets().then(function (nets) { - console.log(JSON.stringify(nets)) +connection.getAllNets().then(function (data) { + console.log(JSON.stringify(data)) }); ``` @@ -186,7 +513,7 @@ connection.getAllNets().then(function (nets) { getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\): 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 @@ -197,15 +524,25 @@ Obtains connection properties of the network corresponding to the given network | Name | Type | Mandatory| Description | | --------- | ------------------------------------------------------------ | ---- | ---------------- | | 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** ```js 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(info)) + console.log(JSON.stringify(data)) }) }) ``` @@ -214,7 +551,7 @@ connection.getDefaultNet().then(function (netHandle) { getConnectionProperties(netHandle: NetHandle): Promise\ -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 @@ -232,12 +569,22 @@ Obtains connection properties of the network corresponding to **netHandle**. Thi | ------------------------------------------------------- | --------------------------------- | | 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** ```js connection.getDefaultNet().then(function (netHandle) { - connection.getConnectionProperties(netHandle).then(function (info) { - console.log(JSON.stringify(info)) + connection.getConnectionProperties(netHandle).then(function (data) { + console.log(JSON.stringify(data)) }) }) ``` @@ -246,7 +593,7 @@ connection.getDefaultNet().then(function (netHandle) { getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\): 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 @@ -257,15 +604,25 @@ Obtains capability information of the network corresponding to **netHandle**. Th | Name | Type | Mandatory| Description | | --------- | --------------------------------------------------- | ---- | ---------------- | | 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** ```js 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(info)) + console.log(JSON.stringify(data)) }) }) ``` @@ -274,7 +631,7 @@ connection.getDefaultNet().then(function (netHandle) { getNetCapabilities(netHandle: NetHandle): Promise\ -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 @@ -292,12 +649,22 @@ Obtains capability information of the network corresponding to **netHandle**. Th | --------------------------------------------- | --------------------------------- | | 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** ```js connection.getDefaultNet().then(function (netHandle) { - connection.getNetCapabilities(netHandle).then(function (info) { - console.log(JSON.stringify(info)) + connection.getNetCapabilities(netHandle).then(function (data) { + console.log(JSON.stringify(data)) }) }) ``` @@ -318,12 +685,20 @@ Checks whether the data traffic usage on the current network is metered. This AP | -------- | ----------------------- | ---- | -------------------------------------- | | callback | AsyncCallback\ | 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 -connection.isDefaultNetMetered(function (error, has) { +connection.isDefaultNetMetered(function (error, data) { 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 | ----------------- | ----------------------------------------------- | | Promise\ | 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\): 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\ | 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\ + +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\ | 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 -connection.isDefaultNetMetered().then(function (has) { - console.log('has: ' + has) +connection.hasDefaultNet().then(function (data) { + console.log('data: ' + data) +}) +``` + +## connection.enableAirplaneMode + +enableAirplaneMode(callback: AsyncCallback\): 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\ | 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\ + +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\ | 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 + +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\ | 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\ + +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\ | 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) { reportNetConnected(netHandle: NetHandle, callback: AsyncCallback<void>): void -Reports connection of the data network. 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. +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. **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 | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| callback | AsyncCallback<void> | 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** @@ -384,9 +973,8 @@ connection.getDefaultNet().then(function (netHandle) { reportNetConnected(netHandle: NetHandle): Promise<void> -Reports connection of the data network. 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. +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. **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 | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| **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 @@ -414,14 +1011,12 @@ connection.getDefaultNet().then(function (netHandle) { }); ``` - ## connection.reportNetDisconnected reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback<void>): void -Reports disconnection of the data network. 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. +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. **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 | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| callback | AsyncCallback<void> | 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** @@ -444,14 +1049,12 @@ connection.getDefaultNet().then(function (netHandle) { }); ``` - ## connection.reportNetDisconnected reportNetDisconnected(netHandle: NetHandle): Promise<void> -Reports disconnection of the data network. 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. +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. **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 | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| **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 @@ -493,213 +1105,185 @@ Resolves the host name by using the default network to obtain all IP addresses. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------- | ---- | ------------------ | -| host | string | Yes | Host name to be resolved.| -| callback | AsyncCallback\> | Yes | Callback used to return the result. | - -**Example** - -```js -let host = "xxxx"; -connection.getAddressesByName(host, function (error, addresses) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(addresses)) -}) -``` - -## connection.getAddressesByName - -getAddressesByName(host: string): Promise\> - -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\> | 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 - -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\ | Yes | Callback used to return the result. | +| host | string | Yes | Host name to resolve.| +| callback | AsyncCallback\> | 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** ```js -connection.enableAirplaneMode(function (error) { +let host = "xxxx"; +connection.getAddressesByName(host, function (error, data) { console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` -## connection.enableAirplaneMode +## connection.getAddressesByName -enableAirplaneMode(): Promise\ +getAddressesByName(host: string): Promise\> -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** | Type | Description | | ------------------------------------------- | ----------------------------- | -| Promise\ | Promise that returns no value.| +| Promise\> | 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 -connection.enableAirplaneMode().then(function (error) { - console.log(JSON.stringify(error)) +let host = "xxxx"; +connection.getAddressesByName(host).then(function (data) { + console.log(JSON.stringify(data)) }) ``` -## connection.disableAirplaneMode - -disableAirplaneMode(callback: AsyncCallback\): 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 +## NetConnection -**Parameters** +Represents the network connection handle. -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | ------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +### register -**Example** +register(callback: AsyncCallback\): void -```js -connection.disableAirplaneMode(function (error) { - console.log(JSON.stringify(error)) -}) -``` +Registers a listener for network status changes. -## connection.disableAirplaneMode +**Required permission**: ohos.permission.GET_NETWORK_INFO -disableAirplaneMode(): Promise\ +**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\ | 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\ | Promise that returns no value.| **Example** ```js -connection.disableAirplaneMode().then(function (error) { +netConnection.register(function (error) { console.log(JSON.stringify(error)) }) ``` -## connection.createNetConnection +### unregister -createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection +unregister(callback: AsyncCallback\): void -Obtains the handle of the network specified by **netSpecifier**. +Unregisters the listener for network status changes. **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.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| callback | AsyncCallback\ | 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.| -**Return value** +**Error codes** -| Type | Description | -| ------------------------------- | -------------------- | -| [NetConnection](#netconnection) | Handle of the network specified by **netSpecifier**.| +| ID| Error Message | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | +| 2101007 | The same callback exists. | **Example** ```js -// Default network -let netConnection = connection.createNetConnection() - -// Cellular network -let netConnectionCellular = connection.createNetConnection({ - netCapabilities: { - bearerTypes: [connection.NetBearType.BEARER_CELLULAR] - } +netConnection.unregister(function (error) { + console.log(JSON.stringify(error)) }) ``` -## NetConnection - -Represents the network connection handle. - ### on('netAvailable') on(type: 'netAvailable', callback: Callback\): void 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 **Parameters** | Name | Type | Mandatory| Description | | -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **netAvailable**.
**netAvailable**: event indicating that the data network is available.| -| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. | +| type | string | Yes | Event type. The value is fixed to **netAvailable**.
**netAvailable**: event indicating that the data network is available.| +| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the network handle.| **Example** ```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)) }) + +// 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<{ netHandle: NetHandle, blocked: boolean }>): 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 @@ -707,22 +1291,38 @@ Registers a listener for **netCapabilitiesChange** events. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **netCapabilitiesChange**.
**netCapabilitiesChange**: event indicating that network capabilities have changed.| -| callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | Yes | Callback used to return the result. | +| type | string | Yes | Event type. The value is fixed to **netBlockStatusChange**.
**netBlockStatusChange**: event indicating a change in the network blocking status.| +| callback | Callback<{ netHandle: [NetHandle](#nethandle), blocked: boolean }> | Yes | Callback used to return the network handle (**netHandle**) and network status (**blocked**).| **Example** ```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)) }) + +// 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 @@ -730,22 +1330,38 @@ Registers a listener for **netConnectionPropertiesChange** events. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **netConnectionPropertiesChange**.
**netConnectionPropertiesChange**: event indicating that network connection properties have changed.| -| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the result. | +| type | string | Yes | Event type. The value is fixed to **netCapabilitiesChange**.
**netCapabilitiesChange**: event indicating that the network capabilities have changed.| +| callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).| **Example** ```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)) }) + +// Call unregister to unregister the listener. +netCon.unregister(function (error) { + console.log(JSON.stringify(error)) +}) ``` -### on('netBlockStatusChange') +### on('netConnectionPropertiesChange') -on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): 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 @@ -753,15 +1369,29 @@ Registers a listener for **netBlockStatusChange** events. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **netBlockStatusChange**.
**netBlockStatusChange**: event indicating a change in the network blocking status.| -| callback | Callback<{ netHandle: [NetHandle](#nethandle), blocked: boolean }> | Yes | Callback used to return the result. | +| type | string | Yes | Event type. The value is fixed to **netConnectionPropertiesChange**.
**netConnectionPropertiesChange**: event indicating that network connection properties have changed.| +| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).| **Example** ```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)) }) + +// Call unregister to unregister the listener. +netCon.unregister(function (error) { + console.log(JSON.stringify(error)) +}) ``` ### on('netLost') @@ -770,22 +1400,37 @@ on(type: 'netLost', callback: Callback\): void 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 **Parameters** | Name | Type | Mandatory| Description | | -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **netLost**.
netLost: event indicating that the network is interrupted or normally disconnected.| -| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. | +| type | string | Yes | Event type. The value is fixed to **netLost**.
netLost: event indicating that the network is interrupted or normally disconnected.| +| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the network handle (**netHandle**).| **Example** ```js -let netConnection1 = connection.createNetConnection() -netConnection1.on('netLost', 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 netLost events. Event notifications can be received only after register is called. +netCon.on('netLost', function (data) { console.log(JSON.stringify(data)) }) + +// Call unregister to unregister the listener. +netCon.unregister(function (error) { + console.log(JSON.stringify(error)) +}) ``` ### on('netUnavailable') @@ -794,65 +1439,35 @@ on(type: 'netUnavailable', callback: Callback\): void 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 **Parameters** | Name | Type | Mandatory| Description | | -------- | --------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **netUnavailable**.
**netUnavailable**: event indicating that the network is unavailable.| -| callback | Callback\ | Yes | Callback used to return the result. | +| type | string | Yes | Event type. The value is fixed to **netUnavailable**.
**netUnavailable**: event indicating that the network is unavailable.| +| callback | Callback\ | Yes | Callback used to return the result, which is empty.| **Example** ```js -netConnection.on('netUnavailable', function (data) { - console.log(JSON.stringify(data)) -}) -``` - -### register - -register(callback: AsyncCallback\): 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\ | Yes | Callback used to return the result.| +// Create a NetConnection object. +let netCon = connection.createNetConnection() -**Example** - -```js -netConnection.register(function (error) { +// Call register to register a listener. +netCon.register(function (error) { console.log(JSON.stringify(error)) }) -``` - -### unregister - -unregister(callback: AsyncCallback\): void - -Unregisters the listener for network status changes. - -**System capability**: SystemCapability.Communication.NetManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------- | -| callback | AsyncCallback\ | 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 -netConnection.unregister(function (error) { +// Call unregister to unregister the listener. +netCon.unregister(function (error) { console.log(JSON.stringify(error)) }) ``` @@ -861,24 +1476,22 @@ netConnection.unregister(function (error) { 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 -### Parameters +### Attributes -| Name| Type | Description | -| ------ | ------ | ------------------------- | -| netId | number | Network ID. The value **0** indicates no default network. Any other value must be greater than or equal to 100.| +| Name | Type | Mandatory| Description | +| ------ | ------ | --- |------------------------- | +| netId | number | Yes | Network ID. The value **0** indicates no default network. Any other value must be greater than or equal to 100.| ### bindSocket9+ -bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\): void; +bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\): void 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 **Parameters** @@ -886,24 +1499,33 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses | Name | Type | Mandatory| Description | | ----------- | ------------------------ | ---- | -------------------------------| | socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | Yes| **TCPSocket** or **UDPSocket** object.| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| callback | AsyncCallback\ | 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** ```js import socket from "@ohos.net.socket"; -connection.getDefaultNet().then((netHandle)=>{ +connection.getDefaultNet().then((netHandle) => { var tcp = socket.constructTCPSocketInstance(); var udp = socket.constructUDPSocketInstance(); let socketType = "TCPSocket"; if (socketType == "TCPSocket") { tcp.bind({ - address: '192.168.xx.xxx', port: xxxx, family: 1 - }, err => { - if (err) { + address: '192.168.xx.xxx', port: 8080, family: 1 + }, error => { + if (error) { console.log('bind fail'); } - netHandle.bindSocket(tcp, (error, data)=>{ + netHandle.bindSocket(tcp, (error, data) => { if (error) { console.log(JSON.stringify(error)); } else { @@ -913,19 +1535,19 @@ connection.getDefaultNet().then((netHandle)=>{ }) } else { 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.bind({ - address: '192.168.xx.xxx', port: xxxx, family: 1 - }, err => { - if (err) { + address: '192.168.xx.xxx', port: 8080, family: 1 + }, error => { + if (error) { console.log('bind fail'); } udp.on('message', (data) => { console.log(JSON.stringify(data)) }); - netHandle.bindSocket(udp,(error, data)=>{ + netHandle.bindSocket(udp, (error, data) => { if (error) { console.log(JSON.stringify(error)); } else { @@ -937,14 +1559,12 @@ connection.getDefaultNet().then((netHandle)=>{ }) ``` -### bindSocket +### bindSocket9+ bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\; 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 **Parameters** @@ -959,56 +1579,60 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses | -------------- | ---------------------- | | Promise\ | 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** ```js import socket from "@ohos.net.socket"; -connection.getDefaultNet().then((netHandle)=>{ +connection.getDefaultNet().then((netHandle) => { var tcp = socket.constructTCPSocketInstance(); var udp = socket.constructUDPSocketInstance(); let socketType = "TCPSocket"; if (socketType == "TCPSocket") { tcp.bind({ - address: '192.168.xx.xxx', port: xxxx, family: 1 - }, err => { - if (err) { + address: '192.168.xx.xxx', port: 8080, family: 1 + }, error => { + if (error) { console.log('bind fail'); } - netHandle.bindSocket(tcp).then((err, data) => { - if (err) { - console.log(JSON.stringify(err)); - } else { - console.log(JSON.stringify(data)); - } + netHandle.bindSocket(tcp).then((data) => { + console.log(JSON.stringify(data)); + }).catch(error => { + console.log(JSON.stringify(error)); }) }) } else { 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.bind({ - address: '192.168.xx.xxx', port: xxxx, family: 1 - }, err => { - if (err) { + address: '192.168.xx.xxx', port: 8080, family: 1 + }, error => { + if (error) { console.log('bind fail'); } udp.on('message', (data) => { console.log(JSON.stringify(data)); }) - netHandle.bindSocket(udp).then((err, data) => { - if (err) { - console.log(JSON.stringify(err)); - } else { - console.log(JSON.stringify(data)); - } + netHandle.bindSocket(udp).then((data) => { + console.log(JSON.stringify(data)); + }).catch(error => { + console.log(JSON.stringify(error)); }) }) } }) ``` - ### getAddressesByName getAddressesByName(host: string, callback: AsyncCallback\>): void @@ -1023,17 +1647,27 @@ Resolves the host name by using the corresponding network to obtain all IP addre | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------- | ---- | ------------------ | -| host | string | Yes | Host name to be resolved.| -| callback | AsyncCallback\> | Yes | Callback used to return the result. | +| host | string | Yes | Host name to resolve.| +| callback | AsyncCallback\> | 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** ```js connection.getDefaultNet().then(function (netHandle) { let host = "xxxx"; - netHandle.getAddressesByName(host, function (error, addresses) { + netHandle.getAddressesByName(host, function (error, data) { 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 | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| host | string | Yes | Host name to be resolved.| +| host | string | Yes | Host name to resolve.| **Return value** @@ -1060,13 +1694,23 @@ Resolves the host name by using the corresponding network to obtain all IP addre | ------------------------------------------- | ----------------------------- | | Promise\> | 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 connection.getDefaultNet().then(function (netHandle) { let host = "xxxx"; - netHandle.getAddressesByName(host).then(function (addresses) { - console.log(JSON.stringify(addresses)) + netHandle.getAddressesByName(host).then(function (data) { + console.log(JSON.stringify(data)) }) }) ``` @@ -1085,17 +1729,27 @@ Resolves the host name by using the corresponding network to obtain the first IP | Name | Type | Mandatory| Description | | -------- | ----------------------------------------- | ---- | ------------------ | -| host | string | Yes | Host name to be resolved.| -| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. | +| host | string | Yes | Host name to resolve.| +| 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** ```js connection.getDefaultNet().then(function (netHandle) { let host = "xxxx"; - netHandle.getAddressByName(host, function (error, address) { + netHandle.getAddressByName(host, function (error, data) { 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 | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| host | string | Yes | Host name to be resolved.| +| host | string | Yes | Host name to resolve.| **Return value** @@ -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.| +**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) { let host = "xxxx"; - netHandle.getAddressByName(host).then(function (address) { - console.log(JSON.stringify(address)) + netHandle.getAddressByName(host).then(function (data) { + 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 -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| netCapabilities | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. | -| bearerPrivateIdentifier | string | No | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).| +| Name | Value | Description | +| ------------------------ | ---- | ---------------------- | +| NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.| +| 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 -| 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. | +| Name | Value | Description | +| --------------- | ---- | ----------- | +| BEARER_CELLULAR | 0 | Cellular network. | +| BEARER_WIFI | 1 | Wi-Fi network.| +| BEARER_ETHERNET | 3 | Ethernet network.| -## NetCap +## HttpProxy10+ -Defines the network capability. +Defines the global HTTP proxy configuration of the network. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Value | Description | -| ------------------------ | ---- | ---------------------- | -| NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.| -| NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.| -| NET_CAPABILITY_INTERNET | 12 | The network can connect to the Internet.| -| NET_CAPABILITY_NOT_VPN | 15 | The network does not use a Virtual Private Network (VPN).| -| NET_CAPABILITY_VALIDATED | 16 | The network is available. | +| Name | Type | Mandatory| Description | +| ------ | ------ | --- |------------------------- | +| host | string | No | Host name of the proxy server.| +| port | number | No | Host port.| +| exclusionList | Array | No | List of hosts that do not use the proxy server.| -## NetBearType +## NetSpecifier -Defines the network type. +Provides an instance that bears data network capabilities. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Value | Description | -| --------------- | ---- | ----------- | -| BEARER_CELLULAR | 0 | Cellular network | -| BEARER_WIFI | 1 | Wi-Fi network| -| BEARER_ETHERNET | 3 | Ethernet network| +| Name | Type | Mandatory | Description | +| ----------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ | +| netCapabilities | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. | +| bearerPrivateIdentifier | string | No | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).| + +## 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 @@ -1189,48 +1865,48 @@ Defines the network connection properties. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| interfaceName | string | Yes | NIC card name. | -| domains | string | Yes | Domain. The default value is **""**.| -| linkAddresses | Array\<[LinkAddress](#linkaddress)> | Yes | Link information. | -| routes | Array\<[RouteInfo](#routeinfo)> | Yes | Route information. | -| dnses | Array\<[NetAddress](#netaddress)>; | Yes | Network address. For details, see [NetAddress](#netaddress).| -| mtu | number | Yes | Maximum transmission unit (MTU). | +| Name | Type | Mandatory| Description | +| ------------- | ---------------------------------- | ----|---------------- | +| interfaceName | string | Yes|Network interface card (NIC) name. | +| domains | string | Yes|Domain. The default value is **""**.| +| linkAddresses | Array\<[LinkAddress](#linkaddress)> | Yes|Link information. | +| routes | Array\<[RouteInfo](#routeinfo)> | Yes|Route information. | +| dnses | Array\<[NetAddress](#netaddress)> | Yes|Network address. For details, see [NetAddress](#netaddress).| +| mtu | number | Yes|Maximum transmission unit (MTU). | -## LinkAddress +## RouteInfo -Network link information. +Defines network route information. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| address | [NetAddress](#netaddress) | Yes | Link address. | -| prefixLength | number | Yes | Length of the link address prefix.| +| Name | Type | Mandatory|Description | +| -------------- | --------------------------- | --- |---------------- | +| interface | string | Yes|NIC name. | +| 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 -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| interface | string | Yes | NIC card name. | -| destination | [LinkAddress](#linkaddress) | Yes | Destination IP 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.| +| Name | Type | Mandatory|Description | +| ------------ | ----------------------- |---- |-------------------- | +| address | [NetAddress](#netaddress) | Yes| Link address. | +| prefixLength | number | Yes|Length of the link address prefix.| ## NetAddress -Defines the network address. +Defines a network address. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| 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**.| -| port | number | No | Port number. The value ranges from **0** to **65535**. | +| Name | Type | Mandatory| Description | +| ------- | ------ | -- |------------------------------ | +| address | string | Yes|Network address. | +| 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**. | diff --git a/en/application-dev/reference/apis/js-apis-net-ethernet.md b/en/application-dev/reference/apis/js-apis-net-ethernet.md index d41845ec1859507bb96a071dff2a57e16f4cf12b..3445952a9c818fad947373508accb50322e8cf59 100644 --- a/en/application-dev/reference/apis/js-apis-net-ethernet.md +++ b/en/application-dev/reference/apis/js-apis-net-ethernet.md @@ -1,8 +1,8 @@ -# @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. -> **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. ## Modules to Import @@ -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. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | 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. | | callback | AsyncCallback\ | 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** ```js -ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", routeAddr:"192.168.1.1", - gateAddr:"192.168.1.1", maskAddr:"255.255.255.0", dnsAddr0:"1.1.1.1", dnsAddr1:"2.2.2.2"}, - (error) => { - if (error) { - console.log("setIfaceConfig callback error = " + error); - } else { - console.log("setIfaceConfig callback ok "); - } - }); +ethernet.setIfaceConfig("eth0", { + 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" +}, (error) => { + if (error) { + console.log("setIfaceConfig callback error = " + JSON.stringify(error)); + } else { + console.log("setIfaceConfig callback ok "); + } +}); ``` ## ethernet.setIfaceConfig @@ -49,31 +70,53 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\ 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 -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | 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.| **Return value** | Type | Description | | ------------------- | ----------------------------------------------------------- | -| Promise\ | Promise that returns no value.| +| Promise\ | 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** ```js -ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", routeAddr:"192.168.1.1", - gateAddr:"192.168.1.1", maskAddr:"255.255.255.0", dnsAddr0:"1.1.1.1", dnsAddr1:"2.2.2.2"}).then(() => { +ethernet.setIfaceConfig("eth0", { + 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 "); -}).catch((error) => { - console.log("setIfaceConfig promiss error = " + error); +}).catch(error => { + console.log("setIfaceConfig promiss error = " + JSON.stringify(error)); }); ``` @@ -83,31 +126,44 @@ getIfaceConfig(iface: string, callback: AsyncCallback\): 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 -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | Name | Type | Mandatory | Description | | -------- | ----------------------------------------------- | ----- | ------------ | -| iface | string | Yes | Name of the network interface.| -| callback | AsyncCallback\<[InterfaceConfiguration](#interfaceconfiguration)> | Yes | Callback used to return the configuration. | +| iface | string | Yes | Interface name.| +| 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** ```js ethernet.getIfaceConfig("eth0", (error, value) => { if (error) { - console.log("getIfaceConfig callback error = " + error); + console.log("getIfaceConfig callback error = " + JSON.stringify(error)); } else { - console.log("getIfaceConfig callback mode = " + value.mode); - console.log("getIfaceConfig callback ipAddr = " + value.ipAddr); - console.log("getIfaceConfig callback routeAddr = " + value.routeAddr); - console.log("getIfaceConfig callback gateAddr = " + value.gateAddr); - console.log("getIfaceConfig callback maskAddr = " + value.maskAddr); - console.log("getIfaceConfig callback dns0Addr = " + value.dns0Addr); - console.log("getIfaceConfig callback dns1Addr = " + value.dns1Addr); + console.log("getIfaceConfig callback mode = " + JSON.stringify(value.mode)); + console.log("getIfaceConfig callback ipAddr = " + JSON.stringify(value.ipAddr)); + console.log("getIfaceConfig callback route = " + JSON.stringify(value.route)); + console.log("getIfaceConfig callback gateway = " + JSON.stringify(value.gateway)); + console.log("getIfaceConfig callback netMask = " + JSON.stringify(value.netMask)); + console.log("getIfaceConfig callback dnsServers = " + JSON.stringify(value.dnsServers)); + console.log("getIfaceConfig callback domain = " + JSON.stringify(value.domain)); } }); ``` @@ -118,64 +174,90 @@ getIfaceConfig(iface: string): Promise\ 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 -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ------------ | -| iface | string | Yes | Name of the network interface.| +| iface | string | Yes | Interface name.| **Return value** | 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** ```js ethernet.getIfaceConfig("eth0").then((data) => { - console.log("getIfaceConfig promiss mode = " + data.mode); - console.log("getIfaceConfig promiss ipAddr = " + data.ipAddr); - console.log("getIfaceConfig promiss routeAddr = " + data.routeAddr); - console.log("getIfaceConfig promiss gateAddr = " + data.gateAddr); - console.log("getIfaceConfig promiss maskAddr = " + data.maskAddr); - console.log("getIfaceConfig promiss dns0Addr = " + data.dns0Addr); - console.log("getIfaceConfig promiss dns1Addr = " + data.dns1Addr); -}).catch((error) => { - console.log("getIfaceConfig promiss error = " + error); + console.log("getIfaceConfig promiss mode = " + JSON.stringify(data.mode)); + console.log("getIfaceConfig promiss ipAddr = " + JSON.stringify(data.ipAddr)); + console.log("getIfaceConfig promiss route = " + JSON.stringify(data.route)); + console.log("getIfaceConfig promiss gateway = " + JSON.stringify(data.gateway)); + console.log("getIfaceConfig promiss netMask = " + JSON.stringify(data.netMask)); + console.log("getIfaceConfig promiss dnsServers = " + JSON.stringify(data.dnsServers)); + console.log("getIfaceConfig promiss domain = " + JSON.stringify(data.domain)); +}).catch(error => { + console.log("getIfaceConfig promiss error = " + JSON.stringify(error)); }); ``` ## ethernet.isIfaceActive -isIfaceActive(iface?: string, callback: AsyncCallback\): void +isIfaceActive(iface: string, callback: AsyncCallback\): void 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 -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | 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\ | 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** ```js ethernet.isIfaceActive("eth0", (error, value) => { - if (error) { - console.log("whether2Activate callback error = " + error); - } else { - console.log("whether2Activate callback = " + value); - } + if (error) { + console.log("whether2Activate callback error = " + JSON.stringify(error)); + } else { + console.log("whether2Activate callback = " + JSON.stringify(value)); + } }); ``` @@ -185,15 +267,17 @@ isIfaceActive(iface: string): Promise\ 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 -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | 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** @@ -201,13 +285,24 @@ Checks whether a network interface is active. This API uses a promise to return | ----------------| ------------------------------------------------------------------ | | Promise\ | 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** ```js ethernet.isIfaceActive("eth0").then((data) => { - console.log("isIfaceActive promiss = " + data); -}).catch((error) => { - console.log("isIfaceActive promiss error = " + error); + console.log("isIfaceActive promiss = " + JSON.stringify(data)); +}).catch(error => { + console.log("isIfaceActive promiss error = " + JSON.stringify(error)); }); ``` @@ -215,30 +310,40 @@ ethernet.isIfaceActive("eth0").then((data) => { getAllActiveIfaces(callback: AsyncCallback\>): 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 -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------ | ---- | ------------------------------ | -| callback | AsyncCallback\> | Yes | Callback used to return all the active network interface names obtained.| +| callback | AsyncCallback\> | 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** ```js ethernet.getAllActiveIfaces((error, value) => { - if (error) { - console.log("getAllActiveIfaces callback error = " + error); - } else { - console.log("getAllActiveIfaces callback value.length = " + value.length); - for (let i = 0; i < value.length; i++) { - console.log("getAllActiveIfaces callback = " + value[i]); + if (error) { + console.log("getAllActiveIfaces callback error = " + JSON.stringify(error)); + } else { + console.log("getAllActiveIfaces callback value.length = " + JSON.stringify(value.length)); + for (let i = 0; i < value.length; i++) { + console.log("getAllActiveIfaces callback = " + JSON.stringify(value[i])); + } } - } }); ``` @@ -246,30 +351,38 @@ ethernet.getAllActiveIfaces((error, value) => { getAllActiveIfaces(): Promise\> -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** | Type | Description | | ------------------------------ | ----------------------------------------------- | -| Promise\> | Promise used to return all the active network interface names obtained.| +| Promise\> | 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** ```js ethernet.getAllActiveIfaces().then((data) => { - console.log("getAllActiveIfaces promiss data.length = " + data.length); - for (let i = 0; i < data.length; i++) { - console.log("getAllActiveIfaces promiss = " + data[i]); - } -}).catch((error) => { - console.log("getAllActiveIfaces promiss error = " + error); + console.log("getAllActiveIfaces promiss data.length = " + JSON.stringify(data.length)); + for (let i = 0; i < data.length; i++) { + console.log("getAllActiveIfaces promiss = " + JSON.stringify(data[i])); + } +}).catch(error => { + console.log("getAllActiveIfaces promiss error = " + JSON.stringify(error)); }); ``` @@ -277,22 +390,26 @@ ethernet.getAllActiveIfaces().then((data) => { 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 | -| -------- | ------- | --------- | ----------- | -| mode | [IPSetMode](#ipsetmode) | Yes | Configuration mode of the Ethernet connection.| -| 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.| -| 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.| -| 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.| -| 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 (,).| +**System capability**: SystemCapability.Communication.NetManager.Ethernet + +| Name | Type | Mandatory| Description | +| ------------ | ----------------------- | ---|------------------------------------------------------------ | +| mode | [IPSetMode](#ipsetmode) | Yes| Configuration mode of the Ethernet connection.| +| 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, 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.| +| 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 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 | | ------------------------ | ---- | ---------------------- | diff --git a/en/application-dev/reference/apis/js-apis-net-policy.md b/en/application-dev/reference/apis/js-apis-net-policy.md new file mode 100644 index 0000000000000000000000000000000000000000..375ee31e24b9a24d14aae0217f12b8cd78eb57b1 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-net-policy.md @@ -0,0 +1,1558 @@ +# @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 + +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\ | 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\ + +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\ | 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\): 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\ | 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\; + +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\ | 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 + +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\ | 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\; + +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\ | 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\): 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\; + +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\>): 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\> | 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\>; + +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\> | 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\>): 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\> | 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\>; + +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\> | 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\, callback: AsyncCallback\): 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\ | 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\): Promise\; + +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\ | 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 + +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\ | 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\; + +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\ | 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\): 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\ | 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\; + +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\ | 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\): 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\ | 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\; + +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\ | 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 + +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\ | 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\; + +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\ | 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\>): 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\> | 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\>; + +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\> | 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\): 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\; + +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 + +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\ | 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\; + +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\ | 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 + +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\ | 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\; + +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\ | 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 + +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\ | 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\; + +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\ | 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\>): 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\> | 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\>; + +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\> | 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\>): 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\> | 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\>): 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\> | 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\): 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\ | 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.| diff --git a/en/application-dev/reference/apis/js-apis-net-sharing.md b/en/application-dev/reference/apis/js-apis-net-sharing.md index 144ffa9c6e2d405c83e7cf14fdb7278c616759d3..f4682131182b59d9b54c26978ec780cd738172ef 100644 --- a/en/application-dev/reference/apis/js-apis-net-sharing.md +++ b/en/application-dev/reference/apis/js-apis-net-sharing.md @@ -1,8 +1,9 @@ -# @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. -> **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. ## Modules to Import @@ -29,6 +30,15 @@ Checks whether network sharing is supported. This API uses an asynchronous callb | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | 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** ```js @@ -56,6 +66,15 @@ Checks whether network sharing is supported. This API uses a promise to return t | --------------------------------- | ------------------------------------- | | Promise\ | 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** ```js @@ -84,6 +103,14 @@ Checks whether network sharing is in progress. This API uses an asynchronous cal | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | 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** ```js @@ -99,10 +126,10 @@ isSharing(): Promise\ 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. +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + **System capability**: SystemCapability.Communication.NetManager.NetSharing **Return value** @@ -111,6 +138,14 @@ Checks whether network sharing is in progress. This API uses a promise to return | --------------------------------- | ------------------------------------- | | Promise\ | 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** ```js @@ -127,10 +162,10 @@ startSharing(type: SharingIfaceType, callback: AsyncCallback\): void 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. +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + **System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -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.| | callback | AsyncCallback\ | 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** ```js 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)); }); ``` @@ -173,11 +224,27 @@ Starts network sharing of a specified type. This API uses a promise to return th | --------------------------------- | ------------------------------------- | | Promise\ | 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** ```js 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"); }).catch(error => { console.log("start wifi sharing failed"); @@ -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.| | callback | AsyncCallback\ | 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** ```js 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)); }); ``` @@ -236,11 +317,25 @@ Stops network sharing of a specified type. This API uses a promise to return the | --------------------------------- | ------------------------------------- | | Promise\ | 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** ```js 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"); }).catch(error => { console.log("stop wifi sharing failed"); @@ -265,6 +360,14 @@ Obtains the volume of mobile data traffic received via network sharing. This API | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | 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** ```js @@ -292,6 +395,14 @@ Obtains the volume of mobile data traffic received via network sharing. This API | --------------------------------- | ------------------------------------- | | Promise\ | 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** ```js @@ -320,6 +431,14 @@ Obtains the volume of mobile data traffic sent via network sharing. This API use | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | 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** ```js @@ -347,6 +466,14 @@ Obtains the volume of mobile data traffic sent via network sharing. This API use | --------------------------------- | ------------------------------------- | | Promise\ | 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** ```js @@ -375,6 +502,14 @@ Obtains the volume of mobile data traffic sent and received via network sharing. | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | 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** ```js @@ -402,6 +537,14 @@ Obtains the volume of mobile data traffic sent and received via network sharing. | --------------------------------- | ------------------------------------- | | Promise\ | 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** ```js @@ -428,14 +571,25 @@ Obtains the names of NICs in the specified network sharing state. This API uses | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | -| state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| +| state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| | callback | AsyncCallback\> | 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** ```js -import SharingIfaceType from '@ohos.net.sharing' -sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER, (error, data) => { +import SharingIfaceState from '@ohos.net.sharing' +let SHARING_BLUETOOTH=2; +sharing.getSharingIfaces(SHARING_BLUETOOTH, (error, data) => { console.log(JSON.stringify(error)); console.log(JSON.stringify(data)); }); @@ -457,7 +611,7 @@ Obtains the names of NICs in the specified network sharing state. This API uses | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | -| state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| +| state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| **Return value** @@ -465,11 +619,22 @@ Obtains the names of NICs in the specified network sharing state. This API uses | --------------------------------- | ------------------------------------- | | Promise\> | 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** ```js 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)); }).catch(error => { console.log(JSON.stringify(error)); @@ -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.| | 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** ```js -import SharingIfaceState from '@ohos.net.sharing' -sharing.getSharingState(SharingIfaceType.SHARING_WIFI, (error, data) => { +import SharingIfaceType from '@ohos.net.sharing' +let SHARING_WIFI=0; +sharing.getSharingState(SHARING_WIFI, (error, data) => { console.log(JSON.stringify(error)); console.log(JSON.stringify(data)); }); @@ -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.| +**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** | Type | Description | @@ -533,7 +719,8 @@ Obtains the network sharing state of the specified type. This API uses a promise ```js 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)); }).catch(error => { console.log(JSON.stringify(error)); @@ -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.| | callback | AsyncCallback\> | 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** ```js 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(data)); }); @@ -593,11 +791,22 @@ Obtains regular expressions of NICs of a specified type. This API uses a promise | --------------------------------- | ------------------------------------- | | Promise\> | 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** ```js 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)); }).catch(error => { console.log(JSON.stringify(error)); @@ -621,14 +830,20 @@ Subscribes to network sharing state changes. This API uses an asynchronous callb | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | | type | string | Yes | Event name.| -| callback | AsyncCallback\ | Yes | Callback used to return the network sharing state.| +| callback | AsyncCallback\ | Yes | Callback invoked when the network sharing state changes.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | **Example** ```js -sharing.on('sharingStateChange', (error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + sharing.on('sharingStateChange', (data) => { + console.log('on sharingStateChange: ' + JSON.stringify(data)); }); ``` @@ -649,13 +864,19 @@ Unsubscribes from network sharing state changes. This API uses an asynchronous c | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | | type | string | Yes | Event name.| -| callback | AsyncCallback\ | No | Callback used for unsubscription.| +| callback | AsyncCallback\ | No | Callback invoked when the network sharing state changes.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | **Example** ```js -sharing.off('sharingStateChange', (error, data) => { - console.log(JSON.stringify(error)); +sharing.off('sharingStateChange', (data) => { console.log(JSON.stringify(data)); }); ``` @@ -679,12 +900,18 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an | 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.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | + **Example** ```js -sharing.on('interfaceSharingStateChange', (error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + sharing.on('interfaceSharingStateChange', (data) => { + console.log('on interfaceSharingStateChange: ' + JSON.stringify(data)); }); ``` @@ -705,13 +932,19 @@ Unsubscribes from network sharing status changes of a specified NIC. This API us | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | | 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** ```js -sharing.off('interfaceSharingStateChange', (error, data) => { - console.log(JSON.stringify(error)); +sharing.off('interfaceSharingStateChange', (data) => { console.log(JSON.stringify(data)); }); ``` @@ -735,12 +968,18 @@ Subscribes to upstream network changes. This API uses an asynchronous callback t | type | string | Yes | Event name.| | callback | AsyncCallback\ | Yes | Callback invoked when the upstream network changes.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | + **Example** ```js -sharing.on('sharingUpstreamChange', (error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + sharing.on('sharingUpstreamChange', (data) => { + console.log('on sharingUpstreamChange: ' + JSON.stringify(data)); }); ``` @@ -761,13 +1000,19 @@ Unsubscribes from upstream network changes. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | | type | string | Yes | Event name.| -| callback | AsyncCallback\ | No | Callback used for unsubscription.| +| callback | AsyncCallback\ | No | Callback used for unsubscription from upstream network changes.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | **Example** ```js -sharing.off('sharingUpstreamChange', (error, data) => { - console.log(JSON.stringify(error)); +sharing.off('sharingUpstreamChange', (data) => { console.log(JSON.stringify(data)); }); ``` @@ -788,7 +1033,7 @@ Enumerates the network sharing states of an NIC. ## SharingIfaceType -Enumerates the network sharing types of an NIC. +Enumerates the network sharing types of an NIC. **System API**: This is a system API. @@ -797,5 +1042,5 @@ Enumerates the network sharing types of an NIC. | Name | Value | Description | | ------------------------ | ---- | ---------------------- | | 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.| diff --git a/en/application-dev/reference/apis/js-apis-pointer.md b/en/application-dev/reference/apis/js-apis-pointer.md index 3a31a8179560f622bcf62e7d3c3640a72436beb5..49ed81e115de6345453c93441b68cda2a132021b 100644 --- a/en/application-dev/reference/apis/js-apis-pointer.md +++ b/en/application-dev/reference/apis/js-apis-pointer.md @@ -2,7 +2,8 @@ The **pointer** module provides APIs related to pointer attribute management. -> **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. ## Modules to Import @@ -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 API**: This is a system API. + **Return value** | Name | Description | @@ -263,8 +266,6 @@ Obtains the mouse pointer style. This API uses an asynchronous callback to retur **System capability**: SystemCapability.MultimodalInput.Input.Pointer -**System API**: This is a system API. - **Parameters** | Name | Type | Mandatory | Description | @@ -277,21 +278,23 @@ Obtains the mouse pointer style. This API uses an asynchronous callback to retur ```js import window from '@ohos.window'; -window.getTopWindow((error, win) => { - win.getProperties((error, properties) => { - let windowId = properties.id; - if (windowId < 0) { - console.log(`Invalid windowId`); - return; - } - try { - pointer.getPointerStyle(windowId, (error, style) => { - console.log(`Get pointer style success, style: ${JSON.stringify(style)}`); - }); - } catch (error) { - console.log(`Get pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); - } - }); +window.getLastWindow(this.context, (error, win) => { + if (error.code) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error)); + return; + } + let windowId = win.getWindowProperties().id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + pointer.getPointerStyle(windowId, (error, style) => { + 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. ```js import window from '@ohos.window'; -window.getTopWindow((error, win) => { - win.getProperties((error, properties) => { - let windowId = properties.id; - if (windowId < 0) { - console.log(`Invalid windowId`); - return; - } - try { - pointer.getPointerStyle(windowId).then((style) => { - console.log(`Get pointer style success, style: ${JSON.stringify(style)}`); - }); - } catch (error) { - console.log(`Get pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); - } - }); +window.getLastWindow(this.context, (error, win) => { + if (error.code) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error)); + return; + } + let windowId = win.getWindowProperties().id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + pointer.getPointerStyle(windowId).then((style) => { + 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 ```js import window from '@ohos.window'; -window.getTopWindow((error, win) => { - win.getProperties((error, properties) => { - let windowId = properties.id; - if (windowId < 0) { - console.log(`Invalid windowId`); - return; - } - try { - pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS, error => { - console.log(`Set pointer style success`); - }); - } catch (error) { - console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); - } - }); +window.getLastWindow(this.context, (error, win) => { + if (error.code) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error)); + return; + } + let windowId = win.getWindowProperties().id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS, error => { + console.log(`Set pointer style success`); + }); + } catch (error) { + console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + } }); ``` ## pointer.setPointerStyle9+ @@ -397,21 +404,23 @@ Sets the mouse pointer style. This API uses a promise to return the result. ```js import window from '@ohos.window'; -window.getTopWindow((error, win) => { - win.getProperties((error, properties) => { - let windowId = properties.id; - if (windowId < 0) { - console.log(`Invalid windowId`); - return; - } - try { - pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS).then(() => { - console.log(`Set pointer style success`); - }); - } catch (error) { - console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); - } - }); +window.getLastWindow(this.context, (error, win) => { + if (error.code) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error)); + return; + } + let windowId = win.getWindowProperties().id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS).then(() => { + console.log(`Set pointer style success`); + }); + } catch (error) { + console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + } }); ``` ## PointerStyle9+ @@ -444,8 +453,8 @@ Enumerates mouse pointer styles. | HAND_POINTING | 19 | Hand-shaped pointer |![Hand_Poniting.png](./figures/Hand_Pointing.png)| | HELP | 20 | Help |![Help.png](./figures/Help.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_UP_DOWN | 23 | Up-and-down resizing|![Resize_Up_Down.png](./figures/Resize_Up_Down.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)| | SCREENSHOT_CHOOSE | 24 | Screenshot crosshair|![Screenshot_Cross.png](./figures/Screenshot_Cross.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)| diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md index 54cf7cc816d7def45a86a450765c5b23b9ef2a06..9f259f378ac523284d4aa17bce9742ec9b812636 100644 --- a/en/application-dev/reference/apis/js-apis-resource-manager.md +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -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). ```ts -import Ability from '@ohos.application.Ability'; -class MainAbility extends Ability { +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { let context = this.context; let resourceManager = context.resourceManager; diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index bd14137464ce195f5c61b9d6a53ce6ef79cd3f10..f099ece8f25d5fcb6ba4f5c753d55fa2a4f83717 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -1,8 +1,7 @@ -# @ohos.net.socket (Socket Connection) +# # @ohos.net.socket (Socket Connection) -The **socket** module implements socket connection management and operation. - -> **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. ## Modules to Import @@ -13,7 +12,7 @@ import socket from '@ohos.net.socket'; ## socket.constructUDPSocketInstance -constructUDPSocketInstance\(\): UDPSocket +constructUDPSocketInstance(): UDPSocket Creates a **UDPSocket** object. @@ -22,7 +21,7 @@ Creates a **UDPSocket** object. **Return value** | Type | Description | -| --------------------------------- | ---------------------- | +| :--------------------------------- | :---------------------- | | [UDPSocket](#udpsocket) | **UDPSocket** object.| @@ -39,7 +38,7 @@ Defines a **UDPSocket** connection. Before invoking UDPSocket APIs, you need to ### bind -bind\(address: NetAddress, callback: AsyncCallback\): void +bind(address: NetAddress, callback: AsyncCallback\): 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. @@ -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).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -70,7 +76,7 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ### bind -bind\(address: NetAddress\): Promise +bind(address: NetAddress): Promise\ 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 | ------- | ---------------------------------- | ---- | ------------------------------------------------------ | | address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | **Return value** | Type | Description | -| -------------- | ----------------------------------------- | +| :-------------- | :----------------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -106,7 +118,7 @@ promise .then(() => { ### send -send\(options: UDPSendOptions, callback: AsyncCallback\): void +send(options: UDPSendOptions, callback: AsyncCallback\): void 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 | options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -146,7 +165,7 @@ udp.send({ ### send -send\(options: UDPSendOptions\): Promise +send(options: UDPSendOptions): Promise\ 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 | ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | | 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** | Type | Description | -| -------------- | --------------------------------------------- | +| :-------------- | :--------------------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -190,7 +216,7 @@ promise.then(() => { ### close -close\(callback: AsyncCallback\): void +close(callback: AsyncCallback\): void Closes a UDPSocket connection. This API uses an asynchronous callback to return the result. @@ -220,7 +246,7 @@ udp.close(err => { ### close -close\(\): Promise +close(): Promise\ 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** | Type | Description | -| -------------- | ----------------------------------------- | +| :-------------- | :----------------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -249,12 +275,12 @@ promise.then(() => { ### getState -getState\(callback: AsyncCallback\): void +getState(callback: AsyncCallback\): void Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
->This API can be called only after [bind](#bind) is successfully called. +>**NOTE** +>This API can be called only after **bind** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -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.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | + **Example** ```js @@ -289,12 +321,12 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ### getState -getState\(\): Promise +getState(): Promise\ Obtains the status of the UDPSocket connection. This API uses a promise to return the result. ->**NOTE**
->This API can be called only after [bind](#bind) is successfully called. +>**NOTE** +>This API can be called only after **bind** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -303,8 +335,8 @@ Obtains the status of the UDPSocket connection. This API uses a promise to retur **Return value** | Type | Description | -| ----------------------------------------------- | ----------------------------------------- | -| Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.| +| :----------------------------------------------- | :----------------------------------------- | +| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result.| **Example** @@ -328,12 +360,12 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ### setExtraOptions -setExtraOptions\(options: UDPExtraOptions, callback: AsyncCallback\): void +setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\): 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**
->This API can be called only after [bind](#bind) is successfully called. +>**NOTE** +>This API can be called only after **bind** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -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).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | **Example** @@ -376,12 +414,12 @@ udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> { ### setExtraOptions -setExtraOptions\(options: UDPExtraOptions\): Promise +setExtraOptions(options: UDPExtraOptions): Promise\ -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**
->This API can be called only after [bind](#bind) is successfully called. +>**NOTE** +>This API can be called only after **bind** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -396,9 +434,16 @@ Sets other properties of the UDPSocket connection. This API uses a promise to re **Return value** | Type | Description | -| -------------- | --------------------------------------------------- | +| :-------------- | :--------------------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -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. @@ -437,7 +482,7 @@ Enables listening for message receiving events of the UDPSocket connection. This | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | | type | string | Yes | Type of the event to subscribe to.
**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** @@ -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. ->**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. **System capability**: SystemCapability.Communication.NetStack @@ -475,15 +520,15 @@ let callback = value =>{ console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); } 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'); ``` -### on\('listening' | 'close'\) +### on('listening' | 'close') -on\(type: 'listening' | 'close', callback: Callback\): void +on(type: 'listening' | 'close', callback: Callback\): 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. @@ -509,13 +554,13 @@ udp.on('close', () => { ``` -### off\('listening' | 'close'\) +### off('listening' | 'close') -off\(type: 'listening' | 'close', callback?: Callback\): void +off(type: 'listening' | 'close', callback?: Callback\): 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. ->**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. **System capability**: SystemCapability.Communication.NetStack @@ -535,22 +580,22 @@ let callback1 = () =>{ console.log("on listening, success"); } 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'); let callback2 = () =>{ console.log("on close, success"); } 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'); ``` -### 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. @@ -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.
**error**: error event| | callback | ErrorCallback | Yes | Callback used to return the result. | - **Example** ```js @@ -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. ->**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. **System capability**: SystemCapability.Communication.NetStack @@ -600,7 +644,7 @@ let callback = err =>{ console.log("on error, err:" + JSON.stringify(err)); } 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'); ``` @@ -668,9 +712,15 @@ Defines information about the socket connection. | port | number | Yes | Port number. The value ranges from **0** to **65535**. | | 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 -constructTCPSocketInstance\(\): TCPSocket +constructTCPSocketInstance(): TCPSocket Creates a **TCPSocket** object. @@ -679,7 +729,7 @@ Creates a **TCPSocket** object. **Return value** | Type | Description | - | --------------------------------- | ---------------------- | + | :--------------------------------- | :---------------------- | | [TCPSocket](#tcpsocket) | **TCPSocket** object.| **Example** @@ -695,7 +745,7 @@ Defines a TCPSocket connection. Before invoking TCPSocket APIs, you need to call ### bind -bind\(address: NetAddress, callback: AsyncCallback\): void +bind(address: NetAddress, callback: AsyncCallback\): 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. @@ -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).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | **Example** @@ -727,7 +783,7 @@ tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ### bind -bind\(address: NetAddress\): Promise +bind(address: NetAddress): Promise\ 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 **Return value** | Type | Description | -| -------------- | ------------------------------------------------------- | +| :-------------- | :------------------------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -762,10 +825,13 @@ promise.then(() => { ### connect -connect\(options: TCPConnectOptions, callback: AsyncCallback\): void +connect(options: TCPConnectOptions, callback: AsyncCallback\): void 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 **System capability**: SystemCapability.Communication.NetStack @@ -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).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -793,7 +866,7 @@ tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , time ### connect -connect\(options: TCPConnectOptions\): Promise +connect(options: TCPConnectOptions): Promise\ 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 **Return value** | Type | Description | -| -------------- | --------------------------------------------------------- | +| :-------------- | :--------------------------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -828,12 +908,12 @@ promise.then(() => { ### send -send\(options: TCPSendOptions, callback: AsyncCallback\): void +send(options: TCPSendOptions, callback: AsyncCallback\): void Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
->This API can be called only after [connect](#connect) is successfully called. +>**NOTE** +>This API can be called only after **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -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).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -870,12 +957,12 @@ promise.then(() => { ### send -send\(options: TCPSendOptions\): Promise +send(options: TCPSendOptions): Promise\ Sends data over a TCPSocket connection. This API uses a promise to return the result. ->**NOTE**
->This API can be called only after [connect](#connect) is successfully called. +>**NOTE** +>This API can be called only after **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -890,9 +977,16 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re **Return value** | Type | Description | -| -------------- | ------------------------------------------------- | +| :-------------- | :------------------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -916,7 +1010,7 @@ promise1.then(() => { ### close -close\(callback: AsyncCallback\): void +close(callback: AsyncCallback\): void 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 | -------- | --------------------- | ---- | ---------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | **Example** @@ -947,7 +1046,7 @@ tcp.close(err => { ### close -close\(\): Promise +close(): Promise\ 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** | Type | Description | -| -------------- | ----------------------------------------- | +| :-------------- | :----------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | + **Example** ```js @@ -976,12 +1081,12 @@ promise.then(() => { ### getRemoteAddress -getRemoteAddress\(callback: AsyncCallback\): void +getRemoteAddress(callback: AsyncCallback\): void Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
->This API can be called only after [connect](#connect) is successfully called. +>**NOTE** +>This API can be called only after **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -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.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | + **Example** ```js @@ -1015,12 +1126,12 @@ promise.then(() => { ### getRemoteAddress -getRemoteAddress\(\): Promise +getRemoteAddress(): Promise\ Obtains the remote address of a socket connection. This API uses a promise to return the result. ->**NOTE**
->This API can be called only after [connect](#connect) is successfully called. +>**NOTE** +>This API can be called only after **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1029,9 +1140,15 @@ Obtains the remote address of a socket connection. This API uses a promise to re **Return value** | Type | Description | -| ------------------------------------------ | ------------------------------------------ | +| :------------------------------------------ | :------------------------------------------ | | Promise<[NetAddress](#netaddress)> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | + **Example** ```js @@ -1053,12 +1170,12 @@ promise1.then(() => { ### getState -getState\(callback: AsyncCallback\): void +getState(callback: AsyncCallback\): void Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
->This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. +>**NOTE** +>This API can be called only after **bind** or **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -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.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | **Example** @@ -1093,12 +1215,12 @@ promise.then(() => { ### getState -getState\(\): Promise +getState(): Promise\ Obtains the status of the TCPSocket connection. This API uses a promise to return the result. ->**NOTE**
->This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. +>**NOTE** +>This API can be called only after **bind** or **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1107,9 +1229,14 @@ Obtains the status of the TCPSocket connection. This API uses a promise to retur **Return value** | Type | Description | -| ----------------------------------------------- | ----------------------------------------- | +| :----------------------------------------------- | :----------------------------------------- | | Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | **Example** @@ -1132,12 +1259,12 @@ promise.then(() => { ### setExtraOptions -setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback\): void +setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\): void Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
->This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. +>**NOTE** +>This API can be called only after **bind** or **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -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).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -1181,12 +1315,12 @@ promise.then(() => { ### setExtraOptions -setExtraOptions\(options: TCPExtraOptions\): Promise +setExtraOptions(options: TCPExtraOptions): Promise\ Sets other properties of the TCPSocket connection. This API uses a promise to return the result. ->**NOTE**
->This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. +>**NOTE** +>This API can be called only after **bind** or **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1201,9 +1335,15 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re **Return value** | Type | Description | -| -------------- | --------------------------------------------------- | +| :-------------- | :--------------------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | **Example** @@ -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. @@ -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. ->**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. **System capability**: SystemCapability.Communication.NetStack @@ -1284,15 +1424,15 @@ let callback = value =>{ console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); } 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'); ``` -### on\('connect' | 'close'\) +### on('connect' | 'close') -on\(type: 'connect' | 'close', callback: Callback\): void +on(type: 'connect' | 'close', callback: Callback\): void 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 | type | string | Yes | Type of the event to subscribe to.

- **connect**: connection event
- **close**: close event| | callback | Callback\ | Yes | Callback used to return the result. | - **Example** ```js @@ -1319,13 +1458,13 @@ tcp.on('close', data => { ``` -### off\('connect' | 'close'\) +### off('connect' | 'close') -off\(type: 'connect' | 'close', callback?: Callback\): void +off(type: 'connect' | 'close', callback?: Callback\): void Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**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. **System capability**: SystemCapability.Communication.NetStack @@ -1345,22 +1484,22 @@ let callback1 = () =>{ console.log("on connect success"); } 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'); let callback2 = () =>{ console.log("on close success"); } 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'); ``` -### 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. @@ -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. ->**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. **System capability**: SystemCapability.Communication.NetStack @@ -1409,7 +1548,7 @@ let callback = err =>{ console.log("on error, err:" + JSON.stringify(err)); } 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'); ``` @@ -1452,7 +1591,13 @@ Defines other properties of the TCPSocket connection. | receiveBufferSize | number | No | Size of the receive 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**. | -| 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.constructTLSSocketInstance9+ @@ -1465,7 +1610,7 @@ Creates a **TLSSocket** object. **Return value** | Type | Description | -| --------------------------------- | ---------------------- | +| :--------------------------------- | :---------------------- | | [TLSSocket](#tlssocket9) | **TLSSocket** object.| **Example** @@ -1480,7 +1625,7 @@ Defines a TLSSocket connection. Before invoking TLSSocket APIs, you need to call ### bind9+ -bind\(address: NetAddress, callback: AsyncCallback\): void +bind(address: NetAddress, callback: AsyncCallback\): void 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 => { ### bind9+ -bind\(address: NetAddress\): Promise +bind(address: NetAddress): Promise\ 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 **Return value** | Type | Description | -| -------------- | ------------------------------------------------------- | +| :-------------- | :------------------------------------------------------- | | Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -1560,7 +1705,7 @@ promise.then(() => { ### getState9+ -getState\(callback: AsyncCallback\): void +getState(callback: AsyncCallback\): void 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) => { ### getState9+ -getState\(\): Promise +getState(): Promise\ 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 **Return value** | Type | Description | -| ----------------------------------------------- | ----------------------------------------- | +| :----------------------------------------------- | :----------------------------------------- | | Promise\<[SocketStateBase](#socketstatebase)> | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -1639,7 +1784,7 @@ promise.then(() => { ### setExtraOptions9+ -setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback\): void +setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\): 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. @@ -1691,7 +1836,7 @@ tls.setExtraOptions({ ### setExtraOptions9+ -setExtraOptions\(options: TCPExtraOptions\): Promise +setExtraOptions(options: TCPExtraOptions): Promise\ 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 **Return value** | Type | Description | -| -------------- | --------------------------------------------------- | +| :-------------- | :--------------------------------------------------- | | Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -1746,7 +1891,7 @@ promise.then(() => { ### connect9+ -connect(options: TLSConnectOptions, callback: AsyncCallback\): void +connect(options: TLSConnectOptions, callback: AsyncCallback\): 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. @@ -1767,7 +1912,6 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after | 2303104 | Interrupted system call. | | 2303109 | Bad file number. | | 2303111 | Resource temporarily unavailable try again. | -| 2303113 | System permission denied. | | 2303188 | Socket operation on non-socket. | | 2303191 | Protocol wrong type for socket. | | 2303198 | Address already in use. | @@ -1784,7 +1928,7 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after ```js 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) { console.log('bind fail'); return; @@ -1795,14 +1939,14 @@ let options = { ALPNProtocols: ["spdy/1", "http/1.1"], address: { address: "192.168.xx.xxx", - port: xxxx, + port: 8080, family: 1, }, secureOptions: { key: "xxxx", cert: "xxxx", ca: ["xxxx"], - passwd: "xxxx", + password: "xxxx", protocols: [socket.Protocol.TLSv12], useRemoteCipherPrefer: true, signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", @@ -1810,12 +1954,12 @@ let options = { }, }; tlsTwoWay.connect(options, (err, data) => { - console.error(err); - console.log(data); + console.error("connect callback error"+err); + console.log(JSON.stringify(data)); }); 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) { console.log('bind fail'); return; @@ -1825,7 +1969,7 @@ tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { let oneWayOptions = { address: { address: "192.168.xxx.xxx", - port: xxxx, + port: 8080, family: 1, }, secureOptions: { @@ -1834,14 +1978,14 @@ let oneWayOptions = { }, }; tlsOneWay.connect(oneWayOptions, (err, data) => { - console.error(err); - console.log(data); + console.error("connect callback error"+err); + console.log(JSON.stringify(data)); }); ``` ### connect9+ -connect(options: TLSConnectOptions): Promise\ +connect(options: TLSConnectOptions): Promise\ 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 | Type | Description | | ------------------------------------------- | ----------------------------- | -| Promise\ | 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\ | 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** @@ -1867,7 +2011,6 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after | 2303104 | Interrupted system call. | | 2303109 | Bad file number. | | 2303111 | Resource temporarily unavailable try again. | -| 2303113 | System permission denied. | | 2303188 | Socket operation on non-socket. | | 2303191 | Protocol wrong type for socket. | | 2303198 | Address already in use. | @@ -1884,7 +2027,7 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after ```js 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) { console.log('bind fail'); return; @@ -1895,14 +2038,14 @@ let options = { ALPNProtocols: ["spdy/1", "http/1.1"], address: { address: "xxxx", - port: xxxx, + port: 8080, family: 1, }, secureOptions: { key: "xxxx", cert: "xxxx", ca: ["xxxx"], - passwd: "xxxx", + password: "xxxx", protocols: [socket.Protocol.TLSv12], useRemoteCipherPrefer: true, signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", @@ -1910,13 +2053,13 @@ let options = { }, }; tlsTwoWay.connect(options).then(data => { - console.log(data); + console.log(JSON.stringify(data)); }).catch(err => { console.error(err); }); 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) { console.log('bind fail'); return; @@ -1926,7 +2069,7 @@ tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { let oneWayOptions = { address: { address: "192.168.xxx.xxx", - port: xxxx, + port: 8080, family: 1, }, secureOptions: { @@ -1935,7 +2078,7 @@ let oneWayOptions = { }, }; tlsOneWay.connect(oneWayOptions).then(data => { - console.log(data); + console.log(JSON.stringify(data)); }).catch(err => { console.error(err); }); @@ -1943,7 +2086,7 @@ tlsOneWay.connect(oneWayOptions).then(data => { ### getRemoteAddress9+ -getRemoteAddress\(callback: AsyncCallback\): void +getRemoteAddress(callback: AsyncCallback\): void 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 | 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** @@ -1976,7 +2119,7 @@ tls.getRemoteAddress((err, data) => { ### getRemoteAddress9+ -getRemoteAddress\(\): Promise\ +getRemoteAddress(): Promise\ 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 **Return value** | Type | Description | -| ------------------------------------------ | ------------------------------------------ | +| :------------------------------------------ | :------------------------------------------ | | Promise\<[NetAddress](#netaddress)> | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2008,7 +2151,7 @@ promise.then(() => { ### getCertificate9+ -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. @@ -2018,7 +2161,7 @@ Obtains the local digital certificate after a TLSSocket connection is establishe | 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** @@ -2042,7 +2185,7 @@ tls.getCertificate((err, data) => { ### getCertificate9+ -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. @@ -2050,9 +2193,9 @@ Obtains the local digital certificate after a TLSSocket connection is establishe **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** @@ -2074,7 +2217,7 @@ tls.getCertificate().then(data => { ### getRemoteCertificate9+ -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. @@ -2084,7 +2227,7 @@ Obtains the digital certificate of the server after a TLSSocket connection is es | 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** @@ -2107,7 +2250,7 @@ tls.getRemoteCertificate((err, data) => { ### getRemoteCertificate9+ -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. @@ -2117,7 +2260,7 @@ Obtains the digital certificate of the server after a TLSSocket connection is es | 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** @@ -2138,7 +2281,7 @@ tls.getRemoteCertificate().then(data => { ### getProtocol9+ -getProtocol(callback: AsyncCallback\): void +getProtocol(callback: AsyncCallback\): void 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 | Name | Type | Mandatory| Description | | -------- | ----------------------------------------| ---- | ---------------| -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2172,7 +2315,7 @@ tls.getProtocol((err, data) => { ### getProtocol9+ -getProtocol():Promise\ +getProtocol():Promise\ 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 | Type | Description | | -------------- | -------------------- | -| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2204,7 +2347,7 @@ tls.getProtocol().then(data => { ### getCipherSuite9+ -getCipherSuite(callback: AsyncCallback\>): void +getCipherSuite(callback: AsyncCallback\\>): 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. @@ -2214,7 +2357,7 @@ Obtains the cipher suite negotiated by both communication parties after a TLSSoc | Name | Type | Mandatory| Description| | -------- | ----------------------------------------| ---- | ---------------| -| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| +| callback | AsyncCallback\\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2239,7 +2382,7 @@ tls.getCipherSuite((err, data) => { ### getCipherSuite9+ -getCipherSuite(): Promise\> +getCipherSuite(): Promise\\> 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 | Type | Description | | ---------------------- | --------------------- | -| Promise\> | Promise used to return the result. If the operation fails, an error message is returned.| +| Promise\\> | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2264,7 +2407,7 @@ Obtains the cipher suite negotiated by both communication parties after a TLSSoc ```js tls.getCipherSuite().then(data => { - console.log(data); + console.log('getCipherSuite success:' + JSON.stringify(data)); }).catch(err => { console.error(err); }); @@ -2272,7 +2415,7 @@ tls.getCipherSuite().then(data => { ### getSignatureAlgorithms9+ -getSignatureAlgorithms(callback: AsyncCallback\>): void +getSignatureAlgorithms(callback: AsyncCallback\\>): 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. @@ -2282,7 +2425,7 @@ Obtains the signing algorithm negotiated by both communication parties after a T | Name | Type | Mandatory| Description | | -------- | -------------------------------------| ---- | ---------------| -| callback | AsyncCallback\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\\> | Yes | Callback used to return the result. | **Error codes** @@ -2305,7 +2448,7 @@ tls.getSignatureAlgorithms((err, data) => { ### getSignatureAlgorithms9+ -getSignatureAlgorithms(): Promise\> +getSignatureAlgorithms(): Promise\\> 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 | Type | Description | | ---------------------- | -------------------- | -| Promise\> | Promise used to return the result.| +| Promise\\> | Promise used to return the result.| **Error codes** @@ -2328,7 +2471,7 @@ Obtains the signing algorithm negotiated by both communication parties after a T ```js tls.getSignatureAlgorithms().then(data => { - console.log(data); + console.log("getSignatureAlgorithms success" + data); }).catch(err => { console.error(err); }); @@ -2336,7 +2479,7 @@ tls.getSignatureAlgorithms().then(data => { ### send9+ -send(data: string, callback: AsyncCallback\): void +send(data: string, callback: AsyncCallback\): void 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 | Name | Type | Mandatory| Description | | -------- | -----------------------------| ---- | ---------------| | data | string | Yes | Data content of the message to send. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2374,7 +2517,7 @@ tls.send("xxxx", (err) => { ### send9+ -send(data: string): Promise\ +send(data: string): Promise\ 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 | Type | Description | | -------------- | -------------------- | -| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| **Example** @@ -2415,7 +2558,7 @@ tls.send("xxxx").then(() =>{ ### close9+ -close(callback: AsyncCallback\): void +close(callback: AsyncCallback\): void 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 | Name | Type | Mandatory| Description | | -------- | -----------------------------| ---- | ---------------| -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2450,7 +2593,7 @@ tls.close((err) => { ### close9+ -close(): Promise\ +close(): Promise\ 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 | | -------------- | -------------------- | -| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2491,7 +2634,7 @@ Defines TLS connection options. | -------------- | ------------------------------------- | --- |-------------- | | address | [NetAddress](#netaddress) | Yes | Gateway address. | | secureOptions | [TLSSecureOptions](#tlssecureoptions9) | Yes| TLS security options.| -| ALPNProtocols | Array\ | Yes| Application Layer Protocol Negotiation (ALPN) protocols. | +| ALPNProtocols | Array\ | No| Application Layer Protocol Negotiation (ALPN) protocols. | ## TLSSecureOptions9+ @@ -2501,11 +2644,11 @@ Defines TLS security options. The CA certificate is mandatory, and other paramet | Name | Type | Mandatory| Description | | --------------------- | ------------------------------------------------------ | --- |----------------------------------- | -| ca | string \| Array\ | Yes| CA certificate of the server, which is used to authenticate the digital certificate of the server.| +| ca | string \| Array\ | 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. | | key | string | No| Private key of the local digital certificate. | -| passwd | string | No| Password for reading the private key. | -| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)> | No| TLS protocol version. | +| password | string | No| Password for reading the private key. | +| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)\> | No| TLS protocol version. | | useRemoteCipherPrefer | boolean | No| Whether to use the remote cipher suite preferentially. | | signatureAlgorithms | string | No| Signing algorithm used during communication. | | cipherSuite | string | No| Cipher suite used during communication. | diff --git a/en/application-dev/reference/apis/js-apis-system-fetch.md b/en/application-dev/reference/apis/js-apis-system-fetch.md index 9493227bde6cd57366fc254bcbbf93216271b958..6144d903c19116e693841e5f4a55840aac43e68b 100644 --- a/en/application-dev/reference/apis/js-apis-system-fetch.md +++ b/en/application-dev/reference/apis/js-apis-system-fetch.md @@ -1,9 +1,8 @@ # @system.fetch (Data Request) > **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 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'; ``` -## fetch.fetch +## fetch.fetch3+ fetch(Object): void @@ -31,9 +30,9 @@ Obtains data through a network. | 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**.| | 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). | -| fail | Function | No| Called when the data failed to be obtained.| -| complete | Function | No| Called when the execution is complete.| +| success | Function | No| Called when the API call is successful. The return value is defined by [FetchResponse](#fetchresponse).| +| fail | Function | No| Called when API call has failed.| +| complete | Function | No| Called when the API call is complete.| **Table 1** Mapping between data and Content-Type @@ -46,11 +45,11 @@ Obtains data through a network. ## FetchResponse -| Name| Type| Description| -| -------- | -------- | -------- | -| code | number | 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.| -| headers | Object | All headers in the response from the server.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| code | number | Yes| No| Server status code.| +| 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 | Yes| No| All headers in the response from the server.| **Table 2** Mapping between responseType and data in success callback @@ -85,8 +84,8 @@ export default { ``` -> **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: +> **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: > > ``` > { diff --git a/en/application-dev/reference/apis/js-apis-system-network.md b/en/application-dev/reference/apis/js-apis-system-network.md index 5fd92bf9e2e58c360ffcd6d6f27408281a53b22a..5fe6e782edc352c4d49377b4e8d9a4343d8435a6 100644 --- a/en/application-dev/reference/apis/js-apis-system-network.md +++ b/en/application-dev/reference/apis/js-apis-system-network.md @@ -1,8 +1,8 @@ -# Network State +# @system.network (Network State) -> **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. -> +> **NOTE** +> - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.telephony.observer`](js-apis-observer.md). +> > - The 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. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| success | Function | No | Called when the execution is successful. The return value is [FetchResponse](#fetchresponse). | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| success | Function | No| Called when the API call is successful. The return value is defined by [NetworkResponse](#networkresponse).| +| fail | Function | No| Called when API call has failed.| +| 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** @@ -71,17 +71,17 @@ Listens to the network connection state. If this method is called multiple times **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). | -| fail | Function | No | Called when the multimedia volume fails to be obtained. | +| success | Function | No| Called when the network state changes. The return value is defined by [NetworkResponse](#networkresponse).| +| 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. | -| 200 | The subscription fails. | +| 602 | The current permission is not declared.| +| 200 | Subscription failed.| **Example** @@ -122,7 +122,9 @@ export default { ## NetworkResponse -| Name | Type | Description | -| -------- | -------- | -------- | -| metered | boolean | Whether the billing is based on the data volume. | -| type | string | Network type. The value can be **2G**, **3G**, **4G**, **5G**, **WiFi**, or **none**. | \ No newline at end of file +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| metered | boolean | No|Whether to charge by traffic.| +| type | string | Yes|Network type. The value can be **2G**, **3G**, **4G**, **5G**, **WiFi**, or **none**.| diff --git a/en/application-dev/reference/apis/js-apis-update.md b/en/application-dev/reference/apis/js-apis-update.md index ffb07ba4f21cc5f154bcf25062f86845c97577dc..923baae8383344c8b0bb252bd59c67aca26d04bc 100644 --- a/en/application-dev/reference/apis/js-apis-update.md +++ b/en/application-dev/reference/apis/js-apis-update.md @@ -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. > **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 @@ -2034,7 +2036,7 @@ Enumerates update states. | WAITING_INSTALL | 30 | Waiting for installation. | | UPDATING | 31 | Updating. | | WAITING_APPLY | 40 | Waiting for applying the update. | -| APPLYING | 21 | Applying the update. | +| APPLYING | 41 | Applying the update. | | UPGRADE_SUCCESS | 50 | Update succeeded.| | UPGRADE_FAIL | 51 | Update failed.| @@ -2056,7 +2058,7 @@ Enumerates event IDs. | Name | Value | Description | | ---------------------- | ---------- | ------ | -| EVENT_TASK_BASE | 0x01000000 | Task event. | +| EVENT_TASK_BASE | EventClassify.TASK | Task event. | | EVENT_TASK_RECEIVE | 0x01000001 | Task received. | | EVENT_TASK_CANCEL | 0x01000010 | Task cancelled. | | EVENT_DOWNLOAD_WAIT | 0x01000011 | Waiting for download. | diff --git a/en/application-dev/reference/apis/js-apis-usb.md b/en/application-dev/reference/apis/js-apis-usb.md index 52eb0d9543055307184aaf810e79556218b73e89..6ec6637ea6f7695da77e2e28ee9823785a84c20d 100644 --- a/en/application-dev/reference/apis/js-apis-usb.md +++ b/en/application-dev/reference/apis/js-apis-usb.md @@ -1,10 +1,12 @@ -# @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**
+> **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 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 @@ -30,7 +32,7 @@ Obtains the list of USB devices connected to the host. If no device is connected ```js let devicesList = usb.getDevices(); -console.log(`devicesList = ${JSON.stringify(devicesList)}`); +console.log(`devicesList = ${devicesList}`); // devicesList is a list of USB devices. // A simple example of devicesList is provided as follows: [ @@ -87,7 +89,7 @@ console.log(`devicesList = ${JSON.stringify(devicesList)}`); connectDevice(device: USBDevice): Readonly<USBDevicePipe> -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. @@ -119,13 +121,12 @@ For details about the error codes, see [USB Error Codes](../errorcodes/errorcode let devicesList = usb.getDevices(); if (devicesList.length == 0) { console.log(`device list is empty`); - return; } let device = devicesList[0]; usb.requestRight(device.name); let devicepipe = usb.connectDevice(device); -console.log(`devicepipe = ${JSON.stringify(devicepipe)}`); +console.log(`devicepipe = ${devicepipe}`); ``` ## usb.hasRight @@ -134,7 +135,7 @@ hasRight(deviceName: string): boolean 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 @@ -183,7 +184,7 @@ Requests the temporary permission for the application to access a USB device. Th ```js let devicesName="1-1"; 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. ```js let devicesName="1-1"; -if (usb.removeRight(devicesName) { +if usb.removeRight(devicesName) { console.log(`Succeed in removing right`); } ``` @@ -246,7 +247,7 @@ Adds the permission for the application to access a USB device. ```js let devicesName = "1-1"; let bundleName = "com.example.hello"; -if (usb.addRight(bundleName, devicesName) { +if usb.addRight(bundleName, devicesName) { console.log(`Succeed in adding right`); } ``` @@ -455,8 +456,9 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **Example** ```js -usb.controlTransfer(devicepipe, USBControlParams).then((ret) => { - console.log(`controlTransfer = ${JSON.stringify(ret)}`); +let param = new usb.USBControlParams(); +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 // 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. 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 **Example** ```js -let funcs = ACM | ECM; +let funcs = usb.ACM | usb.ECM; let ret = usb.usbFunctionsToString(funcs); ``` @@ -608,7 +610,7 @@ Sets the current USB function list in Device mode. **Example** ```js -let funcs = HDC; +let funcs = usb.HDC; let ret = usb.setCurrentFunctions(funcs); ``` @@ -711,7 +713,12 @@ Sets the role types supported by a specified port, which can be **powerRole** (f **Example** ```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 @@ -722,14 +729,14 @@ Represents the USB endpoint from which data is sent or received. You can obtain | Name | Type | Mandatory |Description | | ------------- | ------------------------------------------- | ------------- |------------- | -| address | number | Yes | Endpoint address. | -| attributes | number | Yes | Endpoint attributes. | -| interval | number | Yes | Endpoint interval. | -| maxPacketSize | number | Yes | Maximum size of data packets on the endpoint. | -| direction | [USBRequestDirection](#usbrequestdirection) | Yes | Endpoint direction. | -| number | number | Yes | Endpoint number. | -| type | number | Yes | Endpoint type. | -| interfaceId | number | Yes | Unique ID of the interface to which the endpoint belongs.| +| address | number | Yes|Endpoint address. | +| attributes | number | Yes|Endpoint attributes. | +| interval | number | Yes|Endpoint interval. | +| maxPacketSize | number | Yes|Maximum size of data packets on the endpoint. | +| direction | [USBRequestDirection](#usbrequestdirection) | Yes|Endpoint direction. | +| number | number | Yes|Endpoint number. | +| type | number | Yes|Endpoint type. | +| interfaceId | number | Yes|Unique ID of the interface to which the endpoint belongs.| ## USBInterface @@ -739,13 +746,13 @@ Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **U | Name | Type | Mandatory |Description | | ---------------- | ---------------------------------------- | ------------- |--------------------- | -| id | number | Yes | Unique ID of the USB interface. | -| protocol | number | Yes | Interface protocol. | -| clazz | number | Yes | Device type. | -| subClass | number | Yes | Device subclass. | -| alternateSetting | number | Yes | Settings for alternating between descriptors of the same USB interface.| -| name | string | Yes | Interface name. | -| endpoints | Array<[USBEndpoint](#usbendpoint)> | Yes | Endpoints that belong to the USB interface. | +| id | number | Yes|Unique ID of the USB interface. | +| protocol | number | Yes|Interface protocol. | +| clazz | number | Yes|Device type. | +| subClass | number | Yes|Device subclass. | +| alternateSetting | number | Yes|Settings for alternating between descriptors of the same USB interface.| +| name | string | Yes|Interface name. | +| endpoints | Array<[USBEndpoint](#usbendpoint)> | Yes|Endpoints that belong to the USB interface. | ## USBConfig @@ -755,13 +762,13 @@ Represents the USB configuration. One [USBDevice](#usbdevice) can contain multip | Name | Type | Mandatory |Description | | -------------- | ------------------------------------------------ | --------------- |--------------- | -| id | number | Yes | Unique ID of the USB configuration. | -| attributes | number | Yes | Configuration attributes. | -| maxPower | number | Yes | Maximum power consumption, in mA. | -| name | string | Yes | Configuration name, which can be left empty. | -| isRemoteWakeup | boolean | Yes | Support for remote wakeup.| -| isSelfPowered | boolean | Yes | Support for independent power supplies.| -| interfaces | Array <[USBInterface](#usbinterface)> | Yes | Supported interface attributes. | +| id | number | Yes|Unique ID of the USB configuration. | +| attributes | number | Yes|Configuration attributes. | +| maxPower | number | Yes|Maximum power consumption, in mA. | +| name | string | Yes|Configuration name, which can be left empty. | +| isRemoteWakeup | boolean | Yes|Support for remote wakeup.| +| isSelfPowered | boolean | Yes| Support for independent power supplies.| +| interfaces | Array <[USBInterface](#usbinterface)> | Yes|Supported interface attributes. | ## USBDevice @@ -771,19 +778,19 @@ Represents the USB device information. | Name | Type | Mandatory |Description | | ---------------- | ------------------------------------ | ---------- |---------- | -| busNum | number | Yes | Bus address. | -| devAddress | number | Yes | Device address. | -| serial | string | Yes | Sequence number. | -| name | string | Yes | Device name. | -| manufacturerName | string | Yes | Device manufacturer. | -| productName | string | Yes | Product name. | -| version | string | Yes | Version number. | -| vendorId | number | Yes | Vendor ID. | -| productId | number | Yes | Product ID. | -| clazz | number | Yes | Device class. | -| subClass | number | Yes | Device subclass. | -| protocol | number | Yes | Device protocol code. | -| configs | Array<[USBConfig](#usbconfig)> | Yes | Device configuration descriptor information.| +| busNum | number | Yes|Bus address. | +| devAddress | number | Yes|Device address. | +| serial | string | Yes|Sequence number. | +| name | string | Yes|Device name. | +| manufacturerName | string | Yes| Device manufacturer. | +| productName | string | Yes|Product name. | +| version | string | Yes|Version number. | +| vendorId | number | Yes|Vendor ID. | +| productId | number | Yes|Product ID. | +| clazz | number | Yes|Device class. | +| subClass | number | Yes|Device subclass. | +| protocol | number | Yes|Device protocol code. | +| configs | Array<[USBConfig](#usbconfig)> | Yes|Device configuration descriptor information.| ## USBDevicePipe @@ -804,12 +811,12 @@ Represents control transfer parameters. | Name | Type | Mandatory |Description | | ------- | ----------------------------------------------- | ---------------- |---------------- | -| request | number | Yes | Request type. | -| target | [USBRequestTargetType](#usbrequesttargettype) | Yes | Request target type. | -| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes | Control request type. | -| value | number | Yes | Request parameter value. | -| index | number | Yes | Index of the request parameter value.| -| data | Uint8Array | Yes | Buffer for writing or reading data. | +| request | number | Yes |Request type. | +| target | [USBRequestTargetType](#usbrequesttargettype) | Yes |Request target type. | +| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes |Control request type. | +| value | number | Yes |Request parameter value. | +| index | number | Yes |Index of the request parameter value.| +| data | Uint8Array | Yes |Buffer for writing or reading data. | ## USBPort @@ -821,9 +828,9 @@ Represents a USB port. | Name | Type | Mandatory |Description | | -------------- | ------------------------------- | ------------------- |------------------------ | -| id | number | Yes | Unique identifier of a USB port. | -| supportedModes | [PortModeType](#portmodetype) | Yes | Numeric mask combination for the supported mode list.| -| status | [USBPortStatus](#usbportstatus) | Yes | USB port role. | +| id | number | Yes |Unique identifier of a USB port. | +| supportedModes | [PortModeType](#portmodetype) | Yes |Numeric mask combination for the supported mode list.| +| status | [USBPortStatus](#usbportstatus) | Yes |USB port role. | ## USBPortStatus @@ -835,9 +842,9 @@ Enumerates USB port roles. | Name | Type| Mandatory |Description | | ---------------- | -------- | ---------------- |---------------------- | -| currentMode | number | Yes | Current USB mode. | -| currentPowerRole | number | Yes | Current power role. | -| currentDataRole | number | Yes | Current data role.| +| currentMode | number | Yes|Current USB mode. | +| currentPowerRole | number | Yes |Current power role. | +| currentDataRole | number | Yes |Current data role.| ## USBRequestTargetType @@ -845,12 +852,12 @@ Enumerates request target types. **System capability**: SystemCapability.USB.USBManager -| Name | Value | Description | -| ---------------------------- | ----- | ----------- | -| USB_REQUEST_TARGET_DEVICE | 0 | Device | -| USB_REQUEST_TARGET_INTERFACE | 1 | Interface | -| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint | -| USB_REQUEST_TARGET_OTHER | 3 | Other | +| Name | Value | Description | +| ---------------------------- | ---- | ------ | +| USB_REQUEST_TARGET_DEVICE | 0 | Device| +| USB_REQUEST_TARGET_INTERFACE | 1 | Interface| +| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint| +| USB_REQUEST_TARGET_OTHER | 3 | Other| ## USBControlRequestType diff --git a/en/application-dev/reference/apis/js-apis-usbManager.md b/en/application-dev/reference/apis/js-apis-usbManager.md index 96da37cd6d35610b2813a7cbd3b6067922364d42..b4dd81002e3cd18ffbbd6ab0af635ccd8d23a6c4 100644 --- a/en/application-dev/reference/apis/js-apis-usbManager.md +++ b/en/application-dev/reference/apis/js-apis-usbManager.md @@ -30,7 +30,7 @@ Obtains the list of USB devices connected to the host. If no device is connected ```js let devicesList = usb.getDevices(); -console.log(`devicesList = ${JSON.stringify(devicesList)}`); +cconsole.log(`devicesList = ${devicesList}`); // devicesList is a list of USB devices. // 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 let devicesList = usb.getDevices(); if (devicesList.length == 0) { console.log(`device list is empty`); - return; } let device = devicesList[0]; usb.requestRight(device.name); let devicepipe = usb.connectDevice(device); -console.log(`devicepipe = ${JSON.stringify(devicepipe)}`); +console.log(`devicepipe = ${devicepipe}`); ``` ## usb.hasRight @@ -155,7 +154,7 @@ Checks whether the user, for example, the application or system, has the device ```js let devicesName="1-1"; let bool = usb.hasRight(devicesName); -console.log(bool); +console.log(`${bool}`); ``` ## usb.requestRight @@ -183,7 +182,7 @@ Requests the temporary permission for the application to access a USB device. Th ```js let devicesName="1-1"; 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. ```js let devicesName="1-1"; -if (usb.removeRight(devicesName) { +if usb.removeRight(devicesName) { console.log(`Succeed in removing right`); } ``` @@ -246,7 +245,7 @@ Adds the permission for the application to access a USB device. ```js let devicesName = "1-1"; let bundleName = "com.example.hello"; -if (usb.addRight(bundleName, devicesName) { +if usb.addRight(bundleName, devicesName) { console.log(`Succeed in adding right`); } ``` @@ -455,8 +454,9 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **Example** ```js -usb.controlTransfer(devicepipe, USBControlParams).then((ret) => { - console.log(`controlTransfer = ${JSON.stringify(ret)}`); +let param = new usb.USBControlParams(); +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 // 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. 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 **Example** ```js -let funcs = ACM | ECM; +let funcs = usb.ACM | usb.ECM; let ret = usb.usbFunctionsToString(funcs); ``` @@ -608,7 +608,7 @@ Sets the current USB function list in Device mode. **Example** ```js -let funcs = HDC; +let funcs = usb.HDC; usb.setCurrentFunctions(funcs).then(() => { console.info('usb setCurrentFunctions successfully.'); }).catch(err => { @@ -716,7 +716,7 @@ Sets the role types supported by a specified port, which can be **powerRole** (f ```js 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.'); }).catch(err => { console.error('usb setPortRoles failed: ' + err.code + ' message: ' + err.message); diff --git a/en/application-dev/reference/apis/js-apis-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md index ae1f200331f1236cf299108ef0e871c4c6dcb6c0..bd7a55c09324684d80e787174483fcc8aefd884e 100644 --- a/en/application-dev/reference/apis/js-apis-webSocket.md +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -1,8 +1,7 @@ -# @ohos.net.webSocket (WebSocket Connection) +# # @ohos.net.webSocket (WebSocket Connection) -The **webSocket** module implements WebSocket connection management and operation. - -> **NOTE**
+> **NOTE** +> > 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 import webSocket from '@ohos.net.webSocket'; ``` -## Complete Example +## Examples ```js import webSocket from '@ohos.net.webSocket'; @@ -37,7 +36,7 @@ ws.on('open', (err, value) => { }); ws.on('message', (err, 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') { ws.close((err, value) => { if (!err) { @@ -49,7 +48,7 @@ ws.on('message', (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) => { console.log("on error, error:" + JSON.stringify(err)); @@ -65,13 +64,13 @@ ws.connect(defaultIpAddress, (err, value) => { ## 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. **System capability**: SystemCapability.Communication.NetStack -**Return Value** +**Return value** | Type | Description | | :---------------------------------- | :----------------------------------------------------------- | @@ -90,11 +89,11 @@ Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call ### connect -connect\(url: string, callback: AsyncCallback\): void +connect(url: string, callback: AsyncCallback\): void 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 @@ -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.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | **Example** @@ -123,11 +128,11 @@ ws.connect(url, (err, value) => { ### connect -connect\(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\): void +connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\): 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. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -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).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | **Example** @@ -162,11 +173,11 @@ ws.connect(url, { ### connect -connect\(url: string, options?: WebSocketRequestOptions\): Promise +connect(url: string, options?: WebSocketRequestOptions): Promise\ 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 @@ -177,12 +188,19 @@ Initiates a WebSocket request carrying specified options to establish a WebSocke | url | string | Yes | URL for establishing a WebSocket connection. | | options | WebSocketRequestOptions | No | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).| -**Return Value** +**Return value** | Type | Description | | :----------------- | :-------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -199,11 +217,11 @@ promise.then((value) => { ### send -send\(data: string | ArrayBuffer, callback: AsyncCallback\): void +send(data: string | ArrayBuffer, callback: AsyncCallback\): void 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 @@ -211,9 +229,16 @@ Sends data through a WebSocket connection. This API uses an asynchronous callbac | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | ------------ | -| data | string \| ArrayBuffer 8+ | Yes | Data to send.| +| data | string \| ArrayBuffer | Yes | Data to send.
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\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -233,11 +258,11 @@ ws.connect(url, (err, value) => { ### send -send\(data: string | ArrayBuffer\): Promise +send(data: string | ArrayBuffer): Promise\ 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 @@ -245,14 +270,21 @@ Sends data through a WebSocket connection. This API uses a promise to return the | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------ | -| data | string \| ArrayBuffer 8+ | Yes | Data to send.| +| data | string \| ArrayBuffer | Yes | Data to send.
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 | | :----------------- | :-------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -271,11 +303,11 @@ ws.connect(url, (err, value) => { ### close -close\(callback: AsyncCallback\): void +close(callback: AsyncCallback\): void 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 @@ -285,6 +317,13 @@ Closes a WebSocket connection. This API uses an asynchronous callback to return | -------- | ------------------------ | ---- | ---------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -302,11 +341,11 @@ ws.close((err, value) => { ### close -close\(options: WebSocketCloseOptions, callback: AsyncCallback\): void +close(options: WebSocketCloseOptions, callback: AsyncCallback\): void 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 @@ -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).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -337,11 +383,11 @@ ws.close({ ### close -close\(options?: WebSocketCloseOptions\): Promise +close(options?: WebSocketCloseOptions): Promise\ 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 @@ -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).| -**Return Value** +**Return value** | Type | Description | | :----------------- | :-------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -374,9 +427,9 @@ promise.then((value) => { ``` -### on\('open'\) +### on('open') -on\(type: 'open', callback: AsyncCallback\): void +on(type: 'open', callback: AsyncCallback\): void 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) => { ``` -### off\('open'\) +### off('open') -off\(type: 'open', callback?: AsyncCallback\): void +off(type: 'open', callback?: AsyncCallback\): void 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. **System capability**: SystemCapability.Communication.NetStack @@ -431,14 +484,14 @@ ws.off('open', callback1); ``` -### on\('message'\) +### on('message') -on\(type: 'message', callback: AsyncCallback\): void +on(type: 'message', callback: AsyncCallback\): 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. ->![](public_sys-resources/icon-note.gif) **NOTE:** ->The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). +>**NOTE** +>The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8). **System capability**: SystemCapability.Communication.NetStack @@ -449,7 +502,6 @@ Enables listening for the **message** events of a WebSocket connection. This API | type | string | Yes | Event type.
**message**: event indicating that a message has been received from the server.| | callback | AsyncCallback\8+\> | Yes | Callback used to return the result. | - **Example** ```js @@ -460,14 +512,14 @@ ws.on('message', (err, value) => { ``` -### off\('message'\) +### off('message') -off\(type: 'message', callback?: AsyncCallback\): void +off(type: 'message', callback?: AsyncCallback\): 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. ->![](public_sys-resources/icon-note.gif) **NOTE:** ->The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). +>**NOTE** +>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. **System capability**: SystemCapability.Communication.NetStack @@ -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. @@ -500,25 +552,25 @@ Enables listening for the **close** events of a WebSocket connection. This API u | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------- | ---- | ------------------------------ | | type | string | Yes | Event type.
**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.
**close** indicates the close error code and **reason** indicates the error code description.| **Example** ```js let ws = webSocket.createWebSocket(); 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. ->![](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. **System capability**: SystemCapability.Communication.NetStack @@ -528,8 +580,7 @@ Disables listening for the **close** events of a WebSocket connection. This API | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------- | ---- | ------------------------------ | | type | string | Yes | Event type.
**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.
**close** indicates the close error code and **reason** indicates the error code description.| **Example** @@ -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. @@ -554,7 +605,6 @@ Enables listening for the **error** events of a WebSocket connection. This API u | type | string | Yes | Event type.
**error**: event indicating the WebSocket connection has encountered an error.| | callback | ErrorCallback | Yes | Callback used to return the result. | - **Example** ```js @@ -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. ->![](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. **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 | Value | Description | | :-------- | :----------------- | -| 1000 | Normally closed | -| 1001 | Connection closed by the server | -| 1002 | Incorrect protocol | -| 1003 | Data unable to be processed| -| 1004~1015 | Reserved | +| 1000 | Normally closed. | +| 1001 | Connection closed by the server. | +| 1002 | Incorrect protocol. | +| 1003 | Data unable to be processed.| +| 1004~1015 | Reserved. | diff --git a/en/application-dev/reference/errorcodes/Readme-EN.md b/en/application-dev/reference/errorcodes/Readme-EN.md index a02a8f29d4e6ace770d6748a3f8146c45271e084..96e4cfe4bec67427950c8fac2203257060c7d135 100644 --- a/en/application-dev/reference/errorcodes/Readme-EN.md +++ b/en/application-dev/reference/errorcodes/Readme-EN.md @@ -47,6 +47,12 @@ - [File Management Error Codes](errorcode-filemanagement.md) - Network Management - [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 - [NFC Error Codes](errorcode-nfc.md) - [RPC Error Codes](errorcode-rpc.md) diff --git a/en/application-dev/reference/errorcodes/errorcode-net-connection.md b/en/application-dev/reference/errorcodes/errorcode-net-connection.md new file mode 100644 index 0000000000000000000000000000000000000000..00e1eaaf78562f95549c4724e182c66878ea249b --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-net-connection.md @@ -0,0 +1,114 @@ +# 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. diff --git a/en/application-dev/reference/errorcodes/errorcode-net-ethernet.md b/en/application-dev/reference/errorcodes/errorcode-net-ethernet.md new file mode 100644 index 0000000000000000000000000000000000000000..b8a940de2a94863b309c4e6fd86600c39354a444 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-net-ethernet.md @@ -0,0 +1,116 @@ +# 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. diff --git a/en/application-dev/reference/errorcodes/errorcode-net-http.md b/en/application-dev/reference/errorcodes/errorcode-net-http.md new file mode 100644 index 0000000000000000000000000000000000000000..bece9d1b26bdeae59cfd489432aa88f49bc7fe60 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-net-http.md @@ -0,0 +1,527 @@ +# 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. diff --git a/en/application-dev/reference/errorcodes/errorcode-net-policy.md b/en/application-dev/reference/errorcodes/errorcode-net-policy.md new file mode 100644 index 0000000000000000000000000000000000000000..87e1ad36f03dc74003787c764521fca1de10e3b2 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-net-policy.md @@ -0,0 +1,59 @@ +# 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. diff --git a/en/application-dev/reference/errorcodes/errorcode-net-sharing.md b/en/application-dev/reference/errorcodes/errorcode-net-sharing.md new file mode 100644 index 0000000000000000000000000000000000000000..5535d15e992c96d063746f89112be0d341f9a641 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-net-sharing.md @@ -0,0 +1,159 @@ +# 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. diff --git a/en/application-dev/reference/errorcodes/errorcode-net-socket.md b/en/application-dev/reference/errorcodes/errorcode-net-socket.md new file mode 100644 index 0000000000000000000000000000000000000000..ebd15740b694e135c394b9459c06a7f09438fc8f --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-net-socket.md @@ -0,0 +1,351 @@ +# 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. diff --git a/en/device-dev/get-code/gettools-acquire.md b/en/device-dev/get-code/gettools-acquire.md index a3025ebd834424ff319aa25f3194609ead2cf1e9..5c220923fef21109d1556e925d96946da2d54c7f 100644 --- a/en/device-dev/get-code/gettools-acquire.md +++ b/en/device-dev/get-code/gettools-acquire.md @@ -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. +3. Perform subsequent operations as a user who has the root permission or has been granted the permission to use Docker. ## Standalone Docker Environment diff --git a/en/device-dev/subsystems/subsys-dfx-hitracemeter.md b/en/device-dev/subsystems/subsys-dfx-hitracemeter.md index e5e02d1479d2b744d92bceb0525c944e87742b08..23bbef737016ec45e06f1781ff0f7b2de0cebc81 100644 --- a/en/device-dev/subsystems/subsys-dfx-hitracemeter.md +++ b/en/device-dev/subsystems/subsys-dfx-hitracemeter.md @@ -7,20 +7,17 @@ HiTraceMeter is the OpenHarmony subsystem that provides APIs to implement call c ## Basic Concepts The HiTraceMeter subsystem consists of three parts: - - JS/C++ HiTraceMeter APIs for application logging - hitrace CLI tool for data collection - 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. - -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. +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. 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. -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 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 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. @@ -109,7 +106,7 @@ Only C++ APIs are now open for system developers. If you're developing a JS app, **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.
**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.| @@ -119,7 +116,7 @@ Only C++ APIs are now open for system developers. If you're developing a JS app, **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.
**value**: trace data that indicates the specific status, such as the memory size and queue length.
**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.
**value**: trace data that indicates the specific status, such as the memory size and queue length.
**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 **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.
**name**: trace name displayed in the IDE.| +| void CountTrace(uint64_t label, const std::string& name, int64_t); | Count trace.|**label**: trace category.
**name**: trace name displayed in the IDE.| ## How to Develop @@ -147,33 +144,8 @@ The trace data of **StartAsyncTrace** and **FinishAsyncTrace** is matched based #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. - - - ```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 +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. -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 #include "hitrace_meter.h" // Include hitrace_meter.h @@ -192,11 +164,21 @@ int main() FinishTrace (label); // Trace end point of func2Trace sleep(1); 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; - } -``` + } + ``` +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 @@ -313,7 +295,7 @@ Examples: hitrace -l ``` - Or, + Alternatively, run the following command: ``` hitrace --list_categories @@ -356,6 +338,6 @@ Examples: -# References +# Reference For details about HiTraceMeter, see [hiviewdfx_hitrace: A Lightweight Distributed Tracing](https://gitee.com/openharmony/hiviewdfx_hitrace). diff --git a/en/readme/network-management.md b/en/readme/network-management.md index 08e5ae88a87a5423efbf05bdf78a818c1ad7dc31..ac7fe63d43054c0badb2fa4d5de27dd117f31022 100644 --- a/en/readme/network-management.md +++ b/en/readme/network-management.md @@ -36,6 +36,8 @@ foundation/communication/ 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. ``` @@ -43,9 +45,9 @@ foundation/communication/ import connection from '@ohos.net.connection' let netCap = { - // Set the network type to cellular network. + // Set the network type to CELLULAR. bearerTypes: [connection.NetBearType.BEARER_CELLULAR], - // Set the network capability to Internet. + // Set the network capability to INTERNET. networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET], }; let netSpec = { @@ -55,7 +57,7 @@ foundation/communication/ let timeout = 10 * 1000; // Create a NetConnection object. 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=> { console.log("net is available, netId is " + data.netId); })); @@ -67,16 +69,12 @@ foundation/communication/ ### 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. - 3. Start network sharing. - 4. Stop network sharing. - ``` -// Import the network sharing namespace. +// Import the connection namespace. import sharing from '@ohos.net.sharing'; // Set the network sharing type. 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)=>{ ### 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. - -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. - +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. 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. - -6. Call **httpRequest.destroy()** to release resources after the request is processed. +6. Call **off()** to unsubscribe from HTTP response header events. +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'; -// 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(); -// Subscribe to the HTTP response header, which is returned earlier than the response to httpRequest. -httpRequest.on('headersReceive', (data) => { - console.info('header: ' + data.header); +// 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. +// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8. +httpRequest.on('headersReceive', (header) => { + console.info('header: ' + JSON.stringify(header)); }); 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", { - 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. header: { 'Content-Type': 'application/json' @@ -127,21 +122,28 @@ httpRequest.request( extraData: { "data": "data to send", }, - connectTimeout: 60000, // This parameter is optional. The default value is 60000, that is, 60s. - readTimeout: 60000, // This parameter is optional. The default value is 60000, that is, 60s. - },(err, data) => { + 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. + 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) { // data.result carries the HTTP response. Parse the response based on service requirements. - console.info('Result:' + data.result); - console.info('code:' + data.responseCode); + console.info('Result:' + JSON.stringify(data.result)); + console.info('code:' + JSON.stringify(data.responseCode)); // data.header carries the HTTP response header. Parse the content based on service requirements. - console.info('header:' + data.header); - console.info('header:' + data.cookies); + console.info('header:' + JSON.stringify(data.header)); + console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ } 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( **Network Management Subsystem** -[communication_netmanager_base](https://gitee.com/openharmony/communication_netmanager_base) - -[communication_netmanager_ext](https://gitee.com/openharmony/communication_netmanager_ext) - -[communication_netstack](https://gitee.com/openharmony/communication_netstack) \ No newline at end of file +[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_netstack](https://gitee.com/openharmony/communication_netstack/blob/master/README_zh.md)