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/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 73fba422c3314239836d43912325159247345dc8..db5538601ca6e788e46cd4a7cc32ac662f9c4c7f 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -137,6 +137,7 @@ - [NotificationSlot](js-apis-inner-notification-notificationSlot.md) - [NotificationTemplate](js-apis-inner-notification-notificationTemplate.md) - [NotificationUserInput](js-apis-inner-notification-notificationUserInput.md) + - Bundle Management - [@ohos.bundle.appControl (appControl)](js-apis-appControl.md) - [@ohos.bundle.bundleManager (bundleManager)](js-apis-bundleManager.md) @@ -171,6 +172,7 @@ - [@ohos.promptAction (Prompt)](js-apis-promptAction.md) - [@ohos.router (Page Routing)](js-apis-router.md) - [@ohos.measure (Text Measurement)](js-apis-measure.md) + - Graphics - [@ohos.animation.windowAnimationManager (Window Animation Management)](js-apis-windowAnimationManager.md) - [@ohos.application.WindowExtensionAbility (WindowExtensionAbility)](js-apis-application-windowExtensionAbility.md) @@ -304,6 +306,7 @@ - [Timer](js-apis-timer.md) - application - [AccessibilityExtensionContext (Accessibility Extension Context)](js-apis-inner-application-accessibilityExtensionContext.md) + - Device Management - [@ohos.batteryInfo (Battery Information)](js-apis-battery-info.md) - [@ohos.batteryStatistics (Battery Statistics)](js-apis-batteryStatistics.md) diff --git a/en/application-dev/reference/apis/js-apis-bluetooth.md b/en/application-dev/reference/apis/js-apis-bluetooth.md index aa9e1937cd66e83262211280f42f11f468e2d200..617a49b7562910bcb05ca63c0b66087c1bf5f510 100644 --- a/en/application-dev/reference/apis/js-apis-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-bluetooth.md @@ -1,10 +1,10 @@ -# @ohos.bluetooth +# @ohos.bluetooth (Bluetooth) The **Bluetooth** module provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. > **NOTE** -> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs provided by this module are no longer maintained since API version 9. You are advised to use [bluetoothManager](js-apis-bluetoothManager.md). @@ -15,12 +15,15 @@ import bluetooth from '@ohos.bluetooth'; ``` -## bluetooth.enableBluetooth8+ +## bluetooth.enableBluetooth8+(deprecated) enableBluetooth(): boolean Enables Bluetooth. +> **NOTE** +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.enableBluetooth](js-apis-bluetoothManager.md#bluetoothmanagerenablebluetooth). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -38,12 +41,15 @@ let enable = bluetooth.enableBluetooth(); ``` -## bluetooth.disableBluetooth8+ +## bluetooth.disableBluetooth8+(deprecated) disableBluetooth(): boolean Disables Bluetooth. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.disableBluetooth](js-apis-bluetoothManager.md#bluetoothmanagerdisablebluetooth). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -61,12 +67,15 @@ let disable = bluetooth.disableBluetooth(); ``` -## bluetooth.getLocalName8+ +## bluetooth.getLocalName8+(deprecated) getLocalName(): string Obtains the name of the local Bluetooth device. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.getLocalName](js-apis-bluetoothManager.md#bluetoothmanagergetlocalname). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -84,12 +93,15 @@ let localName = bluetooth.getLocalName(); ``` -## bluetooth.getState +## bluetooth.getState(deprecated) getState(): BluetoothState Obtains the Bluetooth state. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.getState](js-apis-bluetoothManager.md#bluetoothmanagergetstate). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -107,12 +119,15 @@ let state = bluetooth.getState(); ``` -## bluetooth.getBtConnectionState +## bluetooth.getBtConnectionState(deprecated) getBtConnectionState(): ProfileConnectionState Obtains the profile connection state of this Bluetooth device. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.getBtConnectionState](js-apis-bluetoothManager.md#bluetoothmanagergetbtconnectionstate). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -130,12 +145,15 @@ let connectionState = bluetooth.getBtConnectionState(); ``` -## bluetooth.setLocalName8+ +## bluetooth.setLocalName8+(deprecated) setLocalName(name: string): boolean Sets the name of the local Bluetooth device. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.setLocalName](js-apis-bluetoothManager.md#bluetoothmanagersetlocalname). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -159,12 +177,15 @@ let ret = bluetooth.setLocalName('device_name'); ``` -## bluetooth.pairDevice +## bluetooth.pairDevice(deprecated) pairDevice(deviceId: string): boolean Initiates Bluetooth pairing. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.pairDevice](js-apis-bluetoothManager.md#bluetoothmanagerpairdevice). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -189,12 +210,15 @@ let result = bluetooth.pairDevice("XX:XX:XX:XX:XX:XX"); ``` -## bluetooth.getProfileConnState8+ +## bluetooth.getProfileConnState8+(deprecated) getProfileConnState(profileId: ProfileId): ProfileConnectionState Obtains the connection state of a profile. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.getProfileConnectionState](js-apis-bluetoothManager.md#bluetoothmanagergetprofileconnectionstate). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -218,12 +242,15 @@ let result = bluetooth.getProfileConnState(bluetooth.ProfileId.PROFILE_A2DP_SOUR ``` -## bluetooth.cancelPairedDevice8+ +## bluetooth.cancelPairedDevice8+(deprecated) cancelPairedDevice(deviceId: string): boolean Cancels a paired remote device. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.cancelPairedDevice](js-apis-bluetoothManager.md#bluetoothmanagercancelpaireddevice). + **System API**: This is a system API. **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH @@ -249,12 +276,15 @@ let result = bluetooth.cancelPairedDevice("XX:XX:XX:XX:XX:XX"); ``` -## bluetooth.getRemoteDeviceName8+ +## bluetooth.getRemoteDeviceName8+(deprecated) getRemoteDeviceName(deviceId: string): string Obtains the name of the remote Bluetooth device. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.getRemoteDeviceName](js-apis-bluetoothManager.md#bluetoothmanagergetremotedevicename). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -278,12 +308,15 @@ let remoteDeviceName = bluetooth.getRemoteDeviceName("XX:XX:XX:XX:XX:XX"); ``` -## bluetooth.getRemoteDeviceClass8+ +## bluetooth.getRemoteDeviceClass8+(deprecated) getRemoteDeviceClass(deviceId: string): DeviceClass Obtains the class of the remote Bluetooth device. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.getRemoteDeviceClass](js-apis-bluetoothManager.md#bluetoothmanagergetremotedeviceclass). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -307,12 +340,15 @@ let remoteDeviceClass = bluetooth.getRemoteDeviceClass("XX:XX:XX:XX:XX:XX"); ``` -## bluetooth.getPairedDevices8+ +## bluetooth.getPairedDevices8+(deprecated) getPairedDevices(): Array<string> Obtains the paired devices. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.getPairedDevices](js-apis-bluetoothManager.md#bluetoothmanagergetpaireddevices). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -330,12 +366,15 @@ let devices = bluetooth.getPairedDevices(); ``` -## bluetooth.setBluetoothScanMode8+ +## bluetooth.setBluetoothScanMode8+(deprecated) setBluetoothScanMode(mode: ScanMode, duration: number): boolean Sets the Bluetooth scan mode so that the device can be discovered by a remote device. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.setBluetoothScanMode](js-apis-bluetoothManager.md#bluetoothmanagersetbluetoothscanmode). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -361,12 +400,15 @@ let result = bluetooth.setBluetoothScanMode(bluetooth.ScanMode.SCAN_MODE_CONNECT ``` -## bluetooth.getBluetoothScanMode8+ +## bluetooth.getBluetoothScanMode8+(deprecated) getBluetoothScanMode(): ScanMode Obtains the Bluetooth scan mode. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.getBluetoothScanMode](js-apis-bluetoothManager.md#bluetoothmanagergetbluetoothscanmode). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -384,12 +426,15 @@ let scanMode = bluetooth.getBluetoothScanMode(); ``` -## bluetooth.startBluetoothDiscovery8+ +## bluetooth.startBluetoothDiscovery8+(deprecated) startBluetoothDiscovery(): boolean Starts Bluetooth scan to discover remote devices. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.startBluetoothDiscovery](js-apis-bluetoothManager.md#bluetoothmanagerstartbluetoothdiscovery). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH and ohos.permission.LOCATION **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -412,12 +457,15 @@ let result = bluetooth.startBluetoothDiscovery(); ``` -## bluetooth.stopBluetoothDiscovery8+ +## bluetooth.stopBluetoothDiscovery8+(deprecated) stopBluetoothDiscovery(): boolean Stops Bluetooth scan. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.stopBluetoothDiscovery](js-apis-bluetoothManager.md#bluetoothmanagerstopbluetoothdiscovery). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -435,12 +483,15 @@ let result = bluetooth.stopBluetoothDiscovery(); ``` -## bluetooth.setDevicePairingConfirmation8+ +## bluetooth.setDevicePairingConfirmation8+(deprecated) setDevicePairingConfirmation(device: string, accept: boolean): boolean Sets the device pairing confirmation. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.setDevicePairingConfirmation](js-apis-bluetoothManager.md#bluetoothmanagersetdevicepairingconfirmation). + **Required permissions**: ohos.permission.MANAGE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -470,12 +521,15 @@ bluetooth.on("pinRequired", onReceivePinRequiredEvent); ``` -## bluetooth.on('bluetoothDeviceFind')8+ +## bluetooth.on('bluetoothDeviceFind')8+(deprecated) on(type: "bluetoothDeviceFind", callback: Callback<Array<string>>): void Subscribes to the Bluetooth device discovery events. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.on('bluetoothDeviceFind')](js-apis-bluetoothManager.md#bluetoothmanageronbluetoothdevicefind). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -501,12 +555,15 @@ bluetooth.on('bluetoothDeviceFind', onReceiveEvent); ``` -## bluetooth.off('bluetoothDeviceFind')8+ +## bluetooth.off('bluetoothDeviceFind')8+(deprecated) off(type: "bluetoothDeviceFind", callback?: Callback<Array<string>>): void Unsubscribes from the Bluetooth device discovery events. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.off('bluetoothDeviceFind')](js-apis-bluetoothManager.md#bluetoothmanageroffbluetoothdevicefind). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -533,12 +590,15 @@ bluetooth.off('bluetoothDeviceFind', onReceiveEvent); ``` -## bluetooth.on('pinRequired')8+ +## bluetooth.on('pinRequired')8+(deprecated) on(type: "pinRequired", callback: Callback<PinRequiredParam>): void Subscribes to the pairing request events of the remote Bluetooth device. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.on('pinRequired')](js-apis-bluetoothManager.md#bluetoothmanageronpinrequired). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -564,12 +624,15 @@ bluetooth.on('pinRequired', onReceiveEvent); ``` -## bluetooth.off('pinRequired')8+ +## bluetooth.off('pinRequired')8+(deprecated) off(type: "pinRequired", callback?: Callback<PinRequiredParam>): void Unsubscribes from the pairing request events of the remote Bluetooth device. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.off('pinRequired')](js-apis-bluetoothManager.md#bluetoothmanageroffpinrequired). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -596,12 +659,15 @@ bluetooth.off('pinRequired', onReceiveEvent); ``` -## bluetooth.on('bondStateChange')8+ +## bluetooth.on('bondStateChange')8+(deprecated) on(type: "bondStateChange", callback: Callback<BondStateParam>): void Subscribes to the Bluetooth pairing state change events. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.on('bondStateChange')](js-apis-bluetoothManager.md#bluetoothmanageronbondstatechange). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -627,12 +693,15 @@ bluetooth.on('bondStateChange', onReceiveEvent); ``` -## bluetooth.off('bondStateChange')8+ +## bluetooth.off('bondStateChange')8+(deprecated) off(type: "bondStateChange", callback?: Callback<BondStateParam>): void Unsubscribes from the Bluetooth pairing state change events. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.off('bondStateChange')](js-apis-bluetoothManager.md#bluetoothmanageroffbondstatechange). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -659,12 +728,15 @@ bluetooth.off('bondStateChange', onReceiveEvent); ``` -## bluetooth.on('stateChange')8+ +## bluetooth.on('stateChange')8+(deprecated) on(type: "stateChange", callback: Callback<BluetoothState>): void Subscribes to the Bluetooth connection state change events. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.on('stateChange')](js-apis-bluetoothManager.md#bluetoothmanageronstatechange). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -690,12 +762,15 @@ bluetooth.on('stateChange', onReceiveEvent); ``` -## bluetooth.off('stateChange')8+ +## bluetooth.off('stateChange')8+(deprecated) off(type: "stateChange", callback?: Callback<BluetoothState>): void Unsubscribes from the Bluetooth connection state change events. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.off('stateChange')](js-apis-bluetoothManager.md#bluetoothmanageroffstatechange). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -722,12 +797,15 @@ bluetooth.off('stateChange', onReceiveEvent); ``` -## bluetooth.sppListen8+ +## bluetooth.sppListen8+(deprecated) sppListen(name: string, option: SppOption, callback: AsyncCallback<number>): void Creates a server listening socket. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.sppListen](js-apis-bluetoothManager.md#bluetoothmanagerspplisten). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -757,12 +835,15 @@ bluetooth.sppListen('server1', sppOption, serverSocket); ``` -## bluetooth.sppAccept8+ +## bluetooth.sppAccept8+(deprecated) sppAccept(serverSocket: number, callback: AsyncCallback<number>): void Listens for a connection to be made to this socket from the client and accepts it. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.sppAccept](js-apis-bluetoothManager.md#bluetoothmanagersppaccept). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -796,12 +877,15 @@ bluetooth.sppAccept(serverNumber, acceptClientSocket); ``` -## bluetooth.sppConnect8+ +## bluetooth.sppConnect8+(deprecated) sppConnect(device: string, option: SppOption, callback: AsyncCallback<number>): void Initiates an SPP connection to a remote device from the client. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.sppConnect](js-apis-bluetoothManager.md#bluetoothmanagersppconnect). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -832,12 +916,15 @@ bluetooth.sppConnect('XX:XX:XX:XX:XX:XX', sppOption, clientSocket); ``` -## bluetooth.sppCloseServerSocket8+ +## bluetooth.sppCloseServerSocket8+(deprecated) sppCloseServerSocket(socket: number): void Closes the listening socket of the server. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.sppCloseServerSocket](js-apis-bluetoothManager.md#bluetoothmanagersppcloseserversocket). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -861,12 +948,15 @@ bluetooth.sppCloseServerSocket(serverNumber); ``` -## bluetooth.sppCloseClientSocket8+ +## bluetooth.sppCloseClientSocket8+(deprecated) sppCloseClientSocket(socket: number): void Closes the client socket. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.sppCloseClientSocket](js-apis-bluetoothManager.md#bluetoothmanagersppcloseclientsocket). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -892,12 +982,15 @@ bluetooth.sppCloseClientSocket(clientNumber); ``` -## bluetooth.sppWrite8+ +## bluetooth.sppWrite8+(deprecated) sppWrite(clientSocket: number, data: ArrayBuffer): boolean Writes data to the remote device through the socket. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.sppWrite](js-apis-bluetoothManager.md#bluetoothmanagersppwrite). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -937,10 +1030,13 @@ if (ret) { ``` -## bluetooth.on('sppRead')8+ +## bluetooth.on('sppRead')8+(deprecated) on(type: "sppRead", clientSocket: number, callback: Callback<ArrayBuffer>): void +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.on('sppRead')](js-apis-bluetoothManager.md#bluetoothmanageronsppread). + Subscribes to the SPP read request events. **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -977,12 +1073,15 @@ bluetooth.on('sppRead', clientNumber, dataRead); ``` -## bluetooth.off('sppRead')8+ +## bluetooth.off('sppRead')8+(deprecated) off(type: "sppRead", clientSocket: number, callback?: Callback<ArrayBuffer>): void Unsubscribes from the SPP read request events. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.off('sppRead')](js-apis-bluetoothManager.md#bluetoothmanageroffsppread). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -1013,12 +1112,15 @@ bluetooth.off('sppRead', clientNumber); ``` -## bluetooth.getProfile8+ +## bluetooth.getProfile8+(deprecated) getProfile(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile Obtains a profile object. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.getProfileInstance](js-apis-bluetoothManager.md#bluetoothmanagergetprofileinstance). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -1039,41 +1141,18 @@ Obtains a profile object. let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); ``` -## bluetooth.getProfileInst9+ - -getProfileInst(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile | HidHostProfile | PanProfile - -Obtains a profile instance. API version 9 is added with **HidHostProfile** and **PanProfile**. - -**System capability**: SystemCapability.Communication.Bluetooth.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| --------- | --------- | ---- | ------------------------------------- | -| profileId | [ProfileId](#ProfileId) | Yes | ID of the profile to obtain, for example, **PROFILE_A2DP_SOURCE**.| - -**Return value** - -| Type | Description | -| ------------------------------------------------------------ | ------------------------------------------------------------ | -| [A2dpSourceProfile](#a2dpsourceprofile), [HandsFreeAudioGatewayProfile](#handsfreeaudiogatewayprofile), [HidHostProfile](#hidhostprofile), or [PanProfile](#panprofile)| Profile instance obtained, which can be **A2dpSourceProfile**, **HandsFreeAudioGatewayProfile**, **HidHostProfile**, or **PanProfile**.| - -**Example** - -```js -let hidHost = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST); -``` - ## bluetooth.BLE -### bluetooth.BLE.createGattServer +### bluetooth.BLE.createGattServer(deprecated) createGattServer(): GattServer Creates a **GattServer** instance. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.BLE.createGattServer](js-apis-bluetoothManager.md#bluetoothmanagerblecreategattserver). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Return value** @@ -1089,12 +1168,15 @@ let gattServer = bluetooth.BLE.createGattServer(); ``` -### bluetooth.BLE.createGattClientDevice +### bluetooth.BLE.createGattClientDevice(deprecated) createGattClientDevice(deviceId: string): GattClientDevice Creates a **GattClientDevice** instance. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.BLE.createGattClientDevice](js-apis-bluetoothManager.md#bluetoothmanagerblecreategattclientdevice). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -1116,12 +1198,15 @@ let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); ``` -### bluetooth.BLE.getConnectedBLEDevices +### bluetooth.BLE.getConnectedBLEDevices(deprecated) getConnectedBLEDevices(): Array<string> Obtains the BLE devices connected to this device. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.BLE.getConnectedBLEDevices](js-apis-bluetoothManager.md#bluetoothmanagerblegetconnectedbledevices). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1139,12 +1224,15 @@ let result = bluetooth.BLE.getConnectedBLEDevices(); ``` -### bluetooth.BLE.startBLEScan +### bluetooth.BLE.startBLEScan(deprecated) startBLEScan(filters: Array<ScanFilter>, options?: ScanOptions): void Starts a BLE scan. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.BLE.startBLEScan](js-apis-bluetoothManager.md#bluetoothmanagerblestartblescan). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH, ohos.permission.MANAGE_BLUETOOTH, and ohos.permission.LOCATION **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1182,12 +1270,15 @@ bluetooth.BLE.startBLEScan( ``` -### bluetooth.BLE.stopBLEScan +### bluetooth.BLE.stopBLEScan(deprecated) stopBLEScan(): void Stops the BLE scan. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.BLE.stopBLEScan](js-apis-bluetoothManager.md#bluetoothmanagerblestopblescan). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1203,12 +1294,15 @@ bluetooth.BLE.stopBLEScan(); ``` -### bluetooth.BLE.on('BLEDeviceFind') +### bluetooth.BLE.on('BLEDeviceFind')(deprecated) on(type: "BLEDeviceFind", callback: Callback<Array<ScanResult>>): void Subscribe to the BLE device discovery events. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.BLE.on('BLEDeviceFind')](js-apis-bluetoothManager.md#bluetoothmanagerbleonbledevicefind). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1234,12 +1328,15 @@ bluetooth.BLE.on('BLEDeviceFind', onReceiveEvent); ``` -### bluetooth.BLE.off('BLEDeviceFind') +### bluetooth.BLE.off('BLEDeviceFind')(deprecated) off(type: "BLEDeviceFind", callback?: Callback<Array<ScanResult>>): void Unsubscribes from the BLE device discovery events. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.BLE.off('BLEDeviceFind')](js-apis-bluetoothManager.md#bluetoothmanagerbleoffbledevicefind). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1271,12 +1368,15 @@ bluetooth.BLE.off('BLEDeviceFind', onReceiveEvent); Provides the profile base class. -### getConnectionDevices8+ +### getConnectionDevices8+(deprecated) getConnectionDevices(): Array<string> Obtains the connected devices. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.BaseProfile.getConnectionDevices](js-apis-bluetoothManager.md#getconnectiondevices). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1294,12 +1394,15 @@ let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as b let retArray = a2dpSrc.getConnectionDevices(); ``` -### getDeviceState8+ +### getDeviceState8+(deprecated) getDeviceState(device: string): ProfileConnectionState Obtains the connection state of the profile. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.BaseProfile.getDeviceState](js-apis-bluetoothManager.md#getdevicestate). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1328,12 +1431,15 @@ let ret = a2dpSrc.getDeviceState('XX:XX:XX:XX:XX:XX'); Before using a method of **A2dpSourceProfile**, you need to create an instance of this class by using the **getProfile()** method. -### connect8+ +### connect8+(deprecated) connect(device: string): boolean Sets up an Advanced Audio Distribution Profile (A2DP) connection. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.A2dpSourceProfile.connect](js-apis-bluetoothManager.md#connect). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1358,12 +1464,15 @@ let ret = a2dpSrc.connect('XX:XX:XX:XX:XX:XX'); ``` -### disconnect8+ +### disconnect8+(deprecated) disconnect(device: string): boolean Disconnects an A2DP connection. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.A2dpSourceProfile.disconnect](js-apis-bluetoothManager.md#disconnect). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1388,12 +1497,15 @@ let ret = a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX'); ``` -### on('connectionStateChange')8+ +### on('connectionStateChange')8+(deprecated) on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void Subscribes to the A2DP connection state change events. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.A2dpSourceProfile.on('connectionStateChange')](js-apis-bluetoothManager.md#onconnectionstatechange). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -1401,7 +1513,7 @@ Subscribes to the A2DP connection state change events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | | type | string | Yes | Event type. The value **connectionStateChange** indicates an A2DP connection state change event.| -| callback | Callback<[StateChangeParam](#StateChangeParam)> | Yes | Callback invoked to return the A2DP connection state change event. | +| callback | Callback<[StateChangeParam](#StateChangeParam)> | Yes | Callback used to return the A2DP connection state change event. | **Return value** @@ -1418,12 +1530,15 @@ a2dpSrc.on('connectionStateChange', onReceiveEvent); ``` -### off('connectionStateChange')8+ +### off('connectionStateChange')8+(deprecated) off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void Unsubscribes from the A2DP connection state change events. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.A2dpSourceProfile.off('connectionStateChange')](js-apis-bluetoothManager.md#offconnectionstatechange). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -1449,12 +1564,15 @@ a2dpSrc.off('connectionStateChange', onReceiveEvent); ``` -### getPlayingState8+ +### getPlayingState8+(deprecated) getPlayingState(device: string): PlayingState Obtains the playing state of a device. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.A2dpSourceProfile.getPlayingState](js-apis-bluetoothManager.md#getplayingstate). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -1482,12 +1600,15 @@ let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX'); Before using a method of **HandsFreeAudioGatewayProfile**, you need to create an instance of this class by using the **getProfile()** method. -### connect8+ +### connect8+(deprecated) connect(device: string): boolean Sets up a Hands-free Profile (HFP) connection of a device. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.HandsFreeAudioGatewayProfile.connect](js-apis-bluetoothManager.md#connect-1). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1513,12 +1634,15 @@ let ret = hfpAg.connect('XX:XX:XX:XX:XX:XX'); ``` -### disconnect8+ +### disconnect8+(deprecated) disconnect(device: string): boolean Disconnects the HFP connection of a device. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.HandsFreeAudioGatewayProfile.disconnect](js-apis-bluetoothManager.md#disconnect-1). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1544,12 +1668,15 @@ let ret = hfpAg.disconnect('XX:XX:XX:XX:XX:XX'); ``` -### on('connectionStateChange')8+ +### on('connectionStateChange')8+(deprecated) on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void Subscribes to the HFP connection state change events. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.HandsFreeAudioGatewayProfile.on('connectionStateChange')](js-apis-bluetoothManager.md#onconnectionstatechange-1). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -1575,12 +1702,15 @@ hfpAg.on('connectionStateChange', onReceiveEvent); ``` -### off('connectionStateChange')8+ +### off('connectionStateChange')8+(deprecated) off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void Unsubscribes from the HFP connection state change events. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.HandsFreeAudioGatewayProfile.off('connectionStateChange')](js-apis-bluetoothManager.md#offconnectionstatechange-1). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -1607,301 +1737,20 @@ hfpAg.off('connectionStateChange', onReceiveEvent); ``` -## HidHostProfile - -Before using a method of **HidHostProfile**, you need to create an instance of this class by using the **getProfile()** method. - - -### connect9+ - -connect(device: string): boolean - -Connects to the HidHost service of a device. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH - -**System capability**: SystemCapability.Communication.Bluetooth.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ------- | -| device | string | Yes | Address of the target device.| - -**Return value** - -| Type | Description | -| --------------------- | --------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Example** - -```js -let hidHostProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile; -let ret = hidHostProfile.connect('XX:XX:XX:XX:XX:XX'); -``` - - -### disconnect9+ - -disconnect(device: string): boolean - -Disconnects from the HidHost service of a device. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH - -**System capability**: SystemCapability.Communication.Bluetooth.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ------- | -| device | string | Yes | Address of the target device.| - -**Return value** - -| Type | Description | -| --------------------- | --------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Example** - -```js -let hidHostProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile; -let ret = hidHostProfile.disconnect('XX:XX:XX:XX:XX:XX'); -``` - - -### on('connectionStateChange')9+ - -on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void - -Subscribes to the HidHost connection state change events. - -**System capability**: SystemCapability.Communication.Bluetooth.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | string | Yes | Event type. The value **connectionStateChange** indicates a HidHost connection state change event.| -| callback | Callback<[StateChangeParam](#StateChangeParam)> | Yes | Callback invoked to return the HidHost connection state change event. | - -**Return value** - -No value is returned. - -**Example** - -```js -function onReceiveEvent(data) { - console.info('hidHost state = '+ JSON.stringify(data)); -} -let hidHost = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile; -hidHost.on('connectionStateChange', onReceiveEvent); -``` - - -### off('connectionStateChange')9+ - -off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void - -Unsubscribes from the HidHost connection state change events. - -**System capability**: SystemCapability.Communication.Bluetooth.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | ---- | --------------------------------------------------------- | -| type | string | Yes | Event type. The value **connectionStateChange** indicates a HidHost connection state change event.| -| callback | Callback<[StateChangeParam](#StateChangeParam)> | No | Callback for the HidHost connection state change event. | - -**Return value** - -No value is returned. - -**Example** - -```js -function onReceiveEvent(data) { - console.info('hidHost state = '+ JSON.stringify(data)); -} -let hidHost = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile; -hidHost.on('connectionStateChange', onReceiveEvent); -hidHost.off('connectionStateChange', onReceiveEvent); -``` - - -## PanProfile - -Before using a method of **PanProfile**, you need to create an instance of this class by using the **getProfile()** method. - - -### disconnect9+ - -disconnect(device: string): boolean - -Disconnects from the Personal Area Network (PAN) service of a device. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.USE_BLUETOOTH - -**System capability**: SystemCapability.Communication.Bluetooth.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ------- | -| device | string | Yes | Address of the target device.| - -**Return value** - -| Type | Description | -| --------------------- | --------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Example** - -```js -let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; -let ret = panProfile.disconnect('XX:XX:XX:XX:XX:XX'); -``` - - -### on('connectionStateChange')9+ - -on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void - -Subscribes to the PAN connection state change events. - -**System capability**: SystemCapability.Communication.Bluetooth.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | string | Yes | Event type. The value **connectionStateChange** indicates a PAN connection state change event.| -| callback | Callback<[StateChangeParam](#StateChangeParam)> | Yes | Callback invoked to return the PAN connection state change event. | - -**Return value** - -No value is returned. - -**Example** - -```js -function onReceiveEvent(data) { - console.info('pan state = '+ JSON.stringify(data)); -} -let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; -panProfile.on('connectionStateChange', onReceiveEvent); -``` - - -### off('connectionStateChange')9+ - -off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void - -Unsubscribes from the PAN connection state change events. - -**System capability**: SystemCapability.Communication.Bluetooth.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | ---- | --------------------------------------------------------- | -| type | string | Yes | Event type. The value **connectionStateChange** indicates a PAN connection state change event.| -| callback | Callback<[StateChangeParam](#StateChangeParam)> | No | Callback for the PAN connection state change event. | - -**Return value** - -No value is returned. - -**Example** - -```js -function onReceiveEvent(data) { - console.info('pan state = '+ JSON.stringify(data)); -} -let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; -panProfile.on('connectionStateChange', onReceiveEvent); -panProfile.off('connectionStateChange', onReceiveEvent); -``` - - -### setTethering9+ - -setTethering(enable: boolean): void - -Sets tethering. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH - -**System capability**: SystemCapability.Communication.Bluetooth.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ------- | -| value | boolean | Yes | Whether to set tethering over a Bluetooth PAN.| - -**Return value** - -| Type | Description | -| --------------------- | --------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Example** - -```js -let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; -let ret = panProfile.setTethering(true); -``` - - -### isTetheringOn9+ - -isTetheringOn(): boolean - -Obtains the tethering state. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.Bluetooth.Core - -**Return value** - -| Type | Description | -| --------------------- | --------------------------------- | -| boolean | Returns **true** if tethering is available over a Bluetooth PAN; return **false** otherwise.| - -**Example** - -```js -let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; -let ret = panProfile.isTetheringOn(); -``` - - ## GattServer Implements the Generic Attribute Profile (GATT) server. Before using a method of this class, you need to create a **GattServer** instance using the **createGattServer()** method. -### startAdvertising +### startAdvertising(deprecated) startAdvertising(setting: AdvertiseSetting, advData: AdvertiseData, advResponse?: AdvertiseData): void Starts BLE advertising. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.startAdvertising](js-apis-bluetoothManager.md#startadvertising). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1963,12 +1812,15 @@ gattServer.startAdvertising({ ``` -### stopAdvertising +### stopAdvertising(deprecated) stopAdvertising(): void Stops BLE advertising. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.stopAdvertising](js-apis-bluetoothManager.md#stopadvertising). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1985,12 +1837,15 @@ server.stopAdvertising(); ``` -### addService +### addService(deprecated) addService(service: GattService): boolean Adds a service to this GATT server. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.addService](js-apis-bluetoothManager.md#addservice). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2044,12 +1899,15 @@ if (ret) { ``` -### removeService +### removeService(deprecated) removeService(serviceUuid: string): boolean Removes a service from this GATT server. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.removeService](js-apis-bluetoothManager.md#removeservice). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2074,12 +1932,15 @@ server.removeService('00001810-0000-1000-8000-00805F9B34FB'); ``` -### close +### close(deprecated) close(): void Closes this GATT server to unregister it from the protocol stack. After this method is called, this [GattServer](#gattserver) cannot be used. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.close](js-apis-bluetoothManager.md#close). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2092,12 +1953,15 @@ server.close(); ``` -### notifyCharacteristicChanged +### notifyCharacteristicChanged(deprecated) notifyCharacteristicChanged(deviceId: string, notifyCharacteristic: NotifyCharacteristic): boolean Notifies the connected client device when a characteristic value changes. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.notifyCharacteristicChanged](js-apis-bluetoothManager.md#notifycharacteristicchanged). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2137,12 +2001,15 @@ server.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacteristic); ``` -### sendResponse +### sendResponse(deprecated) sendResponse(serverResponse: ServerResponse): boolean Sends a response to a read or write request from the GATT client. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.sendResponse](js-apis-bluetoothManager.md#sendresponse). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2184,12 +2051,15 @@ if (ret) { ``` -### on('characteristicRead') +### on('characteristicRead')(deprecated) on(type: "characteristicRead", callback: Callback<CharacteristicReadReq>): void Subscribes to the characteristic read request events. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.on('characteristicRead')](js-apis-bluetoothManager.md#oncharacteristicread). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2232,12 +2102,15 @@ gattServer.on("characteristicRead", ReadCharacteristicReq); ``` -### off('characteristicRead') +### off('characteristicRead')(deprecated) off(type: "characteristicRead", callback?: Callback<CharacteristicReadReq>): void Unsubscribes from the characteristic read request events. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.off('characteristicRead')](js-apis-bluetoothManager.md#offcharacteristicread). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2261,12 +2134,16 @@ gattServer.off("characteristicRead"); ``` -### on('characteristicWrite') +### on('characteristicWrite')(deprecated) on(type: "characteristicWrite", callback: Callback<CharacteristicWriteReq>): void Subscribes to the characteristic write request events. +> **NOTE**
+> This API is supported since API version 7 and +> deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.on('characteristicWrite')](js-apis-bluetoothManager.md#oncharacteristicwrite). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2312,12 +2189,15 @@ gattServer.on("characteristicWrite", WriteCharacteristicReq); ``` -### off('characteristicWrite') +### off('characteristicWrite')(deprecated) off(type: "characteristicWrite", callback?: Callback<CharacteristicWriteReq>): void Unsubscribes from the characteristic write request events. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.off('characteristicWrite')](js-apis-bluetoothManager.md#offcharacteristicwrite). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2341,12 +2221,15 @@ gattServer.off("characteristicWrite"); ``` -### on('descriptorRead') +### on('descriptorRead')(deprecated) on(type: "descriptorRead", callback: Callback<DescriptorReadReq>): void Subscribes to the descriptor read request events. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.on('descriptorRead')](js-apis-bluetoothManager.md#ondescriptorread). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2356,7 +2239,7 @@ Subscribes to the descriptor read request events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------- | | type | string | Yes | Event type. The value **descriptorRead** indicates a descriptor read request event.| -| callback | Callback<[DescriptorReadReq](#descriptorreadreq)> | Yes | Callback invoked to return a descriptor read request event from the GATT client. | +| callback | Callback<[DescriptorReadReq](#descriptorreadreq)> | Yes | Callback invoked to return a descriptor read request event from the GATT client. | **Return value** @@ -2389,12 +2272,15 @@ gattServer.on("descriptorRead", ReadDescriptorReq); ``` -### off('descriptorRead') +### off('descriptorRead')(deprecated) off(type: "descriptorRead", callback?: Callback<DescriptorReadReq>): void Unsubscribes from the descriptor read request events. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.off('descriptorRead')](js-apis-bluetoothManager.md#offdescriptorread). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2418,12 +2304,15 @@ gattServer.off("descriptorRead"); ``` -### on('descriptorWrite') +### on('descriptorWrite')(deprecated) on(type: "descriptorWrite", callback: Callback<DescriptorWriteReq>): void Subscribes to the descriptor write request events. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.on('descriptorWrite')](js-apis-bluetoothManager.md#ondescriptorwrite). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2433,7 +2322,7 @@ Subscribes to the descriptor write request events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------- | | type | string | Yes | Event type. The value **descriptorWrite** indicates a descriptor write request event.| -| callback | Callback<[DescriptorWriteReq](#descriptorwritereq)> | Yes | Callback invoked to return a descriptor write request from the GATT client. | +| callback | Callback<[DescriptorWriteReq](#descriptorwritereq)> | Yes | Callback invoked to return a descriptor write request from the GATT client. | **Return value** @@ -2469,12 +2358,15 @@ gattServer.on("descriptorRead", WriteDescriptorReq); ``` -### off('descriptorWrite') +### off('descriptorWrite')(deprecated) off(type: "descriptorWrite", callback?: Callback<DescriptorWriteReq>): void Unsubscribes from the descriptor write request events. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.off('descriptorWrite')](js-apis-bluetoothManager.md#offdescriptorwrite). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2498,12 +2390,15 @@ gattServer.off("descriptorWrite"); ``` -### on('connectStateChange') +### on('connectStateChange')(deprecated) on(type: "connectStateChange", callback: Callback<BLEConnectChangedState>): void Subscribes to the BLE connection state change events. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.on('connectStateChange')](js-apis-bluetoothManager.md#onconnectstatechange). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2532,12 +2427,15 @@ gattServer.on("connectStateChange", Connected); ``` -### off('connectStateChange') +### off('connectStateChange')(deprecated) off(type: "connectStateChange", callback?: Callback<BLEConnectChangedState>): void Unsubscribes from the BLE connection state change events. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.off('connectStateChange')](js-apis-bluetoothManager.md#offconnectstatechange). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2566,12 +2464,15 @@ gattServer.off("connectStateChange"); Implements the GATT client. Before using a method of this class, you must create a **GattClientDevice** instance using the **createGattClientDevice(deviceId: string)** method. -### connect +### connect(deprecated) connect(): boolean Initiates a connection to the remote BLE device. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.connect](js-apis-bluetoothManager.md#connect-3). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2590,12 +2491,15 @@ let ret = device.connect(); ``` -### disconnect +### disconnect(deprecated) disconnect(): boolean Disconnects from the remote BLE device. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.disconnect](js-apis-bluetoothManager.md#disconnect-4). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2614,12 +2518,15 @@ let ret = device.disconnect(); ``` -### close +### close(deprecated) close(): boolean Closes this GATT client to unregister it from the protocol stack. After this method is called, this [GattClientDevice](#gattclientdevice) instance cannot be used. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.close](js-apis-bluetoothManager.md#close-1). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2640,12 +2547,15 @@ let ret = device.close(); -### getServices +### getServices(deprecated) getServices(callback: AsyncCallback<Array<GattService>>): void Obtains all services of the remote BLE device. This API uses an asynchronous callback to return the result. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.getServices](js-apis-bluetoothManager.md#getservices). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2682,12 +2592,15 @@ device.getServices(getServices); ``` -### getServices +### getServices(deprecated) getServices(): Promise<Array<GattService>> Obtains all services of the remote BLE device. This API uses a promise to return the result. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.getServices](js-apis-bluetoothManager.md#getservices-1). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2710,12 +2623,15 @@ device.getServices().then(result => { ``` -### readCharacteristicValue +### readCharacteristicValue(deprecated) readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback<BLECharacteristic>): void Reads the characteristic value of the specific service of the remote BLE device. This API uses an asynchronous callback to return the result. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.readCharacteristicValue](js-apis-bluetoothManager.md#readcharacteristicvalue). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2764,12 +2680,15 @@ device.readCharacteristicValue(characteristic, readCcc); ``` -### readCharacteristicValue +### readCharacteristicValue(deprecated) readCharacteristicValue(characteristic: BLECharacteristic): Promise<BLECharacteristic> Reads the characteristic value of the specific service of the remote BLE device. This API uses a promise to return the result. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.readCharacteristicValue](js-apis-bluetoothManager.md#readcharacteristicvalue-1). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2810,12 +2729,15 @@ device.readCharacteristicValue(characteristic); ``` -### readDescriptorValue +### readDescriptorValue(deprecated) readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<BLEDescriptor>): void Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses an asynchronous callback to return the result. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.readDescriptorValue](js-apis-bluetoothManager.md#readdescriptorvalue). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2854,12 +2776,15 @@ device.readDescriptorValue(descriptor, readDesc); ``` -### readDescriptorValue +### readDescriptorValue(deprecated) readDescriptorValue(descriptor: BLEDescriptor): Promise<BLEDescriptor> Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses a promise to return the result. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.readDescriptorValue](js-apis-bluetoothManager.md#readdescriptorvalue-1). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2890,12 +2815,15 @@ device.readDescriptorValue(descriptor); ``` -### writeCharacteristicValue +### writeCharacteristicValue(deprecated) writeCharacteristicValue(characteristic: BLECharacteristic): boolean Writes a characteristic value to the remote BLE device. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.writeCharacteristicValue](js-apis-bluetoothManager.md#writecharacteristicvalue). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2940,12 +2868,15 @@ if (retWriteCcc) { ``` -### writeDescriptorValue +### writeDescriptorValue(deprecated) writeDescriptorValue(descriptor: BLEDescriptor): boolean Writes binary data to the specific descriptor of the remote BLE device. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.writeDescriptorValue](js-apis-bluetoothManager.md#writedescriptorvalue). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2981,12 +2912,15 @@ if (retWriteDesc) { ``` -### setBLEMtuSize +### setBLEMtuSize(deprecated) setBLEMtuSize(mtu: number): boolean Sets the maximum transmission unit (MTU) that can be transmitted between the GATT client and its remote BLE device. This API can be used only after a connection is set up by calling [connect](#connect). +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.setBLEMtuSize](js-apis-bluetoothManager.md#setblemtusize). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3011,12 +2945,15 @@ device.setBLEMtuSize(128); ``` -### setNotifyCharacteristicChanged +### setNotifyCharacteristicChanged(deprecated) setNotifyCharacteristicChanged(characteristic: BLECharacteristic, enable: boolean): boolean Sets the function of notifying the GATT client when the characteristic value of the remote BLE device changes. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.setNotifyCharacteristicChanged](js-apis-bluetoothManager.md#setnotifycharacteristicchanged). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3054,12 +2991,15 @@ device.setNotifyCharacteristicChanged(characteristic, false); ``` -### on('BLECharacteristicChange') +### on('BLECharacteristicChange')(deprecated) on(type: "BLECharacteristicChange", callback: Callback<BLECharacteristic>): void Subscribes to the BLE characteristic change events. The client can receive a notification from the server only after the **setNotifyCharacteristicChanged** method is called. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.on('BLECharacteristicChange')](js-apis-bluetoothManager.md#onblecharacteristicchange). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3088,12 +3028,15 @@ device.on('BLECharacteristicChange', CharacteristicChange); ``` -### off('BLECharacteristicChange') +### off('BLECharacteristicChange')(deprecated) off(type: "BLECharacteristicChange", callback?: Callback<BLECharacteristic>): void Unsubscribes from the BLE characteristic change events. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.off('BLECharacteristicChange')](js-apis-bluetoothManager.md#offblecharacteristicchange). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3117,12 +3060,15 @@ device.off('BLECharacteristicChange'); ``` -### on('BLEConnectionStateChange') +### on('BLEConnectionStateChange')(deprecated) on(type: "BLEConnectionStateChange", callback: Callback<BLEConnectChangedState>): void Subscribes to the BLE connection state change events. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.on('BLEConnectionStateChange')](js-apis-bluetoothManager.md#onbleconnectionstatechange). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3150,12 +3096,15 @@ device.on('BLEConnectionStateChange', ConnectStateChanged); ``` -### off('BLEConnectionStateChange') +### off('BLEConnectionStateChange')(deprecated) off(type: "BLEConnectionStateChange", callback?: Callback<BLEConnectChangedState>): void Unsubscribes from the BLE connection state change events. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.off('BLEConnectionStateChange')](js-apis-bluetoothManager.md#offbleconnectionstatechange). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3179,12 +3128,15 @@ device.off('BLEConnectionStateChange'); ``` -### getDeviceName +### getDeviceName(deprecated) getDeviceName(callback: AsyncCallback<string>): void Obtains the name of the remote BLE device. This API uses an asynchronous callback to return the result. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.getDeviceName](js-apis-bluetoothManager.md#getdevicename). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3211,12 +3163,15 @@ let deviceName = gattClient.getDeviceName((err, data)=> { ``` -### getDeviceName +### getDeviceName(deprecated) getDeviceName(): Promise<string> Obtains the name of the remote BLE device. This API uses a promise to return the result. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.getDeviceName](js-apis-bluetoothManager.md#getdevicename-1). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3239,11 +3194,14 @@ let deviceName = gattClient.getDeviceName().then((data) => { ``` -### getRssiValue +### getRssiValue(deprecated) getRssiValue(callback: AsyncCallback<number>): void -Obtains the received signal strength indication (RSSI) of the remote BLE device. This API uses an asynchronous callback to return the result. It can be used only after a connection is set up by calling [connect](#connect). +Obtains the RSSI of the remote BLE device. This API uses an asynchronous callback to return the result. It can be used only after a connection is set up by calling [connect](#connect). + +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.getRssiValue](js-apis-bluetoothManager.md#getrssivalue). **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -3272,12 +3230,15 @@ let rssi = gattClient.getRssiValue((err, data)=> { ``` -### getRssiValue +### getRssiValue(deprecated) getRssiValue(): Promise<number> Obtains the RSSI of the remote BLE device. This API uses a promise to return the result. It can be used only after a connection is set up by calling [connect](#connect). +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.getRssiValue](js-apis-bluetoothManager.md#getrssivalue-1). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3298,10 +3259,13 @@ let rssi = gattClient.getRssiValue().then((data) => { }) ``` -## ScanMode8+ +## ScanMode8+(deprecated) Enumerates the scan modes. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.ScanMode](js-apis-bluetoothManager.md#scanmode). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -3313,10 +3277,13 @@ Enumerates the scan modes. | SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE | 4 | General connectable and discoverable mode.| | SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE | 5 | Limited connectable and discoverable mode.| -## BondState8+ +## BondState8+(deprecated) Enumerates the pairing states. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.BondState](js-apis-bluetoothManager.md#bondstate). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -3326,10 +3293,13 @@ Enumerates the pairing states. | BOND_STATE_BONDED | 2 | Paired. | -## SppOption8+ +## SppOption8+(deprecated) Defines the SPP configuration parameters. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.SppOption](js-apis-bluetoothManager.md#sppoption). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3339,10 +3309,13 @@ Defines the SPP configuration parameters. | type | [SppType](#spptype) | Yes | Yes | Type of the SPP link. | -## SppType8+ +## SppType8+(deprecated) Enumerates the SPP link types. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.SppType](js-apis-bluetoothManager.md#spptype). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -3350,10 +3323,13 @@ Enumerates the SPP link types. | SPP_RFCOMM | 0 | Radio frequency communication (RFCOMM) link type.| -## GattService +## GattService(deprecated) Defines the GATT service API parameters. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattService](js-apis-bluetoothManager.md#gattservice). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3364,10 +3340,13 @@ Defines the GATT service API parameters. | includeServices | Array<[GattService](#gattservice)> | Yes | Yes | Services on which the service depends. | -## BLECharacteristic +## BLECharacteristic(deprecated) Defines the characteristic API parameters. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.BLECharacteristic](js-apis-bluetoothManager.md#blecharacteristic). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3378,10 +3357,13 @@ Defines the characteristic API parameters. | descriptors | Array<[BLEDescriptor](#bledescriptor)> | Yes | Yes | List of descriptors of the characteristic. | -## BLEDescriptor +## BLEDescriptor(deprecated) Defines the descriptor API parameters. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.BLEDescriptor](js-apis-bluetoothManager.md#bledescriptor). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3392,10 +3374,13 @@ Defines the descriptor API parameters. | descriptorValue | ArrayBuffer | Yes | Yes | Binary value of the descriptor. | -## NotifyCharacteristic +## NotifyCharacteristic(deprecated) Defines the parameters in the notifications sent when the server characteristic value changes. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.NotifyCharacteristic](js-apis-bluetoothManager.md#notifycharacteristic). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3406,10 +3391,13 @@ Defines the parameters in the notifications sent when the server characteristic | confirm | boolean | Yes | Yes | Whether the notification needs to be confirmed by the remote end. For a notification, set it to **true**. In this case, the remote end must confirm the receipt of the notification. For an indication, set it to **false**. In this case, the remote end does not need to confirm the receipt of the notification.| -## CharacteristicReadReq +## CharacteristicReadReq(deprecated) Defines the parameters of the **CharacteristicReadReq** event received by the server. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.CharacteristicReadRequest](js-apis-bluetoothManager.md#characteristicreadrequest). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3421,10 +3409,13 @@ Defines the parameters of the **CharacteristicReadReq** event received by the se | serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| -## CharacteristicWriteReq +## CharacteristicWriteReq(deprecated) Defines the parameters of the **CharacteristicWriteReq** event received by the server. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.CharacteristicWriteRequest](js-apis-bluetoothManager.md#characteristicwriterequest). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3437,10 +3428,13 @@ Defines the parameters of the **CharacteristicWriteReq** event received by the s | serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| -## DescriptorReadReq +## DescriptorReadReq(deprecated) Defines the parameters of the **DescriptorReadReq** event received by the server. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.DescriptorReadRequest](js-apis-bluetoothManager.md#descriptorreadrequest). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3453,10 +3447,13 @@ Defines the parameters of the **DescriptorReadReq** event received by the server | serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| -## DescriptorWriteReq +## DescriptorWriteReq(deprecated) Defines the parameters of the **DescriptorWriteReq** event received by the server. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.DescriptorWriteRequest](js-apis-bluetoothManager.md#descriptorwriterequest). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3472,10 +3469,13 @@ Defines the parameters of the **DescriptorWriteReq** event received by the serve | serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| -## ServerResponse +## ServerResponse(deprecated) Defines the parameters of the server's response to the GATT client's read/write request. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.ServerResponse](js-apis-bluetoothManager.md#serverresponse). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3487,10 +3487,13 @@ Defines the parameters of the server's response to the GATT client's read/write | value | ArrayBuffer | Yes | No | Binary data in the response. | -## BLEConnectChangedState +## BLEConnectChangedState(deprecated) Defines the parameters of **BLEConnectChangedState**. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.BLEConnectChangedState](js-apis-bluetoothManager.md#bleconnectchangedstate). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable| Writable| Description | @@ -3499,10 +3502,13 @@ Defines the parameters of **BLEConnectChangedState**. | state | [ProfileConnectionState](#profileconnectionstate) | Yes | Yes | BLE connection state. | -## ProfileConnectionState +## ProfileConnectionState(deprecated) Enumerates the profile connection states. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.ProfileConnectionState](js-apis-bluetoothManager.md#profileconnectionstate). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -3513,10 +3519,13 @@ Enumerates the profile connection states. | STATE_DISCONNECTING | 3 | Disconnecting.| -## ScanFilter +## ScanFilter(deprecated) Defines the scan filter parameters. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.ScanFilter](js-apis-bluetoothManager.md#scanfilter). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable| Writable| Description | @@ -3524,20 +3533,15 @@ Defines the scan filter parameters. | deviceId | string | Yes | Yes | Address of the BLE device to filter, for example, XX:XX:XX:XX:XX:XX. | | name | string | Yes | Yes | Name of the BLE device to filter. | | serviceUuid | string | Yes | Yes | Service UUID of the device to filter, for example, **00001888-0000-1000-8000-00805f9b34fb**.| -| serviceUuidMask9+ | string | Yes | Yes | Service UUID mask of the device to filter, for example, **FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF**.| -| serviceSolicitationUuid9+ | string | Yes | Yes | Service solicitation UUID of the device to filter, for example, **00001888-0000-1000-8000-00805F9B34FB**.| -| serviceSolicitationUuidMask9+ | string | Yes | Yes | Service solicitation UUID mask of the device to filter, for example, **FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF**.| -| serviceData9+ | ArrayBuffer | Yes | Yes | Service data of the device to filter, for example, **[0x90, 0x00, 0xF1, 0xF2]**.| -| serviceDataMask9+ | ArrayBuffer | Yes | Yes | Service data mask of the device to filter, for example, **[0xFF,0xFF,0xFF,0xFF]**.| -| manufactureId9+ | number | Yes | Yes | Manufacturer ID of the device to filter, for example, **0x0006**. | -| manufactureData9+ | ArrayBuffer | Yes | Yes | Manufacturer data of the device to filter, for example, **[0x1F,0x2F,0x3F]**.| -| manufactureDataMask9+ | ArrayBuffer | Yes | Yes | Manufacturer data mask of the device to filter, for example, **[0xFF, 0xFF, 0xFF]**.| -## ScanOptions +## ScanOptions(deprecated) Defines the scan configuration parameters. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.ScanOptions](js-apis-bluetoothManager.md#scanoptions). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3547,9 +3551,12 @@ Defines the scan configuration parameters. | matchMode | [MatchMode](#matchmode) | Yes | Yes | Hardware filtering match mode. The default value is **MATCH_MODE_AGGRESSIVE**.| -## ScanDuty +## ScanDuty(deprecated) -Enumerates the scan duty options. +Enumerates the scan modes. + +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.ScanDuty](js-apis-bluetoothManager.md#scanduty). **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3560,10 +3567,13 @@ Enumerates the scan duty options. | SCAN_MODE_LOW_LATENCY | 2 | Low-latency mode. | -## MatchMode +## MatchMode(deprecated) Enumerates the hardware match modes of BLE scan filters. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.MatchMode](js-apis-bluetoothManager.md#matchmode). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -3572,10 +3582,13 @@ Enumerates the hardware match modes of BLE scan filters. | MATCH_MODE_STICKY | 2 | Hardware reports the scan result with a higher threshold of signal strength and sightings. | -## ScanResult +## ScanResult(deprecated) Defines the scan result. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.ScanResult](js-apis-bluetoothManager.md#scanresult). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3585,10 +3598,13 @@ Defines the scan result. | data | ArrayBuffer | Yes | No | Advertisement packets sent by the device. | -## BluetoothState +## BluetoothState(deprecated) Enumerates the Bluetooth states. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.BluetoothState](js-apis-bluetoothManager.md#bluetoothstate). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -3602,10 +3618,13 @@ Enumerates the Bluetooth states. | STATE_BLE_TURNING_OFF | 6 | The LE-only mode is being turned off for Bluetooth.| -## AdvertiseSetting +## AdvertiseSetting(deprecated) Defines the BLE advertising parameters. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.AdvertiseSetting](js-apis-bluetoothManager.md#advertisesetting). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3615,10 +3634,13 @@ Defines the BLE advertising parameters. | connectable | boolean | Yes | Yes | Whether the advertisement is connectable. The default value is **true**. | -## AdvertiseData +## AdvertiseData(deprecated) Defines the content of a BLE advertisement packet. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.AdvertiseData](js-apis-bluetoothManager.md#advertisedata). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3628,10 +3650,13 @@ Defines the content of a BLE advertisement packet. | serviceData | Array<[ServiceData](#servicedata)> | Yes | Yes | List of service data to broadcast. | -## ManufactureData +## ManufactureData(deprecated) Defines the content of a BLE advertisement packet. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.ManufactureData](js-apis-bluetoothManager.md#manufacturedata). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3640,10 +3665,13 @@ Defines the content of a BLE advertisement packet. | manufactureValue | ArrayBuffer | Yes | Yes | Manufacturer data. | -## ServiceData +## ServiceData(deprecated) Defines the service data contained in an advertisement packet. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.ServiceData](js-apis-bluetoothManager.md#servicedata). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3652,10 +3680,13 @@ Defines the service data contained in an advertisement packet. | serviceValue | ArrayBuffer | Yes | Yes | Service data. | -## PinRequiredParam8+ +## PinRequiredParam8+(deprecated) Defines the pairing request parameters. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.PinRequiredParam](js-apis-bluetoothManager.md#pinrequiredparam). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3664,10 +3695,13 @@ Defines the pairing request parameters. | pinCode | string | Yes | No | Key for the device pairing. | -## BondStateParam8+ +## BondStateParam8+(deprecated) Defines the pairing state parameters. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.BondStateParam](js-apis-bluetoothManager.md#bondstateparam). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3676,10 +3710,13 @@ Defines the pairing state parameters. | state | BondState | Yes | No | State of the device.| -## StateChangeParam8+ +## StateChangeParam8+(deprecated) Defines the profile state change parameters. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.StateChangeParam](js-apis-bluetoothManager.md#statechangeparam). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable| Writable| Description | @@ -3688,10 +3725,13 @@ Defines the profile state change parameters. | state | [ProfileConnectionState](#profileconnectionstate) | Yes | No | Profile connection state of the device.| -## DeviceClass8+ +## DeviceClass8+(deprecated) Defines the class of a Bluetooth device. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.DeviceClass](js-apis-bluetoothManager.md#deviceclass). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -3702,10 +3742,13 @@ Defines the class of a Bluetooth device. -## MajorClass8+ +## MajorClass8+(deprecated) Enumerates the major classes of Bluetooth devices. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.MajorClass](js-apis-bluetoothManager.md#majorclass). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -3723,10 +3766,13 @@ Enumerates the major classes of Bluetooth devices. | MAJOR_UNCATEGORIZED | 0x1F00 | Unclassified device. | -## MajorMinorClass8+ +## MajorMinorClass8+(deprecated) Enumerates the major and minor classes of Bluetooth devices. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.MajorMinorClass](js-apis-bluetoothManager.md#majorminorclass). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -3819,10 +3865,13 @@ Enumerates the major and minor classes of Bluetooth devices. | HEALTH_PERSONAL_MOBILITY_DEVICE | 0x093C | Personal mobility device. | -## PlayingState8+ +## PlayingState8+(deprecated) Enumerates the A2DP playing states. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.PlayingState](js-apis-bluetoothManager.md#playingstate). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -3831,9 +3880,12 @@ Enumerates the A2DP playing states. | STATE_PLAYING | 0x0001 | Playing.| -## ProfileId8+ +## ProfileId8+(deprecated) + +Enumerates Bluetooth profiles. API version 9 is added with **PROFILE_HID_HOST** and **PROFILE_PAN_NETWORK**. -Enumerates the Bluetooth profiles. API version 9 is added with **PROFILE_HID_HOST** and **PROFILE_PAN_NETWORK**. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.ProfileId](js-apis-bluetoothManager.md#profileid). **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3841,5 +3893,3 @@ Enumerates the Bluetooth profiles. API version 9 is added with **PROFILE_HID_HOS | -------------------------------- | ------ | --------------- | | PROFILE_A2DP_SOURCE | 1 | A2DP profile.| | PROFILE_HANDS_FREE_AUDIO_GATEWAY | 4 | HFP profile. | -| PROFILE_HID_HOST9+ | 6 | Human Interface Device (HID) profile. | -| PROFILE_PAN_NETWORK9+ | 7 | PAN profile. | diff --git a/en/application-dev/reference/apis/js-apis-bluetoothManager.md b/en/application-dev/reference/apis/js-apis-bluetoothManager.md new file mode 100644 index 0000000000000000000000000000000000000000..db86d9ff8af8ef2c85cdffa344eaf2e6061aada0 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bluetoothManager.md @@ -0,0 +1,4491 @@ +# @ohos.bluetoothManager (Bluetooth) + +The **Bluetooth** module provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. + +> **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 bluetoothManager from '@ohos.bluetoothManager'; +``` + + +## bluetoothManager.enableBluetooth + +enableBluetooth(): void + +Enables Bluetooth. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + bluetoothManager.enableBluetooth(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.disableBluetooth + +disableBluetooth(): void + +Disables Bluetooth. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + bluetoothManager.disableBluetooth(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.getLocalName + +getLocalName(): string + +Obtains the name of the local Bluetooth device. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| ------ | --------- | +| string | Name of the local Bluetooth device obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let localName = bluetoothManager.getLocalName(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.getState + +getState(): BluetoothState + +Obtains the Bluetooth state. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| --------------------------------- | --------- | +| [BluetoothState](#bluetoothstate) | Bluetooth state obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let state = bluetoothManager.getState(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.getBtConnectionState + +getBtConnectionState(): ProfileConnectionState + +Obtains the profile connection state of this Bluetooth device. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------- | +| [ProfileConnectionState](#profileconnectionstate) | Profile connection state obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let connectionState = bluetoothManager.getBtConnectionState(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.setLocalName + +setLocalName(name: string): void + +Sets the name of the local Bluetooth device. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------------------- | +| name | string | Yes | Bluetooth device name to set. It cannot exceed 248 bytes.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + bluetoothManager.setLocalName('device_name'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.pairDevice + +pairDevice(deviceId: string): void + +Initiates Bluetooth pairing. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----------------------------------- | +| deviceId | string | Yes | Address of the remote device to pair, for example, XX:XX:XX:XX:XX:XX.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + // The address can be scanned. + bluetoothManager.pairDevice("XX:XX:XX:XX:XX:XX"); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.getProfileConnectionState + +getProfileConnectionState(profileId: ProfileId): ProfileConnectionState + +Obtains the connection state of a profile. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | --------- | ---- | ------------------------------------- | +| ProfileId | profileId | Yes | ID of the profile to obtain, for example, **PROFILE_A2DP_SOURCE**.| + +**Return value** + +| Type | Description | +| ------------------------------------------------- | ------------------- | +| [ProfileConnectionState](#profileconnectionstate) | Profile connection state obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let result = bluetoothManager.getProfileConnectionState(bluetoothManager.ProfileId.PROFILE_A2DP_SOURCE); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.cancelPairedDevice + +cancelPairedDevice(deviceId: string): void + +Cancels a paired remote device. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------------------------------- | +| deviceId | string | Yes | Address of the remote device to cancel, for example, XX:XX:XX:XX:XX:XX.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + bluetoothManager.cancelPairedDevice("XX:XX:XX:XX:XX:XX"); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.getRemoteDeviceName + +getRemoteDeviceName(deviceId: string): string + +Obtains the name of the remote Bluetooth device. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | --------------------------------- | +| deviceId | string | Yes | Address of the target remote device, for example, XX:XX:XX:XX:XX:XX.| + +**Return value** + +| Type | Description | +| ------ | ------------- | +| string | Device name (a string) obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let remoteDeviceName = bluetoothManager.getRemoteDeviceName("XX:XX:XX:XX:XX:XX"); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.getRemoteDeviceClass + +getRemoteDeviceClass(deviceId: string): DeviceClass + +Obtains the class of the remote Bluetooth device. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | --------------------------------- | +| deviceId | string | Yes | Address of the target remote device, for example, XX:XX:XX:XX:XX:XX.| + +**Return value** + +| Type | Description | +| --------------------------- | -------- | +| [DeviceClass](#deviceclass) | Class of the remote device obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let remoteDeviceClass = bluetoothManager.getRemoteDeviceClass("XX:XX:XX:XX:XX:XX"); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.getPairedDevices + +getPairedDevices(): Array<string> + +Obtains the paired devices. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Array<string> | Addresses of the paired Bluetooth devices.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let devices = bluetoothManager.getPairedDevices(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.setBluetoothScanMode + +setBluetoothScanMode(mode: ScanMode, duration: number): void + +Sets the Bluetooth scan mode so that the device can be discovered by a remote device. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | ---------------------------- | +| mode | [ScanMode](#scanmode) | Yes | Bluetooth scan mode to set. | +| duration | number | Yes | Duration (in ms) in which the device can be discovered. The value **0** indicates unlimited time.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + // The device can be discovered and connected only when the discoverable and connectable mode is used. + bluetoothManager.setBluetoothScanMode(bluetoothManager.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 100); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.getBluetoothScanMode + +getBluetoothScanMode(): ScanMode + +Obtains the Bluetooth scan mode. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| --------------------- | ------- | +| [ScanMode](#scanmode) | Bluetooth scan mode to set.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let scanMode = bluetoothManager.getBluetoothScanMode(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.startBluetoothDiscovery + +startBluetoothDiscovery(): void + +Starts Bluetooth scan to discover remote devices. + +**Rquired permissions**: ohos.permission.DISCOVER_BLUETOOTH and ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +let deviceId; +function onReceiveEvent(data) { + deviceId = data; +} +try { + bluetoothManager.on('bluetoothDeviceFind', onReceiveEvent); + bluetoothManager.startBluetoothDiscovery(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.stopBluetoothDiscovery + +stopBluetoothDiscovery(): void + +Stops Bluetooth scan. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + bluetoothManager.stopBluetoothDiscovery(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.setDevicePairingConfirmation + +setDevicePairingConfirmation(device: string, accept: boolean): void + +Sets the device pairing confirmation. + +**Required permissions**: ohos.permission.MANAGE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------- | ---- | -------------------------------- | +| device | string | Yes | Address of the remote device, for example, XX:XX:XX:XX:XX:XX.| +| accept | boolean | Yes | Whether to accept the pairing request. The value **true** means to accept the pairing request, and the value **false** means the opposite. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js + +try { + // Subscribe to the pinRequired event and configure the pairing confirmation after receiving a pairing request from the remote device. + function onReceivePinRequiredEvent(data) { // data is the input parameter for the pairing request. + console.info('pin required = '+ JSON.stringify(data)); + bluetoothManager.setDevicePairingConfirmation(data.deviceId, true); + } + bluetoothManager.on("pinRequired", onReceivePinRequiredEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.on('bluetoothDeviceFind') + +on(type: "bluetoothDeviceFind", callback: Callback<Array<string>>): void + +Subscribes to the Bluetooth device discovery events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | -------------------------------------- | +| type | string | Yes | Event type. The value **bluetoothDeviceFind** indicates an event reported when a Bluetooth device is discovered.| +| callback | Callback<Array<string>> | Yes | Callback invoked to return the discovered devices. You need to implement this callback. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { // data is a set of Bluetooth device addresses. + console.info('bluetooth device find = '+ JSON.stringify(data)); +} +try { + bluetoothManager.on('bluetoothDeviceFind', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.off('bluetoothDeviceFind') + +off(type: "bluetoothDeviceFind", callback?: Callback<Array<string>>): void + +Unsubscribes from the Bluetooth device discovery events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **bluetoothDeviceFind** indicates an event reported when a Bluetooth device is discovered. | +| callback | Callback<Array<string>> | No | Callback for the **bluetoothDeviceFind** event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('bluetooth device find = '+ JSON.stringify(data)); +} +try { + bluetoothManager.on('bluetoothDeviceFind', onReceiveEvent); + bluetoothManager.off('bluetoothDeviceFind', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.on('pinRequired') + +on(type: "pinRequired", callback: Callback<PinRequiredParam>): void + +Subscribes to the pairing request events of the remote Bluetooth device. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------------------------------- | +| type | string | Yes | Event type. The value **pinRequired** indicates a pairing request event. | +| callback | Callback<[PinRequiredParam](#pinrequiredparam)> | Yes | Callback invoked to return the pairing request. You need to implement this callback.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { // data is the pairing request parameter. + console.info('pin required = '+ JSON.stringify(data)); +} +try { + bluetoothManager.on('pinRequired', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.off('pinRequired') + +off(type: "pinRequired", callback?: Callback<PinRequiredParam>): void + +Unsubscribes from the pairing request events of the remote Bluetooth device. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **pinRequired** indicates a pairing request event. | +| callback | Callback<[PinRequiredParam](#pinrequiredparam)> | No | Callback for the Bluetooth pairing request event. The input parameter is the pairing request parameter. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('pin required = '+ JSON.stringify(data)); +} +try { + bluetoothManager.on('pinRequired', onReceiveEvent); + bluetoothManager.off('pinRequired', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.on('bondStateChange') + +on(type: "bondStateChange", callback: Callback<BondStateParam>): void + +Subscribes to the Bluetooth pairing state change events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------------ | +| type | string | Yes | Event type. The value **bondStateChange** indicates a Bluetooth pairing state change event.| +| callback | Callback<[BondStateParam](#BondStateParam)> | Yes | Callback invoked to return the pairing state. You need to implement this callback. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { // data, as the input parameter of the callback, indicates the pairing state. + console.info('pair state = '+ JSON.stringify(data)); +} +try { + bluetoothManager.on('bondStateChange', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.off('bondStateChange') + +off(type: "bondStateChange", callback?: Callback<BondStateParam>): void + +Unsubscribes from the Bluetooth pairing state change events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **bondStateChange** indicates a Bluetooth pairing state change event. | +| callback | Callback<[BondStateParam](#BondStateParam)> | No | Callback for the change of the Bluetooth pairing state. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('bond state = '+ JSON.stringify(data)); +} +try { + bluetoothManager.on('bondStateChange', onReceiveEvent); + bluetoothManager.off('bondStateChange', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.on('stateChange') + +on(type: "stateChange", callback: Callback<BluetoothState>): void + +Subscribes to the Bluetooth connection state change events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------------------------------- | +| type | string | Yes | Event type. The value **stateChange** indicates a Bluetooth connection state change event. | +| callback | Callback<[BluetoothState](#bluetoothstate)> | Yes | Callback invoked to return the Bluetooth connection state. You need to implement this callback.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('bluetooth state = '+ JSON.stringify(data)); +} +try { + bluetoothManager.on('stateChange', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.off('stateChange') + +off(type: "stateChange", callback?: Callback<BluetoothState>): void + +Unsubscribes from the Bluetooth connection state change events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **stateChange** indicates a Bluetooth connection state change event. | +| callback | Callback<[BluetoothState](#bluetoothstate)> | No | Callback for the Bluetooth connection state change event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('bluetooth state = '+ JSON.stringify(data)); +} +try { + bluetoothManager.on('stateChange', onReceiveEvent); + bluetoothManager.off('stateChange', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.sppListen + +sppListen(name: string, option: SppOption, callback: AsyncCallback<number>): void + +Creates a server listening socket. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ----------------------- | +| name | string | Yes | Name of the service. | +| option | [SppOption](#sppoption) | Yes | Serial port profile (SPP) listening configuration. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the server socket ID.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +let serverNumber = -1; +function serverSocket(code, number) { + console.log('bluetooth error code: ' + code.code); + if (code.code == 0) { + console.log('bluetooth serverSocket Number: ' + number); + serverNumber = number; + } +} + +let sppOption = {uuid: '00001810-0000-1000-8000-00805F9B34FB', secure: false, type: 0}; +try { + bluetoothManager.sppListen('server1', sppOption, serverSocket); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.sppAccept + +sppAccept(serverSocket: number, callback: AsyncCallback<number>): void + +Listens for a connection to be made to this socket from the client and accepts it. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------ | --------------------------- | ---- | ----------------------- | +| serverSocket | number | Yes | Server socket ID. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the client socket ID.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +let serverNumber = -1; +function serverSocket(code, number) { + console.log('bluetooth error code: ' + code.code); + if (code.code == 0) { + console.log('bluetooth serverSocket Number: ' + number); + serverNumber = number; + } +} +let clientNumber = -1; +function acceptClientSocket(code, number) { + console.log('bluetooth error code: ' + code.code); + if (code.code == 0) { + console.log('bluetooth clientSocket Number: ' + number); + // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the server. + clientNumber = number; + } +} +try { + bluetoothManager.sppAccept(serverNumber, acceptClientSocket); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.sppConnect + +sppConnect(device: string, option: SppOption, callback: AsyncCallback<number>): void + +Initiates an SPP connection to a remote device from the client. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------------ | +| device | string | Yes | Address of the remote device, for example, XX:XX:XX:XX:XX:XX.| +| option | [SppOption](#sppoption) | Yes | Configuration for connecting to the SPP client. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the client socket ID. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js + +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client. + clientNumber = number; +} +let sppOption = {uuid: '00001810-0000-1000-8000-00805F9B34FB', secure: false, type: 0}; +try { + bluetoothManager.sppConnect('XX:XX:XX:XX:XX:XX', sppOption, clientSocket); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.sppCloseServerSocket + +sppCloseServerSocket(socket: number): void + +Closes the listening socket of the server. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------- | +| socket | number | Yes | ID of the listening socket on the server. The ID is obtained by **sppListen**.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +let serverNumber = -1; +function serverSocket(code, number) { + console.log('bluetooth error code: ' + code.code); + if (code.code == 0) { + console.log('bluetooth serverSocket Number: ' + number); + serverNumber = number; + } +} +try { + bluetoothManager.sppCloseServerSocket(serverNumber); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.sppCloseClientSocket + +sppCloseClientSocket(socket: number): void + +Closes the client socket. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------------- | +| Name | Type | Mandatory | Description | +| socket | number | Yes | Client socket ID, which is obtained by **sppAccept** or **sppConnect**.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client. + clientNumber = number; +} +try { + bluetoothManager.sppCloseClientSocket(clientNumber); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.sppWrite + +sppWrite(clientSocket: number, data: ArrayBuffer): void + +Writes data to the remote device through the socket. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------ | ----------- | ---- | ------------- | +| clientSocket | number | Yes | Client socket ID, which is obtained by **sppAccept** or **sppConnect**.| +| data | ArrayBuffer | Yes | Data to write. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2901054 | IO error. | +|2900099 | Operation failed. | + +**Example** + +```js +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client. + clientNumber = number; +} +let arrayBuffer = new ArrayBuffer(8); +let data = new Uint8Array(arrayBuffer); +data[0] = 123; +try { + bluetoothManager.sppWrite(clientNumber, arrayBuffer); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.on('sppRead') + +on(type: "sppRead", clientSocket: number, callback: Callback<ArrayBuffer>): void + +Subscribes to the SPP read request events. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------ | --------------------------- | ---- | -------------------------- | +| type | string | Yes | Event type. The value **sppRead** indicates an SPP read request event.| +| clientSocket | number | Yes | Client socket ID, which is obtained by **sppAccept** or **sppConnect**. | +| callback | Callback<ArrayBuffer> | Yes | Callback invoked to return the data read. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2901054 | IO error. | +|2900099 | Operation failed. | + +**Example** + +```js +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client. + clientNumber = number; +} +function dataRead(dataBuffer) { + let data = new Uint8Array(dataBuffer); + console.log('bluetooth data is: ' + data[0]); +} +try { + bluetoothManager.on('sppRead', clientNumber, dataRead); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.off('sppRead') + +off(type: "sppRead", clientSocket: number, callback?: Callback<ArrayBuffer>): void + +Unsubscribes from the SPP read request events. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------ | --------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **sppRead** indicates an SPP read request event. | +| clientSocket | number | Yes | Client socket ID, which is obtained by **sppAccept** or **sppConnect**. | +| callback | Callback<ArrayBuffer> | No | Callback for the SPP read request event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| + +**Example** + +```js +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client. + clientNumber = number; +} +try { + bluetoothManager.off('sppRead', clientNumber); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + +## bluetoothManager.getProfileInstance + +getProfileInstance(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile | HidHostProfile | PanProfile + +Obtains a profile instance. API version 9 is added with **HidHostProfile** and **PanProfile**. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | --------- | ---- | ------------------------------------- | +| profileId | [ProfileId](#ProfileId) | Yes | ID of the profile to obtain, for example, **PROFILE_A2DP_SOURCE**.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| [A2dpSourceProfile](#a2dpsourceprofile), [HandsFreeAudioGatewayProfile](#handsfreeaudiogatewayprofile), [HidHostProfile](#hidhostprofile), or [PanProfile](#panprofile)| Profile instance obtained, which can be **A2dpSourceProfile**, **HandsFreeAudioGatewayProfile**, **HidHostProfile**, or **PanProfile**.| + +**Example** + +```js +try { + let hidHost = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_HID_HOST); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## bluetoothManager.BLE + +### bluetoothManager.BLE.createGattServer + +createGattServer(): GattServer + +Creates a **GattServer** instance. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| ------------------------- | ------------------------------------ | +| [GattServer](#gattserver) | **GattServer** instance created. Before using a method of the server, you must create a **GattSever** instance.| + +**Example** + +```js +let gattServer = bluetoothManager.BLE.createGattServer(); +``` + + +### bluetoothManager.BLE.createGattClientDevice + +createGattClientDevice(deviceId: string): GattClientDevice + +Creates a **GattClientDevice** instance. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------------------------------ | +| deviceId | string | Yes | Address of the remote device, for example, XX:XX:XX:XX:XX:XX.| + +**Return value** + +| Type | Description | +| ------------------------------------- | ------------------------------------ | +| [GattClientDevice](#gattclientdevice) | **GattClientDevice** instance created. Before using a method of the client, you must create a **GattClientDevice** instance.| + +**Example** + +```js +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### bluetoothManager.BLE.getConnectedBLEDevices + +getConnectedBLEDevices(): Array<string> + +Obtains the BLE devices connected to this device. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------- | +| Array<string> | Addresses of the BLE devices connected to this device.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let result = bluetoothManager.BLE.getConnectedBLEDevices(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### bluetoothManager.BLE.startBLEScan + +startBLEScan(filters: Array<ScanFilter>, options?: ScanOptions): void + +Starts a BLE scan. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH, ohos.permission.MANAGE_BLUETOOTH, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | -------------------------------------- | ---- | ----------------------------------- | +| filters | Array<[ScanFilter](#scanfilter)> | Yes | Criteria for filtering the scan result. Set this parameter to **null** if you do not want to filter the scan result.| +| options | [ScanOptions](#scanoptions) | No | Scan options. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('BLE scan device find result = '+ JSON.stringify(data)); +} +try { + bluetoothManager.BLE.on("BLEDeviceFind", onReceiveEvent); + bluetoothManager.BLE.startBLEScan( + [{ + deviceId:"XX:XX:XX:XX:XX:XX", + name:"test", + serviceUuid:"00001888-0000-1000-8000-00805f9b34fb" + }], + { + interval: 500, + dutyMode: bluetoothManager.ScanDuty.SCAN_MODE_LOW_POWER, + matchMode: bluetoothManager.MatchMode.MATCH_MODE_AGGRESSIVE, + } + ); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### bluetoothManager.BLE.stopBLEScan + +stopBLEScan(): void + +Stops the BLE scan. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + bluetoothManager.BLE.stopBLEScan(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### bluetoothManager.BLE.on('BLEDeviceFind') + +on(type: "BLEDeviceFind", callback: Callback<Array<ScanResult>>): void + +Subscribe to the BLE device discovery events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------------------------- | +| type | string | Yes | Event type. The value **BLEDeviceFind** indicates an event reported when a BLE device is discovered. | +| callback | Callback<Array<[ScanResult](#scanresult)>> | Yes | Callback invoked to return the discovered devices. You need to implement this callback.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('bluetooth device find = '+ JSON.stringify(data)); +} +try { + bluetoothManager.BLE.on('BLEDeviceFind', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### bluetoothManager.BLE.off('BLEDeviceFind') + +off(type: "BLEDeviceFind", callback?: Callback<Array<ScanResult>>): void + +Unsubscribes from the BLE device discovery events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **BLEDeviceFind** indicates an event reported when a BLE device is discovered. | +| callback | Callback<Array<[ScanResult](#scanresult)>> | No | Callback for the **BLEDeviceFind** event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('bluetooth device find = '+ JSON.stringify(data)); +} +try { + bluetoothManager.BLE.on('BLEDeviceFind', onReceiveEvent); + bluetoothManager.BLE.off('BLEDeviceFind', onReceiveEvent); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## BaseProfile + +Provides the profile base class. + + +### getConnectionDevices + +getConnectionDevices(): Array<string> + +Obtains the connected devices. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Array<string> | Addresses of the connected devices.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let a2dpSrc = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_A2DP_SOURCE) as bluetoothManager.A2dpSourceProfile; + let retArray = a2dpSrc.getConnectionDevices(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + +### getDeviceState + +getDeviceState(device: string): ProfileConnectionState + +Obtains the connection state of the profile. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| device | string | Yes | Address of the target device.| + +**Return value** + +| Type | Description | +| ------------------------------------------------- | ----------------------- | +| [ProfileConnectionState](#profileconnectionstate) | Profile connection state obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let a2dpSrc = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_A2DP_SOURCE) as bluetoothManager.A2dpSourceProfile; + let ret = a2dpSrc.getDeviceState('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + +## A2dpSourceProfile + +Before using a method of **A2dpSourceProfile**, you need to create an instance of this class by using the **getProfile()** method. + + +### connect + +connect(device: string): void + +Sets up an Advanced Audio Distribution Profile (A2DP) connection. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| device | string | Yes | Address of the target device.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let a2dpSrc = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_A2DP_SOURCE) as bluetoothManager.A2dpSourceProfile; + a2dpSrc.connect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### disconnect + +disconnect(device: string): void + +Disconnects an A2DP connection. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| device | string | Yes | Address of the target device.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let a2dpSrc = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_A2DP_SOURCE) as bluetoothManager.A2dpSourceProfile; + a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### on('connectionStateChange') + +on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void + +Subscribes to the A2DP connection state change events. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **connectionStateChange** indicates an A2DP connection state change event.| +| callback | Callback<[StateChangeParam](#StateChangeParam)> | Yes | Callback invoked to return the A2DP connection state change event. | + +**Return value** + +No value is returned. + +**Example** + +```js +function onReceiveEvent(data) { + console.info('a2dp state = '+ JSON.stringify(data)); +} +let a2dpSrc = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_A2DP_SOURCE) as bluetoothManager.A2dpSourceProfile; +a2dpSrc.on('connectionStateChange', onReceiveEvent); +``` + + +### off('connectionStateChange') + +off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void + +Unsubscribes from the A2DP connection state change events. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **connectionStateChange** indicates an A2DP connection state change event.| +| callback | Callback<[StateChangeParam](#StateChangeParam)> | No | Callback for the A2DP connection state change event. | + +**Return value** + +No value is returned. + +**Example** + +```js +function onReceiveEvent(data) { + console.info('a2dp state = '+ JSON.stringify(data)); +} +let a2dpSrc = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_A2DP_SOURCE) as bluetoothManager.A2dpSourceProfile; +a2dpSrc.on('connectionStateChange', onReceiveEvent); +a2dpSrc.off('connectionStateChange', onReceiveEvent); +``` + + +### getPlayingState + +getPlayingState(device: string): PlayingState + +Obtains the playing state of a device. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| device | string | Yes | Address of the target device.| + +**Return value** + +| Type | Description | +| ----------------------------- | ---------- | +| [PlayingState](#PlayingState) | Playing state of the remote device obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let a2dpSrc = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_A2DP_SOURCE) as bluetoothManager.A2dpSourceProfile; + let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## HandsFreeAudioGatewayProfile + +Before using a method of **HandsFreeAudioGatewayProfile**, you need to create an instance of this class by using the **getProfile()** method. + + +### connect + +connect(device: string): void + +Sets up a Hands-free Profile (HFP) connection of a device. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| device | string | Yes | Address of the target device.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let hfpAg = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as bluetoothManager.HandsFreeAudioGatewayProfile; + hfpAg.connect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### disconnect + +disconnect(device: string): void + +Disconnects the HFP connection of a device. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| device | string | Yes | Address of the target device.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let hfpAg = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as bluetoothManager.HandsFreeAudioGatewayProfile; + hfpAg.disconnect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### on('connectionStateChange') + +on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void + +Subscribes to the HFP connection state change events. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **connectionStateChange** indicates an HFP connection state change event.| +| callback | Callback<[StateChangeParam](#StateChangeParam)> | Yes | Callback invoked to return the HFP connection state change event. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('hfp state = '+ JSON.stringify(data)); +} +let hfpAg = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as + bluetoothManager.HandsFreeAudioGatewayProfile; +hfpAg.on('connectionStateChange', onReceiveEvent); +``` + + +### off('connectionStateChange') + +off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void + +Unsubscribes from the HFP connection state change events. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **connectionStateChange** indicates an HFP connection state change event.| +| callback | Callback<[StateChangeParam](#StateChangeParam)> | No | Callback for the HFP connection state change event. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('hfp state = '+ JSON.stringify(data)); +} +let hfpAg = bluetoothManager.getProfileInstance(bluetoothManager.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as + bluetoothManager.HandsFreeAudioGatewayProfile; +hfpAg.on('connectionStateChange', onReceiveEvent); +hfpAg.off('connectionStateChange', onReceiveEvent); +``` + + +## HidHostProfile + +Before using an API of **HidHostProfile**, you need to create an instance of this class by using **getProfile()**. + + +### connect + +connect(device: string): void + +Connects to the HidHost service of a device. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| device | string | Yes | Address of the target device.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let hidHostProfile = bluetoothManager.getProfileInst(bluetoothManager.ProfileId.PROFILE_HID_HOST) as bluetoothManager.HidHostProfile; + hidHostProfile.connect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### disconnect + +disconnect(device: string): void + +Disconnects from the HidHost service of a device. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| device | string | Yes | Address of the target device.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let hidHostProfile = bluetoothManager.getProfileInst(bluetoothManager.ProfileId.PROFILE_HID_HOST) as bluetoothManager.HidHostProfile; + hidHostProfile.disconnect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### on('connectionStateChange') + +on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void + +Subscribes to the HidHost connection state change events. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **connectionStateChange** indicates a HidHost connection state change event.| +| callback | Callback<[StateChangeParam](#StateChangeParam)> | Yes | Callback invoked to return the HidHost connection state change event. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('hidHost state = '+ JSON.stringify(data)); +} +let hidHost = bluetoothManager.getProfileInst(bluetoothManager.ProfileId.PROFILE_HID_HOST) as bluetoothManager.HidHostProfile; +hidHost.on('connectionStateChange', onReceiveEvent); +``` + + +### off('connectionStateChange') + +off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void + +Unsubscribes from the HidHost connection state change events. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | --------------------------------------------------------- | +| type | string | Yes | Event type. The value **connectionStateChange** indicates a HidHost connection state change event.| +| callback | Callback<[StateChangeParam](#StateChangeParam)> | No | Callback for the HidHost connection state change event. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('hidHost state = '+ JSON.stringify(data)); +} +let hidHost = bluetoothManager.getProfileInst(bluetoothManager.ProfileId.PROFILE_HID_HOST) as bluetoothManager.HidHostProfile; +hidHost.on('connectionStateChange', onReceiveEvent); +hidHost.off('connectionStateChange', onReceiveEvent); +``` + + +## PanProfile + +Before using an API of **PanProfile**, you need to create an instance of this class by using **getProfile()**. + + +### disconnect + +disconnect(device: string): void + +Disconnects from the Personal Area Network (PAN) service of a device. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| device | string | Yes | Address of the target device.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let panProfile = bluetoothManager.getProfileInst(bluetoothManager.ProfileId.PROFILE_PAN_NETWORK) as bluetoothManager.PanProfile; + panProfile.disconnect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### on('connectionStateChange') + +on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void + +Subscribes to the PAN connection state change events. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **connectionStateChange** indicates an PAN connection state change event. | +| callback | Callback<[StateChangeParam](#StateChangeParam)> | Yes | Callback invoked to return the PAN connection state change event. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('pan state = '+ JSON.stringify(data)); +} +let panProfile = bluetoothManager.getProfileInst(bluetoothManager.ProfileId.PROFILE_PAN_NETWORK) as bluetoothManager.PanProfile; +panProfile.on('connectionStateChange', onReceiveEvent); +``` + + +### off('connectionStateChange') + +off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void + +Unsubscribes from the PAN connection state change events. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | --------------------------------------------------------- | +| type | string | Yes | Event type. The value **connectionStateChange** indicates a PAN connection state change event.| +| callback | Callback<[StateChangeParam](#StateChangeParam)> | No | Callback for the PAN connection state change event. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('pan state = '+ JSON.stringify(data)); +} +let panProfile = bluetoothManager.getProfileInst(bluetoothManager.ProfileId.PROFILE_PAN_NETWORK) as bluetoothManager.PanProfile; +panProfile.on('connectionStateChange', onReceiveEvent); +panProfile.off('connectionStateChange', onReceiveEvent); +``` + + +### setTethering + +setTethering(enable: boolean): void + +Sets tethering. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| value | boolean | Yes | Whether to set tethering over a Bluetooth PAN.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let panProfile = bluetoothManager.getProfileInst(bluetoothManager.ProfileId.PROFILE_PAN_NETWORK) as bluetoothManager.PanProfile; + panProfile.setTethering(true); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### isTetheringOn + +isTetheringOn(): boolean + +Obtains the network sharing status. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| --------------------- | --------------------------------- | +| boolean | Returns **true** if tethering is available over a Bluetooth PAN; return **false** otherwise.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let panProfile = bluetoothManager.getProfileInst(bluetoothManager.ProfileId.PROFILE_PAN_NETWORK) as bluetoothManager.PanProfile; + let ret = panProfile.isTetheringOn(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## GattServer + +Implements the Generic Attribute Profile (GATT) server. Before using an API of this class, you need to create a **GattServer** instance using the **createGattServer()** method. + + +### startAdvertising + +startAdvertising(setting: AdvertiseSetting, advData: AdvertiseData, advResponse?: AdvertiseData): void + +Starts BLE advertising. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------------------------------------- | ---- | -------------- | +| setting | [AdvertiseSetting](#advertisesetting) | Yes | Settings related to BLE advertising. | +| advData | [AdvertiseData](#advertisedata) | Yes | Content of the BLE advertisement packet. | +| advResponse | [AdvertiseData](#advertisedata) | No | Response to the BLE scan request.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +let manufactureValueBuffer = new Uint8Array(4); +manufactureValueBuffer[0] = 1; +manufactureValueBuffer[1] = 2; +manufactureValueBuffer[2] = 3; +manufactureValueBuffer[3] = 4; + +let serviceValueBuffer = new Uint8Array(4); +serviceValueBuffer[0] = 4; +serviceValueBuffer[1] = 6; +serviceValueBuffer[2] = 7; +serviceValueBuffer[3] = 8; +console.info('manufactureValueBuffer = '+ JSON.stringify(manufactureValueBuffer)); +console.info('serviceValueBuffer = '+ JSON.stringify(serviceValueBuffer)); +let gattServer = bluetoothManager.BLE.createGattServer(); +try { + gattServer.startAdvertising({ + interval:150, + txPower:60, + connectable:true, + },{ + serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], + manufactureData:[{ + manufactureId:4567, + manufactureValue:manufactureValueBuffer.buffer + }], + serviceData:[{ + serviceUuid:"00001888-0000-1000-8000-00805f9b34fb", + serviceValue:serviceValueBuffer.buffer + }], + },{ + serviceUuids:["00001889-0000-1000-8000-00805f9b34fb"], + manufactureData:[{ + manufactureId:1789, + manufactureValue:manufactureValueBuffer.buffer + }], + serviceData:[{ + serviceUuid:"00001889-0000-1000-8000-00805f9b34fb", + serviceValue:serviceValueBuffer.buffer + }], + }); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### stopAdvertising + +stopAdvertising(): void + +Stops BLE advertising. + +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +let server = bluetoothManager.BLE.createGattServer(); +try { + server.stopAdvertising(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### addService + +addService(service: GattService): void + +Adds a service to this GATT server. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | --------------------------- | ---- | ------------------------ | +| service | [GattService](#gattservice) | Yes | Service to add. Settings related to BLE advertising.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +// Create descriptors. +let descriptors = []; +let arrayBuffer = new ArrayBuffer(8); +let descV = new Uint8Array(arrayBuffer); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; +descriptors[0] = descriptor; + +// Create characteristics. +let characteristics = []; +let arrayBufferC = new ArrayBuffer(8); +let cccV = new Uint8Array(arrayBufferC); +cccV[0] = 1; +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; +let characteristicN = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; +characteristics[0] = characteristic; + +// Create a gattService instance. +let gattService = {serviceUuid:'00001810-0000-1000-8000-00805F9B34FB', isPrimary: true, characteristics:characteristics, includeServices:[]}; + +let gattServer = bluetoothManager.BLE.createGattServer(); +try { + gattServer.addService(gattService); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### removeService + +removeService(serviceUuid: string): void + +Removes a service from this GATT server. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | ---------------------------------------- | +| serviceUuid | string | Yes | Universally unique identifier (UUID) of the service to remove, for example, **00001810-0000-1000-8000-00805F9B34FB**.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +let server = bluetoothManager.BLE.createGattServer(); +try { + server.removeService('00001810-0000-1000-8000-00805F9B34FB'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### close + +close(): void + +Closes this GATT server to unregister it from the protocol stack. After this method is called, this [GattServer](#gattserver) cannot be used. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +let server = bluetoothManager.BLE.createGattServer(); +try { + server.close(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### notifyCharacteristicChanged + +notifyCharacteristicChanged(deviceId: string, notifyCharacteristic: NotifyCharacteristic): void + +Notifies the connected client device when a characteristic value changes. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ---------------------------------------- | ---- | --------------------------------------- | +| deviceId | string | Yes | Address of the client that receives notifications, for example, XX:XX:XX:XX:XX:XX.| +| notifyCharacteristic | [NotifyCharacteristic](#notifycharacteristic) | Yes | New characteristic value. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +// Create descriptors. +let descriptors = []; +let arrayBuffer = new ArrayBuffer(8); +let descV = new Uint8Array(arrayBuffer); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; +descriptors[0] = descriptor; +let arrayBufferC = new ArrayBuffer(8); +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; +let notifyCharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: characteristic.characteristicValue, confirm: false}; +let server = bluetoothManager.BLE.createGattServer(); +try { + server.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacteristic); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### sendResponse + +sendResponse(serverResponse: ServerResponse): void + +Sends a response to a read or write request from the GATT client. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | --------------------------------- | ---- | --------------- | +| serverResponse | [ServerResponse](#serverresponse) | Yes | Response returned by the GATT server.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +/* send response */ +let arrayBufferCCC = new ArrayBuffer(8); +let cccValue = new Uint8Array(arrayBufferCCC); +cccValue[0] = 1123; +let serverResponse = { + "deviceId": "XX:XX:XX:XX:XX:XX", + "transId": 0, + "status": 0, + "offset": 0, + "value": arrayBufferCCC, +}; + +let gattServer = bluetoothManager.BLE.createGattServer(); +try { + gattServer.sendResponse(serverResponse); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### on('characteristicRead') + +on(type: "characteristicRead", callback: Callback<CharacteristicReadRequest>): void + +Subscribes to the characteristic read request events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------------- | +| type | string | Yes | Event type. The value **characteristicRead** indicates a characteristic read request event.| +| callback | Callback<[CharacteristicReadRequest](#characteristicreadrequest)> | Yes | Callback invoked to return a characteristic read request event from the GATT client. | + +**Example** + +```js +let arrayBufferCCC = new ArrayBuffer(8); +let cccValue = new Uint8Array(arrayBufferCCC); +cccValue[0] = 1123; +function ReadCharacteristicReq(CharacteristicReadRequest) { + let deviceId = CharacteristicReadRequest.deviceId; + let transId = CharacteristicReadRequest.transId; + let offset = CharacteristicReadRequest.offset; + let characteristicUuid = CharacteristicReadRequest.characteristicUuid; + + let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC}; + + try { + gattServer.sendResponse(serverResponse); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } +} + +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.on("characteristicRead", ReadCharacteristicReq); +``` + + +### off('characteristicRead') + +off(type: "characteristicRead", callback?: Callback<CharacteristicReadRequest>): void + +Unsubscribes from the characteristic read request events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **characteristicRead** indicates a characteristic read request event. | +| callback | Callback<[CharacteristicReadRequest](#characteristicreadrequest)> | No | Callback for the characteristic read request event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| + +**Example** + +```js +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.off("characteristicRead"); +``` + + +### on('characteristicWrite') + +on(type: "characteristicWrite", callback: Callback<CharacteristicWriteRequest>): void + +Subscribes to the characteristic write request events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------------------------------------- | +| type | string | Yes | Event type. The value **characteristicWrite** indicates a characteristic write request event.| +| callback | Callback<[CharacteristicWriteRequest](#characteristicwriterequest)> | Yes | Callback invoked to return a characteristic write request from the GATT client. | + +**Example** + +```js +let arrayBufferCCC = new ArrayBuffer(8); +let cccValue = new Uint8Array(arrayBufferCCC); +function WriteCharacteristicReq(CharacteristicWriteRequest) { + let deviceId = CharacteristicWriteRequest.deviceId; + let transId = CharacteristicWriteRequest.transId; + let offset = CharacteristicWriteRequest.offset; + let isPrep = CharacteristicWriteRequest.isPrep; + let needRsp = CharacteristicWriteRequest.needRsp; + let value = new Uint8Array(CharacteristicWriteRequest.value); + let characteristicUuid = CharacteristicWriteRequest.characteristicUuid; + + cccValue[0] = value[0]; + let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC}; + + try { + gattServer.sendResponse(serverResponse); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } +} + +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.on("characteristicWrite", WriteCharacteristicReq); +``` + + +### off('characteristicWrite') + +off(type: "characteristicWrite", callback?: Callback<CharacteristicWriteRequest>): void + +Unsubscribes from the characteristic write request events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **characteristicWrite** indicates a characteristic write request event. | +| callback | Callback<[CharacteristicWriteRequest](#characteristicwriterequest)> | No | Callback for the characteristic write request event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| + +**Example** + +```js +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.off("characteristicWrite"); +``` + + +### on('descriptorRead') + +on(type: "descriptorRead", callback: Callback<DescriptorReadRequest>): void + +Subscribes to the descriptor read request events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------------- | +| type | string | Yes | Event type. The value **descriptorRead** indicates a descriptor read request event.| +| callback | Callback<[DescriptorReadRequest](#descriptorreadrequest)> | Yes | Callback invoked to return a characteristic read request event from the GATT client. | + +**Example** + +```js +let arrayBufferDesc = new ArrayBuffer(8); +let descValue = new Uint8Array(arrayBufferDesc); +descValue[0] = 1101; +function ReadDescriptorReq(DescriptorReadRequest) { + let deviceId = DescriptorReadRequest.deviceId; + let transId = DescriptorReadRequest.transId; + let offset = DescriptorReadRequest.offset; + let descriptorUuid = DescriptorReadRequest.descriptorUuid; + + let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc}; + + try { + gattServer.sendResponse(serverResponse); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } +} + +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.on("descriptorRead", ReadDescriptorReq); +``` + + +### off('descriptorRead') + +off(type: "descriptorRead", callback?: Callback<DescriptorReadRequest>): void + +Unsubscribes from the descriptor read request events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **descriptorRead** indicates a descriptor read request event. | +| callback | Callback<[DescriptorReadRequest](#descriptorreadrequest)> | No | Callback for the descriptor read request event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| + +**Example** + +```js +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.off("descriptorRead"); +``` + + +### on('descriptorWrite') + +on(type: "descriptorWrite", callback: Callback<DescriptorWriteRequest>): void + +Subscribes to the descriptor write request events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------- | +| type | string | Yes | Event type. The value **descriptorWrite** indicates a descriptor write request event.| +| callback | Callback<[DescriptorWriteRequest](#descriptorwriterequest)> | Yes | Callback invoked to return a descriptor write request from the GATT client. | + +**Example** + +```js +let arrayBufferDesc = new ArrayBuffer(8); +let descValue = new Uint8Array(arrayBufferDesc); +function WriteDescriptorReq(DescriptorWriteRequest) { + let deviceId = DescriptorWriteRequest.deviceId; + let transId = DescriptorWriteRequest.transId; + let offset = DescriptorWriteRequest.offset; + let isPrep = DescriptorWriteRequest.isPrep; + let needRsp = DescriptorWriteRequest.needRsp; + let value = new Uint8Array(DescriptorWriteRequest.value); + let descriptorUuid = DescriptorWriteRequest.descriptorUuid; + + descValue[0] = value[0]; + let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc}; + + try { + gattServer.sendResponse(serverResponse); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } +} + +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.on("descriptorRead", WriteDescriptorReq); +``` + + +### off('descriptorWrite') + +off(type: "descriptorWrite", callback?: Callback<DescriptorWriteRequest>): void + +Unsubscribes from the descriptor write request events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **descriptorWrite** indicates a descriptor write request event. | +| callback | Callback<[DescriptorWriteRequest](#descriptorwriterequest)> | No | Callback for the descriptor write request event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| + +**Example** + +```js +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.off("descriptorWrite"); +``` + + +### on('connectStateChange') + +on(type: "connectStateChange", callback: Callback<BLEConnectChangedState>): void + +Subscribes to the BLE connection state change events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **connectStateChange** indicates a BLE connection state change event.| +| callback | Callback<[BLEConnectChangedState](#bleconnectchangedstate)> | Yes | Callback invoked to return the BLE connection state. | + +**Example** + +```js +function Connected(BLEConnectChangedState) { + let deviceId = BLEConnectChangedState.deviceId; + let status = BLEConnectChangedState.state; +} + +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.on("connectStateChange", Connected); +``` + + +### off('connectStateChange') + +off(type: "connectStateChange", callback?: Callback<BLEConnectChangedState>): void + +Unsubscribes from the BLE connection state change events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **connectStateChange** indicates a BLE connection state change event.| +| callback | Callback<[BLEConnectChangedState](#bleconnectchangedstate)> | No | Callback for the BLE connection state change event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| + +**Example** + +```js +let gattServer = bluetoothManager.BLE.createGattServer(); +gattServer.off("connectStateChange"); +``` + + +## GattClientDevice + +Implements the GATT client. Before using an API of this class, you must create a **GattClientDevice** instance using **createGattClientDevice(deviceId: string)**. + + +### connect + +connect(): void + +Initiates a connection to the remote BLE device. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.connect(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### disconnect + +disconnect(): void + +Disconnects from the remote BLE device. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.disconnect(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### close + +close(): void + +Closes this GATT client to unregister it from the protocol stack. After this API is called, this [GattClientDevice](#gattclientdevice) instance cannot be used. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.close(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + + + +### getServices + +getServices(callback: AsyncCallback<Array<GattService>>): void + +Obtains all services of the remote BLE device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<Array<[GattService](#gattservice)>> | Yes | Callback invoked to return the services obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +// Callback +function getServices(code, gattServices) { + if (code.code == 0) { + let services = gattServices; + console.log('bluetooth code is ' + code.code); + console.log("bluetooth services size is ", services.length); + + for (let i = 0; i < services.length; i++) { + console.log('bluetooth serviceUuid is ' + services[i].serviceUuid); + } + } +} + +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.connect(); + device.getServices(getServices); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### getServices + +getServices(): Promise<Array<GattService>> + +Obtains all services of the remote BLE device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | --------------------------- | +| Promise<Array<[GattService](#gattservice)>> | Promise used to return the services obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +// Promise +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.connect(); + device.getServices().then(result => { + console.info("getServices successfully:" + JSON.stringify(result)); + }); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### readCharacteristicValue + +readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback<BLECharacteristic>): void + +Reads the characteristic value of the specific service of the remote BLE device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------- | ---- | ----------------------- | +| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | Characteristic value to read. | +| callback | AsyncCallback<[BLECharacteristic](#blecharacteristic)> | Yes | Callback invoked to return the characteristic value read.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901000 | Read forbidden. | +|2900099 | Operation failed. | + +**Example** + +```js +function readCcc(code, BLECharacteristic) { + if (code.code != 0) { + return; + } + console.log('bluetooth characteristic uuid: ' + BLECharacteristic.characteristicUuid); + let value = new Uint8Array(BLECharacteristic.characteristicValue); + console.log('bluetooth characteristic value: ' + value[0] +','+ value[1]+','+ value[2]+','+ value[3]); +} + +let descriptors = []; +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', +characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', +descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; +descriptors[0] = descriptor; + +let bufferCCC = new ArrayBuffer(8); +let cccV = new Uint8Array(bufferCCC); +cccV[0] = 1; +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', +characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', +characteristicValue: bufferCCC, descriptors:descriptors}; + +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.readCharacteristicValue(characteristic, readCcc); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### readCharacteristicValue + +readCharacteristicValue(characteristic: BLECharacteristic): Promise<BLECharacteristic> + +Reads the characteristic value of the specific service of the remote BLE device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | --------------------------------------- | ---- | -------- | +| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | Characteristic value to read.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | -------------------------- | +| Promise<[BLECharacteristic](#blecharacteristic)> | Promise used to return the characteristic value read.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901000 | Read forbidden. | +|2900099 | Operation failed. | + +**Example** + +```js +let descriptors = []; +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', +characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', +descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; +descriptors[0] = descriptor; + +let bufferCCC = new ArrayBuffer(8); +let cccV = new Uint8Array(bufferCCC); +cccV[0] = 1; +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', +characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', +characteristicValue: bufferCCC, descriptors:descriptors}; + +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.readCharacteristicValue(characteristic); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### readDescriptorValue + +readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<BLEDescriptor>): void + +Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------------------- | ---- | ----------------------- | +| descriptor | [BLEDescriptor](#bledescriptor) | Yes | Descriptor to read. | +| callback | AsyncCallback<[BLEDescriptor](#bledescriptor)> | Yes | Callback invoked to return the descriptor read.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901000 | Read forbidden. | +|2900099 | Operation failed. | + +**Example** + +```js +function readDesc(code, BLEDescriptor) { + if (code.code != 0) { + return; + } + console.log('bluetooth descriptor uuid: ' + BLEDescriptor.descriptorUuid); + let value = new Uint8Array(BLEDescriptor.descriptorValue); + console.log('bluetooth descriptor value: ' + value[0] +','+ value[1]+','+ value[2]+','+ value[3]); +} + +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 11; +let descriptor = { + serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', + descriptorValue: bufferDesc +}; +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.readDescriptorValue(descriptor, readDesc); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### readDescriptorValue + +readDescriptorValue(descriptor: BLEDescriptor): Promise<BLEDescriptor> + +Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------------------------------- | ---- | -------- | +| descriptor | [BLEDescriptor](#bledescriptor) | Yes | Descriptor to read.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | -------------------------- | +| Promise<[BLEDescriptor](#bledescriptor)> | Promise used to return the descriptor read.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901000 | Read forbidden. | +|2900099 | Operation failed. | + +**Example** + +```js +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 11; +let descriptor = { + serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', + descriptorValue: bufferDesc +}; +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.readDescriptorValue(descriptor); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### writeCharacteristicValue + +writeCharacteristicValue(characteristic: BLECharacteristic): void + +Writes a characteristic value to the remote BLE device. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | --------------------------------------- | ---- | ------------------- | +| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | Binary value and other parameters of the BLE device characteristic.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901001 | Write forbidden. | +|2900099 | Operation failed. | + +**Example** + +```js +let descriptors = []; +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; +descriptors[0] = descriptor; + +let bufferCCC = new ArrayBuffer(8); +let cccV = new Uint8Array(bufferCCC); +cccV[0] = 1; +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + characteristicValue: bufferCCC, descriptors:descriptors}; +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.writeCharacteristicValue(characteristic); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### writeDescriptorValue + +writeDescriptorValue(descriptor: BLEDescriptor): void + +Writes binary data to the specific descriptor of the remote BLE device. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------------------------------- | ---- | ------------------ | +| descriptor | [BLEDescriptor](#bledescriptor) | Yes | Binary value and other parameters of the BLE device descriptor.| +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901001 | Write forbidden. | +|2900099 | Operation failed. | + +**Example** + +```js +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 22; +let descriptor = { + serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', + descriptorValue: bufferDesc +}; +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.writeDescriptorValue(descriptor); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### setBLEMtuSize + +setBLEMtuSize(mtu: number): void + +Sets the maximum transmission unit (MTU) that can be transmitted between the GATT client and its remote BLE device. This API can be used only after a connection is set up by calling [connect](#connect). + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | -------------- | +| mtu | number | Yes | MTU to set, which ranges from 22 to 512 bytes.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.setBLEMtuSize(128); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### setNotifyCharacteristicChanged + +setNotifyCharacteristicChanged(characteristic: BLECharacteristic, enable: boolean): void + +Sets the function of notifying the GATT client when the characteristic value of the remote BLE device changes. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | --------------------------------------- | ---- | ----------------------------- | +| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | BLE characteristic to listen for. | +| enable | boolean | Yes | Whether to enable the notify function. The value **true** means to enable the notify function, and the value **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +// Create descriptors. +let descriptors = []; +let arrayBuffer = new ArrayBuffer(8); +let descV = new Uint8Array(arrayBuffer); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; +descriptors[0] = descriptor; +let arrayBufferC = new ArrayBuffer(8); +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.setNotifyCharacteristicChanged(characteristic, false); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} + +``` + + +### on('BLECharacteristicChange') + +on(type: "BLECharacteristicChange", callback: Callback<BLECharacteristic>): void + +Subscribes to the BLE characteristic change events. The client can receive a notification from the server only after the **setNotifyCharacteristicChanged** API is called. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **BLECharacteristicChange** indicates a characteristic value change event.| +| callback | Callback<[BLECharacteristic](#blecharacteristic)> | Yes | Callback invoked to return the characteristic value changes. | + +**Example** + +```js +function CharacteristicChange(CharacteristicChangeReq) { + let serviceUuid = CharacteristicChangeReq.serviceUuid; + let characteristicUuid = CharacteristicChangeReq.characteristicUuid; + let value = new Uint8Array(CharacteristicChangeReq.characteristicValue); +} +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.on('BLECharacteristicChange', CharacteristicChange); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### off('BLECharacteristicChange') + +off(type: "BLECharacteristicChange", callback?: Callback<BLECharacteristic>): void + +Unsubscribes from the BLE characteristic change events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **BLECharacteristicChange** indicates a characteristic value change event.| +| callback | Callback<[BLECharacteristic](#blecharacteristic)> | No | Callback for the characteristic value change event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| + +**Example** + +```js +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.off('BLECharacteristicChange'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### on('BLEConnectionStateChange') + +on(type: "BLEConnectionStateChange", callback: Callback<BLEConnectChangedState>): void + +Subscribes to the BLE connection state change events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **BLEConnectionStateChange** indicates a BLE connection state change event.| +| callback | Callback<[BLEConnectChangedState](#bleconnectchangedstate)> | Yes | Callback invoked to return the BLE connection state. | + +**Example** + +```js +function ConnectStateChanged(state) { + console.log('bluetooth connect state changed'); + let connectState = state.state; +} +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.on('BLEConnectionStateChange', ConnectStateChanged); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### off('BLEConnectionStateChange') + +off(type: "BLEConnectionStateChange", callback?: Callback<BLEConnectChangedState>): void + +Unsubscribes from the BLE connection state change events. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **BLEConnectionStateChange** indicates a BLE connection state change event.| +| callback | Callback<[BLEConnectChangedState](#bleconnectchangedstate)> | No | Callback for the BLE connection state change event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| + +**Example** + +```js +try { + let device = bluetoothManager.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.off('BLEConnectionStateChange'); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### getDeviceName + +getDeviceName(callback: AsyncCallback<string>): void + +Obtains the name of the remote BLE device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------------- | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the remote BLE device name obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +// callback +try { + let gattClient = bluetoothManager.BLE.createGattClientDevice("XX:XX:XX:XX:XX:XX"); + gattClient.connect(); + let deviceName = gattClient.getDeviceName((err, data)=> { + console.info('device name err ' + JSON.stringify(err)); + console.info('device name' + JSON.stringify(data)); + }) +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### getDeviceName + +getDeviceName(): Promise<string> + +Obtains the name of the remote BLE device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| --------------------- | ---------------------------------- | +| Promise<string> | Promise used to return the remote BLE device name.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +// promise +try { + let gattClient = bluetoothManager.BLE.createGattClientDevice("XX:XX:XX:XX:XX:XX"); + gattClient.connect(); + let deviceName = gattClient.getDeviceName().then((data) => { + console.info('device name' + JSON.stringify(data)); + }) +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### getRssiValue + +getRssiValue(callback: AsyncCallback<number>): void + +Obtains the received signal strength indication (RSSI) of the remote BLE device. This API uses an asynchronous callback to return the result. It can be used only after a connection is set up by calling [connect](#connect). + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------------ | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the RSSI, in dBm.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +// callback +try { + let gattClient = bluetoothManager.BLE.createGattClientDevice("XX:XX:XX:XX:XX:XX"); + gattClient.connect(); + let rssi = gattClient.getRssiValue((err, data)=> { + console.info('rssi err ' + JSON.stringify(err)); + console.info('rssi value' + JSON.stringify(data)); + }) +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +### getRssiValue + +getRssiValue(): Promise<number> + +Obtains the RSSI of the remote BLE device. This API uses a promise to return the result. It can be used only after a connection is set up by calling [connect](#connect). + +**Required permissions**: ohos.permission.USE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| --------------------- | --------------------------------- | +| Promise<number> | Promise used to return the RSSI, in dBm.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +// promise +try { + let gattClient = bluetoothManager.BLE.createGattClientDevice("XX:XX:XX:XX:XX:XX"); + let rssi = gattClient.getRssiValue().then((data) => { + console.info('rssi' + JSON.stringify(data)); + }) +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + +## ScanMode + +Enumerates the scan modes. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| ---------------------------------------- | ---- | --------------- | +| SCAN_MODE_NONE | 0 | No scan mode. | +| SCAN_MODE_CONNECTABLE | 1 | Connectable mode. | +| SCAN_MODE_GENERAL_DISCOVERABLE | 2 | General discoverable mode. | +| SCAN_MODE_LIMITED_DISCOVERABLE | 3 | Limited discoverable mode. | +| SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE | 4 | General connectable and discoverable mode.| +| SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE | 5 | Limited connectable and discoverable mode.| + +## BondState + +Enumerates the pairing states. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| ------------------ | ---- | ------ | +| BOND_STATE_INVALID | 0 | Invalid pairing.| +| BOND_STATE_BONDING | 1 | Pairing. | +| BOND_STATE_BONDED | 2 | Paired. | + + +## SppOption + +Defines the SPP configuration parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ------ | ------------------- | ---- | ---- | ----------- | +| uuid | string | Yes | Yes | UUID of the SPP.| +| secure | boolean | Yes | Yes | Whether it is a secure channel. | +| type | [SppType](#spptype) | Yes | Yes | Type of the SPP link. | + + +## SppType + +Enumerates the SPP link types. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| ---------- | ---- | ------------- | +| SPP_RFCOMM | 0 | Radio frequency communication (RFCOMM) link type.| + + +## GattService + +Defines the GATT service API parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| --------------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- | +| serviceUuid | string | Yes | Yes | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| +| isPrimary | boolean | Yes | Yes | Whether the service is a primary service. The value **true** means a primary service. | +| characteristics | Array<[BLECharacteristic](#blecharacteristic)> | Yes | Yes | List of characteristics of the service. | +| includeServices | Array<[GattService](#gattservice)> | Yes | Yes | Services on which the service depends. | + + +## BLECharacteristic + +Defines the characteristic API parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ------------------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- | +| serviceUuid | string | Yes | Yes | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| +| characteristicUuid | string | Yes | Yes | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**.| +| characteristicValue | ArrayBuffer | Yes | Yes | Binary value of the characteristic. | +| descriptors | Array<[BLEDescriptor](#bledescriptor)> | Yes | Yes | List of descriptors of the characteristic. | + + +## BLEDescriptor + +Defines the descriptor API parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ------------------ | ----------- | ---- | ---- | ---------------------------------------- | +| serviceUuid | string | Yes | Yes | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| +| characteristicUuid | string | Yes | Yes | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**.| +| descriptorUuid | string | Yes | Yes | UUID of the descriptor, for example, **00002902-0000-1000-8000-00805f9b34fb**.| +| descriptorValue | ArrayBuffer | Yes | Yes | Binary value of the descriptor. | + + +## NotifyCharacteristic + +Defines the parameters in the notifications sent when the server characteristic value changes. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ------------------- | ----------- | ---- | ---- | ---------------------------------------- | +| serviceUuid | string | Yes | Yes | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| +| characteristicUuid | string | Yes | Yes | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**.| +| characteristicValue | ArrayBuffer | Yes | Yes | Binary value of the characteristic. | +| confirm | boolean | Yes | Yes | Whether the notification needs to be confirmed by the remote end. For a notification, set it to **true**. In this case, the remote end must confirm the receipt of the notification. For an indication, set it to **false**. In this case, the remote end does not need to confirm the receipt of the notification.| + + +## CharacteristicReadRequest + +Defines the parameters of the **CharacteristicReadReq** event received by the server. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ------------------ | ------ | ---- | ---- | ---------------------------------------- | +| deviceId | string | Yes | No | Address of the remote device that sends the **CharacteristicReadReq** event, for example, XX:XX:XX:XX:XX:XX.| +| transId | number | Yes | No | Transmission ID of the read request. The response returned by the server must use the same transmission ID. | +| offset | number | Yes | No | Position from which the characteristic value is read. For example, **k** means to read from the kth byte. The response returned by the server must use the same offset.| +| characteristicUuid | string | Yes | No | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**.| +| serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| + + +## CharacteristicWriteRequest + +Defines the parameters of the **CharacteristicWriteReq** event received by the server. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ------------------ | ------ | ---- | ---- | ---------------------------------------- | +| deviceId | string | Yes | No | Address of the remote device that sends the **CharacteristicWriteReq** event, for example, XX:XX:XX:XX:XX:XX.| +| transId | number | Yes | No | Transmission ID of the write request. The response returned by the server must use the same transmission ID. | +| offset | number | Yes | No | Start position for writing the characteristic value. For example, **k** means to write from the kth byte. The response returned by the server must use the same offset.| +| descriptorUuid | string | Yes | No | UUID of the descriptor, for example, **00002902-0000-1000-8000-00805f9b34fb**.| +| characteristicUuid | string | Yes | No | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**.| +| serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| + + +## DescriptorReadRequest + +Defines the parameters of the **DescriptorReadReq** event received by the server. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ------------------ | ------ | ---- | ---- | ---------------------------------------- | +| deviceId | string | Yes | No | Address of the remote device that sends a **DescriptorReadReq** event, for example, XX:XX:XX:XX:XX:XX.| +| transId | number | Yes | No | Transmission ID of the read request. The response returned by the server must use the same transmission ID. | +| offset | number | Yes | No | Position from which the descriptor is read. For example, **k** means to read from the kth byte. The response returned by the server must use the same offset.| +| descriptorUuid | string | Yes | No | UUID of the descriptor, for example, **00002902-0000-1000-8000-00805f9b34fb**.| +| characteristicUuid | string | Yes | No | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**.| +| serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| + + +## DescriptorWriteRequest + +Defines the parameters of the **DescriptorWriteReq** event received by the server. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ------------------ | ----------- | ---- | ---- | ---------------------------------------- | +| deviceId | string | Yes | No | Address of the remote device that sends a **DescriptorWriteReq** event, for example, XX:XX:XX:XX:XX:XX.| +| transId | number | Yes | No | Transmission ID of the write request. The response returned by the server must use the same transmission ID. | +| offset | number | Yes | No | Start position for writing the descriptor. For example, **k** means to write from the kth byte. The response returned by the server must use the same offset.| +| isPrep | boolean | Yes | No | Whether the write request is executed immediately. | +| needRsp | boolean | Yes | No | Whether to send a response to the GATT client. | +| value | ArrayBuffer | Yes | No | Binary value of the descriptor to write. | +| descriptorUuid | string | Yes | No | UUID of the descriptor, for example, **00002902-0000-1000-8000-00805f9b34fb**.| +| characteristicUuid | string | Yes | No | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**.| +| serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| + + +## ServerResponse + +Defines the parameters of the server's response to the GATT client's read/write request. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| -------- | ----------- | ---- | ---- | -------------------------------------- | +| deviceId | string | Yes | No | Address of the remote device, for example, XX:XX:XX:XX:XX:XX. | +| transId | number | Yes | No | Transmission ID of the request. The value must be the same as the ID carried in the read/write request received. | +| status | number | Yes | No | Response state. Set this parameter to **0**, which indicates a normal response. | +| offset | number | Yes | No | Start read/write position. The value must be the same as the offset carried in the read/write request.| +| value | ArrayBuffer | Yes | No | Binary data in the response. | + + +## BLEConnectChangedState + +Defines the parameters of **BLEConnectChangedState**. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable| Writable| Description | +| -------- | ------------------------------------------------- | ---- | ---- | --------------------------------------------- | +| deviceId | string | Yes | No | Address of the remote device, for example, XX:XX:XX:XX:XX:XX.| +| state | [ProfileConnectionState](#profileconnectionstate) | Yes | Yes | BLE connection state. | + + +## ProfileConnectionState + +Enumerates the profile connection states. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| ------------------- | ---- | -------------- | +| STATE_DISCONNECTED | 0 | Disconnected. | +| STATE_CONNECTING | 1 | Connecting.| +| STATE_CONNECTED | 2 | Connected. | +| STATE_DISCONNECTING | 3 | Disconnecting.| + + +## ScanFilter + +Defines the scan filter parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable| Writable| Description | +| ---------------------------------------- | ----------- | ---- | ---- | ------------------------------------------------------------ | +| deviceId | string | Yes | Yes | Address of the BLE device to filter, for example, XX:XX:XX:XX:XX:XX. | +| name | string | Yes | Yes | Name of the BLE device to filter. | +| serviceUuid | string | Yes | Yes | Service UUID of the device to filter, for example, **00001888-0000-1000-8000-00805f9b34fb**.| +| serviceUuidMask | string | Yes | Yes | Service UUID mask of the device to filter, for example, **FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF**.| +| serviceSolicitationUuid | string | Yes | Yes | Service solicitation UUID of the device to filter, for example, **00001888-0000-1000-8000-00805F9B34FB**.| +| serviceSolicitationUuidMask | string | Yes | Yes | Service solicitation UUID mask of the device to filter, for example, **FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF**.| +| serviceData | ArrayBuffer | Yes | Yes | Service data of the device to filter, for example, **[0x90, 0x00, 0xF1, 0xF2]**.| +| serviceDataMask | ArrayBuffer | Yes | Yes | Service data mask of the device to filter, for example, **[0xFF,0xFF,0xFF,0xFF]**.| +| manufactureId | number | Yes | Yes | Manufacturer ID of the device to filter, for example, **0x0006**. | +| manufactureData | ArrayBuffer | Yes | Yes | Manufacturer data of the device to filter, for example, **[0x1F,0x2F,0x3F]**.| +| manufactureDataMask | ArrayBuffer | Yes | Yes | Manufacturer data mask of the device to filter, for example, **[0xFF, 0xFF, 0xFF]**.| + + +## ScanOptions + +Defines the scan configuration parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| --------- | ----------------------- | ---- | ---- | -------------------------------------- | +| interval | number | Yes | Yes | Delay in reporting the scan result. The default value is **0**. | +| dutyMode | [ScanDuty](#scanduty) | Yes | Yes | Scan duty. The default value is SCAN_MODE_LOW_POWER. | +| matchMode | [MatchMode](#matchmode) | Yes | Yes | Hardware filtering match mode. The default value is **MATCH_MODE_AGGRESSIVE**.| + + +## ScanDuty + +Enumerates the scan duty options. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| --------------------- | ---- | ------------ | +| SCAN_MODE_LOW_POWER | 0 | Low-power mode, which is the default value.| +| SCAN_MODE_BALANCED | 1 | Balanced mode. | +| SCAN_MODE_LOW_LATENCY | 2 | Low-latency mode. | + + +## MatchMode + +Enumerates the hardware match modes of BLE scan filters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| --------------------- | ---- | ---------------------------------------- | +| MATCH_MODE_AGGRESSIVE | 1 | Hardware reports the scan result with a lower threshold of signal strength and few number of matches in a duration. This is the default value.| +| MATCH_MODE_STICKY | 2 | Hardware reports the scan result with a higher threshold of signal strength and sightings. | + + +## ScanResult + +Defines the scan result. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| -------- | ----------- | ---- | ---- | ---------------------------------- | +| deviceId | string | Yes | No | Address of the scanned device, for example, XX:XX:XX:XX:XX:XX.| +| rssi | number | Yes | No | RSSI of the device. | +| data | ArrayBuffer | Yes | No | Advertisement packets sent by the device. | + + +## BluetoothState + +Enumerates the Bluetooth states. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| --------------------- | ---- | ------------------ | +| STATE_OFF | 0 | Bluetooth is turned off. | +| STATE_TURNING_ON | 1 | Bluetooth is being turned on. | +| STATE_ON | 2 | Bluetooth is turned on. | +| STATE_TURNING_OFF | 3 | Bluetooth is being turned off. | +| STATE_BLE_TURNING_ON | 4 | The LE-only mode is being turned on for Bluetooth.| +| STATE_BLE_ON | 5 | Bluetooth is in LE-only mode. | +| STATE_BLE_TURNING_OFF | 6 | The LE-only mode is being turned off for Bluetooth.| + + +## AdvertiseSetting + +Defines the BLE advertising parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ----------- | ------- | ---- | ---- | ---------------------------------------- | +| interval | number | Yes | Yes | Interval for BLE advertising. The minimum value is **32** slots (20 ms). The maximum value is **16384** slots. The default value is **1600** slots (1s).| +| txPower | number | Yes | Yes | Transmit power, in dBm. The value range is -127 to 1. The default value is **-7**. | +| connectable | boolean | Yes | Yes | Whether the advertisement is connectable. The default value is **true**. | + + +## AdvertiseData + +Defines the content of a BLE advertisement packet. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| --------------- | ---------------------------------------- | ---- | ---- | --------------------------- | +| serviceUuids | Array<string> | Yes | Yes | List of service UUIDs to broadcast.| +| manufactureData | Array<[ManufactureData](#manufacturedata)> | Yes | Yes | List of manufacturers to broadcast. | +| serviceData | Array<[ServiceData](#servicedata)> | Yes | Yes | List of service data to broadcast. | + + +## ManufactureData + +Defines the content of a BLE advertisement packet. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ---------------- | ------------------- | ---- | ---- | ------------------ | +| manufactureId | number | Yes | Yes | Manufacturer ID allocated by the Bluetooth SIG.| +| manufactureValue | ArrayBuffer | Yes | Yes | Manufacturer data. | + + +## ServiceData + +Defines the service data contained in an advertisement packet. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ------------ | ----------- | ---- | ---- | ---------- | +| serviceUuid | string | Yes | Yes | Service UUID.| +| serviceValue | ArrayBuffer | Yes | Yes | Service data. | + + +## PinRequiredParam + +Defines the pairing request parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| -------- | ------ | ---- | ---- | ----------- | +| deviceId | string | Yes | No | ID of the device to pair.| +| pinCode | string | Yes | No | Key for the device pairing. | + + +## BondStateParam + +Defines the pairing state parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| -------- | ------ | ---- | ---- | ----------- | +| deviceId | string | Yes | No | ID of the device to pair.| +| state | BondState | Yes | No | State of the device.| + + +## StateChangeParam + +Defines the profile state change parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable| Writable| Description | +| -------- | ------------------------------------------------- | ---- | ---- | ------------------------------- | +| deviceId | string | Yes | No | Address of a Bluetooth device. | +| state | [ProfileConnectionState](#profileconnectionstate) | Yes | No | Profile connection state of the device.| + + +## DeviceClass + +Defines the class of a Bluetooth device. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| --------------- | ----------------------------------- | ---- | ---- | ---------------- | +| majorClass | [MajorClass](#majorclass) | Yes | No | Major classes of Bluetooth devices. | +| majorMinorClass | [MajorMinorClass](#majorminorclass) | Yes | No | Major and minor classes of Bluetooth devices.| +| classOfDevice | number | Yes | No | Class of the device. | + + + +## MajorClass + +Enumerates the major classes of Bluetooth devices. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| ------------------- | ------ | ---------- | +| MAJOR_MISC | 0x0000 | Miscellaneous device. | +| MAJOR_COMPUTER | 0x0100 | Computer. | +| MAJOR_PHONE | 0x0200 | Mobile phone. | +| MAJOR_NETWORKING | 0x0300 | Network device. | +| MAJOR_AUDIO_VIDEO | 0x0400 | Audio or video device.| +| MAJOR_PERIPHERAL | 0x0500 | Peripheral device. | +| MAJOR_IMAGING | 0x0600 | Imaging device. | +| MAJOR_WEARABLE | 0x0700 | Wearable device. | +| MAJOR_TOY | 0x0800 | Toy. | +| MAJOR_HEALTH | 0x0900 | Health device. | +| MAJOR_UNCATEGORIZED | 0x1F00 | Unclassified device. | + + +## MajorMinorClass + +Enumerates the major and minor classes of Bluetooth devices. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| ---------------------------------------- | ------ | --------------- | +| COMPUTER_UNCATEGORIZED | 0x0100 | Unclassified computer. | +| COMPUTER_DESKTOP | 0x0104 | Desktop computer. | +| COMPUTER_SERVER | 0x0108 | Server. | +| COMPUTER_LAPTOP | 0x010C | Laptop. | +| COMPUTER_HANDHELD_PC_PDA | 0x0110 | Hand-held computer. | +| COMPUTER_PALM_SIZE_PC_PDA | 0x0114 | Palmtop computer. | +| COMPUTER_WEARABLE | 0x0118 | Wearable computer. | +| COMPUTER_TABLET | 0x011C | Tablet. | +| PHONE_UNCATEGORIZED | 0x0200 | Unclassified mobile phone. | +| PHONE_CELLULAR | 0x0204 | Portable phone. | +| PHONE_CORDLESS | 0x0208 | Cordless phone. | +| PHONE_SMART | 0x020C | Smartphone. | +| PHONE_MODEM_OR_GATEWAY | 0x0210 | Modem or gateway phone.| +| PHONE_ISDN | 0x0214 | ISDN phone. | +| NETWORK_FULLY_AVAILABLE | 0x0300 | Device with network fully available. | +| NETWORK_1_TO_17_UTILIZED | 0x0320 | Device used on network 1 to 17. | +| NETWORK_17_TO_33_UTILIZED | 0x0340 | Device used on network 17 to 33. | +| NETWORK_33_TO_50_UTILIZED | 0x0360 | Device used on network 33 to 50. | +| NETWORK_60_TO_67_UTILIZED | 0x0380 | Device used on network 60 to 67. | +| NETWORK_67_TO_83_UTILIZED | 0x03A0 | Device used on network 67 to 83. | +| NETWORK_83_TO_99_UTILIZED | 0x03C0 | Device used on network 83 to 99. | +| NETWORK_NO_SERVICE | 0x03E0 | Device without network service | +| AUDIO_VIDEO_UNCATEGORIZED | 0x0400 | Unclassified audio or video device. | +| AUDIO_VIDEO_WEARABLE_HEADSET | 0x0404 | Wearable audio or video headset. | +| AUDIO_VIDEO_HANDSFREE | 0x0408 | Hands-free audio or video device. | +| AUDIO_VIDEO_MICROPHONE | 0x0410 | Audio or video microphone. | +| AUDIO_VIDEO_LOUDSPEAKER | 0x0414 | Audio or video loudspeaker. | +| AUDIO_VIDEO_HEADPHONES | 0x0418 | Audio or video headphones. | +| AUDIO_VIDEO_PORTABLE_AUDIO | 0x041C | Portable audio or video device. | +| AUDIO_VIDEO_CAR_AUDIO | 0x0420 | In-vehicle audio or video device. | +| AUDIO_VIDEO_SET_TOP_BOX | 0x0424 | Audio or video STB device. | +| AUDIO_VIDEO_HIFI_AUDIO | 0x0428 | High-fidelity speaker device. | +| AUDIO_VIDEO_VCR | 0x042C | Video cassette recording (VCR) device. | +| AUDIO_VIDEO_VIDEO_CAMERA | 0x0430 | Camera. | +| AUDIO_VIDEO_CAMCORDER | 0x0434 | Camcorder | +| AUDIO_VIDEO_VIDEO_MONITOR | 0x0438 | Audio or video monitor. | +| AUDIO_VIDEO_VIDEO_DISPLAY_AND_LOUDSPEAKER | 0x043C | Video display or loudspeaker. | +| AUDIO_VIDEO_VIDEO_CONFERENCING | 0x0440 | Video conferencing device. | +| AUDIO_VIDEO_VIDEO_GAMING_TOY | 0x0448 | Audio or video gaming toy. | +| PERIPHERAL_NON_KEYBOARD_NON_POINTING | 0x0500 | Non-keyboard or non-pointing peripheral device. | +| PERIPHERAL_KEYBOARD | 0x0540 | Keyboard device. | +| PERIPHERAL_POINTING_DEVICE | 0x0580 | Pointing peripheral device. | +| PERIPHERAL_KEYBOARD_POINTING | 0x05C0 | Keyboard pointing device. | +| PERIPHERAL_UNCATEGORIZED | 0x0500 | Unclassified peripheral device. | +| PERIPHERAL_JOYSTICK | 0x0504 | Peripheral joystick. | +| PERIPHERAL_GAMEPAD | 0x0508 | Peripheral game pad | +| PERIPHERAL_REMOTE_CONTROL | 0x05C0 | Peripheral remote control device | +| PERIPHERAL_SENSING_DEVICE | 0x0510 | Peripheral sensing device. | +| PERIPHERAL_DIGITIZER_TABLET | 0x0514 | Peripheral digitizer tablet.| +| PERIPHERAL_CARD_READER | 0x0518 | Peripheral card reader. | +| PERIPHERAL_DIGITAL_PEN | 0x051C | Peripheral digital pen. | +| PERIPHERAL_SCANNER_RFID | 0x0520 | Peripheral RFID scanner. | +| PERIPHERAL_GESTURAL_INPUT | 0x0522 | Gesture input device. | +| IMAGING_UNCATEGORIZED | 0x0600 | Unclassified imaging device. | +| IMAGING_DISPLAY | 0x0610 | Imaging display device. | +| IMAGING_CAMERA | 0x0620 | Imaging camera device. | +| IMAGING_SCANNER | 0x0640 | Imaging scanner. | +| IMAGING_PRINTER | 0x0680 | Imaging printer. | +| WEARABLE_UNCATEGORIZED | 0x0700 | Unclassified wearable device. | +| WEARABLE_WRIST_WATCH | 0x0704 | Smart watch. | +| WEARABLE_PAGER | 0x0708 | Wearable pager. | +| WEARABLE_JACKET | 0x070C | Smart jacket. | +| WEARABLE_HELMET | 0x0710 | Wearable helmet. | +| WEARABLE_GLASSES | 0x0714 | Wearable glasses. | +| TOY_UNCATEGORIZED | 0x0800 | Unclassified toy. | +| TOY_ROBOT | 0x0804 | Toy robot. | +| TOY_VEHICLE | 0x0808 | Toy vehicle. | +| TOY_DOLL_ACTION_FIGURE | 0x080C | Humanoid toy doll. | +| TOY_CONTROLLER | 0x0810 | Toy controller. | +| TOY_GAME | 0x0814 | Toy gaming device. | +| HEALTH_UNCATEGORIZED | 0x0900 | Unclassified health devices. | +| HEALTH_BLOOD_PRESSURE | 0x0904 | Blood pressure device. | +| HEALTH_THERMOMETER | 0x0908 | Thermometer | +| HEALTH_WEIGHING | 0x090C | Body scale. | +| HEALTH_GLUCOSE | 0x0910 | Blood glucose monitor. | +| HEALTH_PULSE_OXIMETER | 0x0914 | Pulse oximeter. | +| HEALTH_PULSE_RATE | 0x0918 | Heart rate monitor. | +| HEALTH_DATA_DISPLAY | 0x091C | Health data display. | +| HEALTH_STEP_COUNTER | 0x0920 | Step counter. | +| HEALTH_BODY_COMPOSITION_ANALYZER | 0x0924 | Body composition analyzer. | +| HEALTH_PEAK_FLOW_MONITOR | 0x0928 | Hygrometer. | +| HEALTH_MEDICATION_MONITOR | 0x092C | Medication monitor. | +| HEALTH_KNEE_PROSTHESIS | 0x0930 | Prosthetic knee. | +| HEALTH_ANKLE_PROSTHESIS | 0x0934 | Prosthetic ankle. | +| HEALTH_GENERIC_HEALTH_MANAGER | 0x0938 | Generic health management device. | +| HEALTH_PERSONAL_MOBILITY_DEVICE | 0x093C | Personal mobility device. | + + +## PlayingState + +Enumerates the A2DP playing states. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| ----------------- | ------ | ------- | +| STATE_NOT_PLAYING | 0x0000 | Not playing. | +| STATE_PLAYING | 0x0001 | Playing.| + + +## ProfileId + +Enumerates the Bluetooth profiles. API version 9 is added with **PROFILE_HID_HOST** and **PROFILE_PAN_NETWORK**. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| -------------------------------- | ------ | --------------- | +| PROFILE_A2DP_SOURCE | 1 | A2DP profile.| +| PROFILE_HANDS_FREE_AUDIO_GATEWAY | 4 | HFP profile. | +| PROFILE_HID_HOST | 6 | Human Interface Device (HID) profile. | +| PROFILE_PAN_NETWORK | 7 | PAN profile. | 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/errorcode-bluetoothManager.md b/en/application-dev/reference/errorcodes/errorcode-bluetoothManager.md new file mode 100644 index 0000000000000000000000000000000000000000..23218ca3ad566b66ad791897a982cebc07fc186e --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-bluetoothManager.md @@ -0,0 +1,127 @@ +# Bluetooth Error Codes + +## 2900001 + +**Error Message** + +Service stopped. + +**Description** + +The Bluetooth service is stopped, and the APIs related to the Bluetooth service cannot be called. + +**Possible Causes** + +The Bluetooth service fails to start. + +**Solution** + +Start the Bluetooth service. + +## 2900003 + +**Error Message** + +Bluetooth switch is off. + +**Description** + +Bluetooth is disabled. + +**Possible Causes** + +Bluetooth is disabled. + +**Solution** + +Enable Bluetooth. + +## 2900004 + +**Error Message** + +Profile is not supported. + +**Description** + +The profile is not supported. + +**Possible Causes** + +The profile is not supported by the device. + +**Solution** + +Check whether the device supports the profile. Use a profile supported by the device. + +## 2900099 + +**Error Message** + +Operation failed. + +**Description** + +The operation failed. + +**Possible Causes** + +The profile is not supported by the device. + +**Solution** + +Perform this operation again. + +## 2901000 + +**Error Message** + +Read forbidden. + +**Description** + +The read operation is not allowed. + +**Possible Causes** + +The caller does not have the read permission. + +**Solution** + +Check whether the caller has the read permission. + +## 2901001 + +**Error Message** + +Write forbidden. + +**Description** + +The write operation is not allowed. + +**Possible Causes** + +The caller does not have the write permission. + +**Solution** + +Check whether the caller has the write permission. + +## 2901054 + +**Error Message** + +IO error. + +**Description** + +The I/O operation failed. + +**Possible Causes** + +The I/O transmission is abnormal. + +**Solution** + +Perform this operation again. 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) diff --git a/zh-cn/application-dev/application-models/common-event-overview.md b/zh-cn/application-dev/application-models/common-event-overview.md index 074043968aeaa90f4a1cf11a081c904b0d0cee76..ef26de35a6a7cbd01bcc0b9edc4f596da9f3f73e 100644 --- a/zh-cn/application-dev/application-models/common-event-overview.md +++ b/zh-cn/application-dev/application-models/common-event-overview.md @@ -17,7 +17,7 @@ OpenHarmony通过CES(Common Event Service,公共事件服务)为应用程 - 无序公共事件:CES转发公共事件时,不考虑订阅者是否接收到,按订阅者订阅先后顺序转发。 -- 有序公共事件:CES转发公共事件时,按订阅者订阅先后顺序,在接收到前一个订阅者回复后,再转发下一个订阅者。 +- 有序公共事件:CES转发公共事件时,根据订阅者设置的优先级等级,在接收到优先级较高的一个订阅者回复后,再向下一个优先级较低的订阅者转发公共事件。 - 粘性公共事件:能够让订阅者收到在订阅前已经发送的公共事件就是粘性公共事件。普通的公共事件只能在订阅后发送才能收到,而粘性公共事件的特殊性就是可以先发送后订阅。发送粘性事件必须是系统应用或系统服务,且需要申请`ohos.permission.COMMONEVENT_STICKY`权限,配置方式请参阅[访问控制授权申请指导](../security/accesstoken-guidelines.md#stage模型)。 diff --git a/zh-cn/application-dev/reference/apis/Readme-CN.md b/zh-cn/application-dev/reference/apis/Readme-CN.md index 8425f7656d5ff64ab81190592f453500856927b1..c87c165352502ba70ae40c7cc515dae3688fa4b3 100755 --- a/zh-cn/application-dev/reference/apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/apis/Readme-CN.md @@ -213,7 +213,6 @@ - [@ohos.security.huks (通用密钥库系统)](js-apis-huks.md) - [@ohos.userIAM.faceAuth (人脸认证)](js-apis-useriam-faceauth.md) - [@ohos.userIAM.userAuth (用户认证)](js-apis-useriam-userauth.md) - - [@system.cipher (加密算法)](js-apis-system-cipher.md) - security - [PermissionRequestResult](js-apis-permissionrequestresult.md) @@ -392,6 +391,7 @@ - [@ohos.fileio (文件管理)](js-apis-fileio.md) - [@ohos.geolocation (位置服务)](js-apis-geolocation.md) - [@ohos.hiAppEvent (应用打点)](js-apis-hiappevent.md) + - [@ohos.multimedia.medialibrary (媒体库管理)](js-apis-medialibrary.md) - [@ohos.prompt (弹窗)](js-apis-prompt.md) - [@ohos.reminderAgent (后台代理提醒)](js-apis-reminderAgent.md) - [@ohos.statfs (statfs)](js-apis-statfs.md) @@ -403,12 +403,12 @@ - [@system.battery (电量信息)](js-apis-system-battery.md) - [@system.bluetooth (蓝牙)](js-apis-system-bluetooth.md) - [@system.brightness (屏幕亮度)](js-apis-system-brightness.md) + - [@system.cipher (加密算法)](js-apis-system-cipher.md) - [@system.configuration (应用配置)](js-apis-system-configuration.md) - [@system.device (设备信息)](js-apis-system-device.md) - [@system.fetch (数据请求)](js-apis-system-fetch.md) - [@system.file (文件存储)](js-apis-system-file.md) - [@system.geolocation (地理位置)](js-apis-system-location.md) - - [@ohos.multimedia.medialibrary (媒体库管理)](js-apis-medialibrary.md) - [@system.mediaquery (媒体查询)](js-apis-system-mediaquery.md) - [@system.network (网络状态)](js-apis-system-network.md) - [@system.notification (通知消息)](js-apis-system-notification.md) diff --git a/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index f1520db2991e5515eb1cbda31cd304f6a670ba48..023a36614c784550dd595a9c99ac7abcc99cff97 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -2,7 +2,7 @@ 程序访问控制提供程序的权限管理能力,包括鉴权、授权和取消授权等。 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> **说明:** > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 @@ -531,7 +531,9 @@ verifyAccessToken(tokenID: number, permissionName: Permissions): Promise<Gran 校验应用是否授予权限。使用Promise异步回调。 -> **说明:** 建议使用[checkAccessToken](#checkaccesstoken9)替代。 +> **说明:** +> +> 建议使用[checkAccessToken](#checkaccesstoken9)替代。 **系统能力:** SystemCapability.Security.AccessToken @@ -658,7 +660,9 @@ verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStat 校验应用是否授予权限。使用Promise异步回调。 -> **说明:** 从API version 9开始不再维护,建议使用[checkAccessToken](#checkaccesstoken9)替代。 +> **说明:** +> +> 从API version 9开始不再维护,建议使用[checkAccessToken](#checkaccesstoken9)替代。 **系统能力:** SystemCapability.Security.AccessToken diff --git a/zh-cn/application-dev/reference/apis/js-apis-call.md b/zh-cn/application-dev/reference/apis/js-apis-call.md index ea7457f584a7b43f0caa4487d3bccdb8f09c5d9f..16b9fbbafa4bcc54e7a0920772578f4077f87c45 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-call.md +++ b/zh-cn/application-dev/reference/apis/js-apis-call.md @@ -3953,7 +3953,7 @@ promise.then(data => { 拨打电话的可选参数。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ------------------------ | ---------------------------------- | ---- | ----------------------------------------------------------------------------------------------- | @@ -3967,7 +3967,7 @@ promise.then(data => { 拨打电话的可选参数。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ------------------------ | ---------------------------------- | ---- | ------------------------------------------------------------ | @@ -3980,7 +3980,7 @@ promise.then(data => { 通话状态码。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ------------------ | ---- | ------------------------------------------------------------ | @@ -3993,7 +3993,7 @@ promise.then(data => { 判断是否是紧急电话号码的可选参数。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ---------------------------------------------- | @@ -4003,7 +4003,7 @@ promise.then(data => { 格式化号码的可选参数。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ----------- | ------ | ---- | ---------------------------------------------------------- | @@ -4015,7 +4015,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ---------------------- | ---- | ------------------ | @@ -4031,7 +4031,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | -------------------- | ---- | ------------ | @@ -4047,7 +4047,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | --------------------------------------------- | ---- | -------------------------- | @@ -4066,7 +4066,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ------------------------ | ---------------------------------------------------- | ---- | ---------------- | @@ -4084,7 +4084,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | --------------------------- | ---- | ------------ | @@ -4099,7 +4099,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | -------------------------- | ---- | ------------ | @@ -4114,7 +4114,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | --------------- | ---------------------------------------- | ---- | -------------- | @@ -4135,7 +4135,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ---------------------------- | ---- | -------------- | @@ -4150,7 +4150,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ------------- | ---- | ------------ | @@ -4165,7 +4165,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ---------- | ---- | -------- | @@ -4178,7 +4178,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ------------------------- | ---- | -------------- | @@ -4198,7 +4198,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | -------- | -------------------------------------------- | ---- | ------------ | @@ -4212,7 +4212,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ----------------------------- | ---- | ------------ | @@ -4225,7 +4225,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ------- | ------------------------------------------ | ---- | -------------- | @@ -4237,7 +4237,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ------------------------ | ---- | --------------- | @@ -4250,7 +4250,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | --------------- | ---- | ------------ | @@ -4264,7 +4264,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | -------------------- | ---- | ---------------- | @@ -4278,7 +4278,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | -------------- | ------ | ---- | -------- | @@ -4290,7 +4290,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ------------------------ | ---------------------------------- | ---- | ---------------- | @@ -4307,7 +4307,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | -------------------- | ---- | ------------ | @@ -4320,7 +4320,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ------------------- | ---- | -------- | @@ -4333,7 +4333,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ---------------- | ---- | -------- | @@ -4346,7 +4346,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ------- | ------------------------------------------ | ---- | --------------- | @@ -4359,7 +4359,7 @@ IP多媒体系统调用模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ------------------------------------------------------------ | ---- | --------------------------------------- | @@ -4449,7 +4449,7 @@ MMI码结果。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ------- | -------------------------------- | ---- | --------------- | @@ -4462,7 +4462,7 @@ MMI码结果。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 值 | 说明 | | ---------------- | ---- | ------------- | @@ -4475,7 +4475,7 @@ MMI码结果。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CallManager。 +**系统能力**:SystemCapability.Telephony.CallManager | 名称 | 类型 | 必填 | 说明 | | ---------------- | ------ | ---- | -------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md b/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md index 385251bb566383c332c8f10952191ef7121674f7..46f51a3ae4716c6ffe29ae0991bce58e72401a0e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @@ -43,7 +43,7 @@ getOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): voi **系统能力:** SystemCapability.Account.OsAccount -**需要权限:** ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS 或 ohos.permission.GET_DISTRIBUTED_ACCOUNTS 或 ohos.permission.DISTRIBUTED_DATASYNC。 +**需要权限:** ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS 或 ohos.permission.GET_DISTRIBUTED_ACCOUNTS 或 ohos.permission.DISTRIBUTED_DATASYNC **参数:** @@ -79,7 +79,7 @@ getOsAccountDistributedInfo(): Promise<DistributedInfo> **系统能力:** SystemCapability.Account.OsAccount -**需要权限:** ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS 或 ohos.permission.GET_DISTRIBUTED_ACCOUNTS 或 ohos.permission.DISTRIBUTED_DATASYNC。 +**需要权限:** ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS 或 ohos.permission.GET_DISTRIBUTED_ACCOUNTS 或 ohos.permission.DISTRIBUTED_DATASYNC **返回值:** @@ -118,7 +118,7 @@ queryOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): v **系统能力:** SystemCapability.Account.OsAccount -**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS 或 ohos.permission.DISTRIBUTED_DATASYNC。 +**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS 或 ohos.permission.DISTRIBUTED_DATASYNC **参数:** @@ -148,7 +148,7 @@ queryOsAccountDistributedInfo(): Promise<DistributedInfo> **系统能力:** SystemCapability.Account.OsAccount -**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS 或 ohos.permission.DISTRIBUTED_DATASYNC。 +**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS 或 ohos.permission.DISTRIBUTED_DATASYNC **返回值:** @@ -175,7 +175,7 @@ setOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallbac **系统能力:** SystemCapability.Account.OsAccount -**需要权限:** ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS。 +**需要权限:** ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS **参数:** @@ -213,7 +213,7 @@ setOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> **系统能力:** SystemCapability.Account.OsAccount -**需要权限:** ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS。 +**需要权限:** ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS **参数:** @@ -260,7 +260,7 @@ updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCall **系统能力:** SystemCapability.Account.OsAccount -**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS。 +**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS **参数:** @@ -286,9 +286,10 @@ updateOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> > **说明:** > > 从 API version 7开始支持,从API version 9开始废弃。建议使用[setOsAccountDistributedInfo](#setosaccountdistributedinfo9-1)。 + **系统能力:** SystemCapability.Account.OsAccount -**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS。 +**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS **参数:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-faultLogger.md b/zh-cn/application-dev/reference/apis/js-apis-faultLogger.md index 4bd9e741756a4602c94181222395cfbd18ef9bd4..5cde0c467071e5598845fa939feecc7d34c5bf50 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-faultLogger.md +++ b/zh-cn/application-dev/reference/apis/js-apis-faultLogger.md @@ -40,11 +40,9 @@ import faultLogger from '@ohos.faultLogger' | summary | string | 是 | 故障的概要 | | fullLog | string | 是 | 故障日志全文 | -## faultLogger.querySelfFaultLog(deprecated) - -querySelfFaultLog(faultType: FaultType, callback: AsyncCallback<Array<FaultLogInfo>>) : void +## faultLogger.query9+ -> **说明:** 从 API Version 9 开始废弃,建议使用[faultLogger.query](#faultloggerquery9)替代。 +query(faultType: FaultType, callback: AsyncCallback<Array<FaultLogInfo>>) : void 获取当前进程故障信息,该方法通过回调方式获取故障信息数组,故障信息数组内最多上报10份故障信息。 @@ -57,6 +55,14 @@ querySelfFaultLog(faultType: FaultType, callback: AsyncCallback<Array<Faul | faultType | [FaultType](#faulttype) | 是 | 输入要查询的故障类型。 | | callback | AsyncCallback<Array<[FaultLogInfo](#faultloginfo)>> | 是 | 回调函数,在回调函数中获取故障信息数组。
- value拿到故障信息数组;value为undefined表示获取过程中出现异常,error返回错误提示字符串 +**错误码:** + +以下错误码的详细介绍参见[ohos.faultLogger错误码](../errorcodes/errorcode-faultlogger.md)。 + +| 错误码ID | 错误信息 | +| --- | --- | +| 10600001 | The service is not started or is faulty | + **示例:** ```js @@ -79,14 +85,16 @@ function queryFaultLogCallback(error, value) { } } } -faultLogger.querySelfFaultLog(faultLogger.FaultType.JS_CRASH, queryFaultLogCallback); +try { + faultLogger.query(faultLogger.FaultType.JS_CRASH, queryFaultLogCallback); +} catch (err) { + console.error(`code: ${err.code}, message: ${err.message}`); +} ``` -## faultLogger.querySelfFaultLog(deprecated) - -querySelfFaultLog(faultType: FaultType) : Promise<Array<FaultLogInfo>> +## faultLogger.query9+ -> **说明:** 从 API Version 9 开始废弃,建议使用[faultLogger.query](#faultloggerquery9-1)替代。 +query(faultType: FaultType) : Promise<Array<FaultLogInfo>> 获取当前进程故障信息,该方法通过Promise方式返回故障信息数组,故障信息数组内最多上报10份故障信息。 @@ -104,32 +112,48 @@ querySelfFaultLog(faultType: FaultType) : Promise<Array<FaultLogInfo>&g | -------- | -------- | | Promise<Array<[FaultLogInfo](#faultloginfo)>> | Promise实例,可以在其then()方法中获取故障信息实例,也可以使用await。
- value拿到故障信息数组;value为undefined表示获取过程中出现异常 | +**错误码:** + +以下错误码的详细介绍参见[ohos.faultLogger错误码](../errorcodes/errorcode-faultlogger.md)。 + +| 错误码ID | 错误信息 | +| --- | --- | +| 10600001 | The service is not started or is faulty | + **示例:** ```js async function getLog() { - let value = await faultLogger.querySelfFaultLog(faultLogger.FaultType.JS_CRASH); - if (value) { - console.info("value length is " + value.length); - let len = value.length; - for (let i = 0; i < len; i++) { - console.info("log: " + i); - console.info("Log pid: " + value[i].pid); - console.info("Log uid: " + value[i].uid); - console.info("Log type: " + value[i].type); - console.info("Log timestamp: " + value[i].timestamp); - console.info("Log reason: " + value[i].reason); - console.info("Log module: " + value[i].module); - console.info("Log summary: " + value[i].summary); - console.info("Log text: " + value[i].fullLog); + try { + let value = await faultLogger.query(faultLogger.FaultType.JS_CRASH); + if (value) { + console.info("value length is " + value.length); + let len = value.length; + for (let i = 0; i < len; i++) { + console.info("log: " + i); + console.info("Log pid: " + value[i].pid); + console.info("Log uid: " + value[i].uid); + console.info("Log type: " + value[i].type); + console.info("Log timestamp: " + value[i].timestamp); + console.info("Log reason: " + value[i].reason); + console.info("Log module: " + value[i].module); + console.info("Log summary: " + value[i].summary); + console.info("Log text: " + value[i].fullLog); + } } + } catch (err) { + console.error(`code: ${err.code}, message: ${err.message}`); } } ``` -## faultLogger.query9+ +## faultLogger.querySelfFaultLog(deprecated) -query(faultType: FaultType, callback: AsyncCallback<Array<FaultLogInfo>>) : void +querySelfFaultLog(faultType: FaultType, callback: AsyncCallback<Array<FaultLogInfo>>) : void + +> **说明:** +> +> 从 API version 9 开始废弃,建议使用[faultLogger.query](#faultloggerquery9)替代。 获取当前进程故障信息,该方法通过回调方式获取故障信息数组,故障信息数组内最多上报10份故障信息。 @@ -142,14 +166,6 @@ query(faultType: FaultType, callback: AsyncCallback<Array<FaultLogInfo> | faultType | [FaultType](#faulttype) | 是 | 输入要查询的故障类型。 | | callback | AsyncCallback<Array<[FaultLogInfo](#faultloginfo)>> | 是 | 回调函数,在回调函数中获取故障信息数组。
- value拿到故障信息数组;value为undefined表示获取过程中出现异常,error返回错误提示字符串 -**错误码:** - -以下错误码的详细介绍参见[ohos.faultLogger错误码](../errorcodes/errorcode-faultlogger.md)。 - -| 错误码ID | 错误信息 | -| --- | --- | -| 10600001 | The service is not started or is faulty | - **示例:** ```js @@ -172,16 +188,16 @@ function queryFaultLogCallback(error, value) { } } } -try { - faultLogger.query(faultLogger.FaultType.JS_CRASH, queryFaultLogCallback); -} catch (err) { - console.error(`code: ${err.code}, message: ${err.message}`); -} +faultLogger.querySelfFaultLog(faultLogger.FaultType.JS_CRASH, queryFaultLogCallback); ``` -## faultLogger.query9+ +## faultLogger.querySelfFaultLog(deprecated) -query(faultType: FaultType) : Promise<Array<FaultLogInfo>> +querySelfFaultLog(faultType: FaultType) : Promise<Array<FaultLogInfo>> + +> **说明:** +> +> 从 API version 9 开始废弃,建议使用[faultLogger.query](#faultloggerquery9-1)替代。 获取当前进程故障信息,该方法通过Promise方式返回故障信息数组,故障信息数组内最多上报10份故障信息。 @@ -199,37 +215,25 @@ query(faultType: FaultType) : Promise<Array<FaultLogInfo>> | -------- | -------- | | Promise<Array<[FaultLogInfo](#faultloginfo)>> | Promise实例,可以在其then()方法中获取故障信息实例,也可以使用await。
- value拿到故障信息数组;value为undefined表示获取过程中出现异常 | -**错误码:** - -以下错误码的详细介绍参见[ohos.faultLogger错误码](../errorcodes/errorcode-faultlogger.md)。 - -| 错误码ID | 错误信息 | -| --- | --- | -| 10600001 | The service is not started or is faulty | - **示例:** ```js async function getLog() { - try { - let value = await faultLogger.query(faultLogger.FaultType.JS_CRASH); - if (value) { - console.info("value length is " + value.length); - let len = value.length; - for (let i = 0; i < len; i++) { - console.info("log: " + i); - console.info("Log pid: " + value[i].pid); - console.info("Log uid: " + value[i].uid); - console.info("Log type: " + value[i].type); - console.info("Log timestamp: " + value[i].timestamp); - console.info("Log reason: " + value[i].reason); - console.info("Log module: " + value[i].module); - console.info("Log summary: " + value[i].summary); - console.info("Log text: " + value[i].fullLog); - } + let value = await faultLogger.querySelfFaultLog(faultLogger.FaultType.JS_CRASH); + if (value) { + console.info("value length is " + value.length); + let len = value.length; + for (let i = 0; i < len; i++) { + console.info("log: " + i); + console.info("Log pid: " + value[i].pid); + console.info("Log uid: " + value[i].uid); + console.info("Log type: " + value[i].type); + console.info("Log timestamp: " + value[i].timestamp); + console.info("Log reason: " + value[i].reason); + console.info("Log module: " + value[i].module); + console.info("Log summary: " + value[i].summary); + console.info("Log text: " + value[i].fullLog); } - } catch (err) { - console.error(`code: ${err.code}, message: ${err.message}`); } } -``` +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-file-storage-statistics.md b/zh-cn/application-dev/reference/apis/js-apis-file-storage-statistics.md index 076072d2c1ba984bb5682fc4b55af8f3d91aa978..f918ebd6e7a9ee715f812cfc716216aa74a62f63 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-file-storage-statistics.md +++ b/zh-cn/application-dev/reference/apis/js-apis-file-storage-statistics.md @@ -22,8 +22,7 @@ getTotalSizeOfVolume(volumeUuid: string): Promise<number> **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 +**系统接口:** 该接口为系统接口。 **参数:** @@ -59,8 +58,7 @@ getTotalSizeOfVolume(volumeUuid: string, callback: AsyncCallback<number>): **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 +**系统接口:** 该接口为系统接口。 **参数:** @@ -90,8 +88,7 @@ getFreeSizeOfVolume(volumeUuid: string): Promise<number> **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 +**系统接口:** 该接口为系统接口。 **参数:** @@ -128,8 +125,7 @@ getFreeSizeOfVolume(volumeUuid: string, callback: AsyncCallback<number>): **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 +**系统接口:** 该接口为系统接口。 **参数:** @@ -159,8 +155,7 @@ getBundleStats(packageName: string): Promise<BundleStats> **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 +**系统接口:** 该接口为系统接口。 **参数:** @@ -196,8 +191,7 @@ getBundleStats(packageName: string, callback: AsyncCallback<BundleStats>) **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 +**系统接口:** 该接口为系统接口。 **参数:** @@ -263,12 +257,8 @@ getCurrentBundleStats(callback: AsyncCallback<BundleStats>): void ## BundleStats9+ -### 属性 - **系统能力**:以下各项对应的系统能力均为SystemCapability.FileManagement.StorageService.SpatialStatistics - - | 名称 | 类型 | 可读 | 可写 | 说明 | | --------- | ------ | --- | ---- | -------------- | | appSize | number | 是 | 否 | app数据大小(单位为Byte) | @@ -286,9 +276,7 @@ getTotalSize(): Promise<number> **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **返回值:** @@ -313,9 +301,7 @@ getTotalSize(callback: AsyncCallback<number>): void **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **参数:** @@ -343,9 +329,7 @@ getFreeSize(): Promise<number> **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **返回值:** @@ -371,9 +355,7 @@ getFreeSize(callback: AsyncCallback<number>): void **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **参数:** @@ -400,8 +382,7 @@ getSystemSize(): Promise<number> **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 +**系统接口:** 该接口为系统接口。 **返回值:** @@ -430,9 +411,7 @@ getSystemSize(callback: AsyncCallback<number>): void **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **参数:** @@ -459,9 +438,7 @@ getUserStorageStats(): Promise<StorageStats> **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **返回值:** @@ -489,9 +466,7 @@ getUserStorageStats(callback: AsyncCallback<StorageStats>): void **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **参数:** @@ -515,9 +490,7 @@ getUserStorageStats(userId: number): Promise<StorageStats> **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **参数:** @@ -552,9 +525,7 @@ getUserStorageStats(userId: number, callback: AsyncCallback<StorageStats>) **系统能力**:SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 - +**系统接口:** 该接口为系统接口。 **参数:** @@ -576,12 +547,9 @@ getUserStorageStats(userId: number, callback: AsyncCallback<StorageStats>) ## StorageStats9+ -### 属性 - **系统能力**:以下各项对应的系统能力均为SystemCapability.FileManagement.StorageService.SpatialStatistics - -该接口为系统接口。 +**系统接口:** 该接口为系统接口。 | 名称 | 类型 | 可读 | 可写 | 说明 | | --------- | ------ | ---- | ----- | -------------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-hichecker.md b/zh-cn/application-dev/reference/apis/js-apis-hichecker.md index b66101c41937973184db2f07fdbb06184173d37e..78d013ed259c3ef568ffe92899da7bcb5c103bf6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hichecker.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hichecker.md @@ -122,7 +122,9 @@ try { addRule(rule: bigint): void -> **说明:** 从 API Version 9 开始废弃,建议使用[hichecker.addCheckRule](#hicheckeraddcheckrule9)替代。 +> **说明:** +> +> 从 API version 9 开始废弃,建议使用[hichecker.addCheckRule](#hicheckeraddcheckrule9)替代。 添加一条或多条规则到系统,系统根据添加的规则进行检测或反馈。 @@ -149,7 +151,9 @@ hichecker.addRule( removeRule(rule: bigint): void -> **说明:** 从 API Version 9 开始废弃,建议使用[hichecker.removeCheckRule](#hicheckerremovecheckrule9)替代。 +> **说明:** +> +> 从 API version 9 开始废弃,建议使用[hichecker.removeCheckRule](#hicheckerremovecheckrule9)替代。 删除一条或多条规则,删除的规则后续将不再生效。 @@ -200,7 +204,9 @@ hichecker.getRule(); // return 1n; contains(rule: bigint): boolean -> **说明:** 从 API Version 9 开始废弃,建议使用[hichecker.containsCheckRule](#hicheckercontainscheckrule9)替代。 +> **说明:** +> +> 从 API version 9 开始废弃,建议使用[hichecker.containsCheckRule](#hicheckercontainscheckrule9)替代。 当前已添加的规则集中是否包含了某一个特定的规则,如果传入的规则级别为线程级别,则仅在当前线程中进行查询。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-hidebug.md b/zh-cn/application-dev/reference/apis/js-apis-hidebug.md index 66306729dc0da5f124d69eb0f9865c17b4259048..00157671eb6ecd995e45917b4ea767ff766871e1 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hidebug.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hidebug.md @@ -19,8 +19,6 @@ getNativeHeapSize(): bigint 获取本应用堆内存的总大小。 -本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。 - **系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug **返回值:** @@ -42,8 +40,6 @@ getNativeHeapAllocatedSize(): bigint 获取本应用堆内存的已分配内存大小。 -本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。 - **系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug **返回值:** @@ -65,8 +61,6 @@ getNativeHeapFreeSize(): bigint 获取本应用堆内存的空闲内存大小。 -本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。 - **系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug **返回值:** @@ -163,76 +157,6 @@ getCpuUsage(): number let cpuUsage = hidebug.getCpuUsage(); ``` -## hidebug.startProfiling(deprecated) - -startProfiling(filename : string) : void - -> **说明:** 从 API Version 9 开始废弃,建议使用[hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9)替代。 - -启动虚拟机Profiling方法跟踪,`startProfiling()`方法的调用需要与`stopProfiling()`方法的调用一一对应,先开启后关闭,严禁使用`start->start->stop`,`start->stop->stop`,`start->start->stop->stop`等类似的顺序调用。 - -**系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ------------------------------------------------------------ | -| filename | string | 是 | 用户自定义的profiling文件名,根据传入的`filename`,将在应用的`files`目录生成`filename.json`文件。 | - -**示例:** - -```js -hidebug.startProfiling("cpuprofiler-20220216"); -// code block -// ... -// code block -hidebug.stopProfiling(); -``` - - - -## hidebug.stopProfiling(deprecated) - -stopProfiling() : void - -> **说明:** 从 API Version 9 开始废弃,建议使用[hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9)替代。 - -停止虚拟机Profiling方法跟踪,`stopProfiling()`方法的调用需要与`startProfiling()`方法的调用一一对应,先开启后关闭,严禁使用`start->start->stop`,`start->stop->stop`,`start->start->stop->stop`等类似的顺序调用。 - -**系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug - -**示例:** - -```js -hidebug.startProfiling("cpuprofiler-20220216"); -// code block -// ... -// code block -hidebug.stopProfiling(); -``` - -## hidebug.dumpHeapData(deprecated) - -dumpHeapData(filename : string) : void - -> **说明:** 从 API Version 9 开始废弃,建议使用[hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9)替代。 - -虚拟机堆导出。 - -**系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ------------------------------------------------------------ | -| filename | string | 是 | 用户自定义的虚拟机堆文件名,根据传入的`filename`,将在应用的`files`目录生成`filename.heapsnapshot`文件。 | - -**示例:** - -```js -hidebug.dumpHeapData("heap-20220216"); -``` - ## hidebug.getServiceDump9+ getServiceDump(serviceid : number, fd : number, args : Array\) : void @@ -251,7 +175,6 @@ getServiceDump(serviceid : number, fd : number, args : Array\) : void | fd | number | 是 | 文件描述符,该接口会往该fd中写入数据。| | args | Array\ | 是 | 系统服务的Dump接口所对应的参数列表。| - **示例:** ```js @@ -359,4 +282,80 @@ try { console.info(error.code) console.info(error.message) } -``` \ No newline at end of file +``` + +## hidebug.startProfiling(deprecated) + +startProfiling(filename : string) : void + +> **说明:** +> +> 从 API version 9 开始废弃,建议使用[hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9)替代。 + +启动虚拟机Profiling方法跟踪,`startProfiling()`方法的调用需要与`stopProfiling()`方法的调用一一对应,先开启后关闭,严禁使用`start->start->stop`,`start->stop->stop`,`start->start->stop->stop`等类似的顺序调用。 + +**系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| filename | string | 是 | 用户自定义的profiling文件名,根据传入的`filename`,将在应用的`files`目录生成`filename.json`文件。 | + +**示例:** + +```js +hidebug.startProfiling("cpuprofiler-20220216"); +// code block +// ... +// code block +hidebug.stopProfiling(); +``` + + + +## hidebug.stopProfiling(deprecated) + +stopProfiling() : void + +> **说明:** +> +> 从 API version 9 开始废弃,建议使用[hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9)替代。 + +停止虚拟机Profiling方法跟踪,`stopProfiling()`方法的调用需要与`startProfiling()`方法的调用一一对应,先开启后关闭,严禁使用`start->start->stop`,`start->stop->stop`,`start->start->stop->stop`等类似的顺序调用。 + +**系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug + +**示例:** + +```js +hidebug.startProfiling("cpuprofiler-20220216"); +// code block +// ... +// code block +hidebug.stopProfiling(); +``` + +## hidebug.dumpHeapData(deprecated) + +dumpHeapData(filename : string) : void + +> **说明:** +> +> 从 API version 9 开始废弃,建议使用[hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9)替代。 + +虚拟机堆导出。 + +**系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| filename | string | 是 | 用户自定义的虚拟机堆文件名,根据传入的`filename`,将在应用的`files`目录生成`filename.heapsnapshot`文件。 | + +**示例:** + +```js +hidebug.dumpHeapData("heap-20220216"); +``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-http.md b/zh-cn/application-dev/reference/apis/js-apis-http.md index 3eada2b92b5d61165b5010f2f6c60f3d7be88974..afdc43e1e0896d996ac9512e096c6feef6666800 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-http.md +++ b/zh-cn/application-dev/reference/apis/js-apis-http.md @@ -799,7 +799,7 @@ httpRequest.off('dataProgress'); 发起请求可选参数的类型和取值范围。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | @@ -818,7 +818,7 @@ httpRequest.off('dataProgress'); HTTP 请求方法。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 值 | 说明 | | :------ | ------- | :------------------ | @@ -835,7 +835,7 @@ HTTP 请求方法。 发起请求返回的响应码。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 值 | 说明 | | ----------------- | ---- | ------------------------------------------------------------ | @@ -879,7 +879,7 @@ HTTP 请求方法。 request方法回调函数的返回值类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-connection.md b/zh-cn/application-dev/reference/apis/js-apis-net-connection.md index cfd1405bc9385985c34cee0500f6a82aa9e7cf98..585fb77a29c59dc7a361eb306c646879da8f6b09 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-connection.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-connection.md @@ -1801,7 +1801,7 @@ connection.getDefaultNet().then(function (netHandle) { 网络具体能力。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 名称 | 值 | 说明 | | ------------------------ | ---- | ---------------------- | @@ -1815,7 +1815,7 @@ connection.getDefaultNet().then(function (netHandle) { 网络类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 名称 | 值 | 说明 | | --------------- | ---- | ----------- | @@ -1839,7 +1839,7 @@ connection.getDefaultNet().then(function (netHandle) { 提供承载数据网络能力的实例。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 名称 | 类型 | 必填 | 说明 | | ----------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ | @@ -1850,7 +1850,7 @@ connection.getDefaultNet().then(function (netHandle) { 网络的能力集。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 名称 | 类型 | 必填 | 说明 | | --------------------- | ---------------------------------- | --- | ------------------------ | @@ -1863,7 +1863,7 @@ connection.getDefaultNet().then(function (netHandle) { 网络连接信息。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 名称 | 类型 | 必填 | 说明 | | ------------- | ---------------------------------- | ----|---------------- | @@ -1878,7 +1878,7 @@ connection.getDefaultNet().then(function (netHandle) { 网络路由信息。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 名称 | 类型 | 必填 |说明 | | -------------- | --------------------------- | --- |---------------- | @@ -1892,7 +1892,7 @@ connection.getDefaultNet().then(function (netHandle) { 网络链路信息。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 名称 | 类型 | 必填 |说明 | | ------------ | ----------------------- |---- |-------------------- | @@ -1903,7 +1903,7 @@ connection.getDefaultNet().then(function (netHandle) { 网络地址。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 名称 | 类型 | 必填 | 说明 | | ------- | ------ | -- |------------------------------ | diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md b/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md index 823f3f1aa66f05d8d518deeb7c6d43fcba681282..8fcb75209c766a0ca3b7ab20868b1ba4de9dec2a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md @@ -392,7 +392,7 @@ ethernet.getAllActiveIfaces().then((data) => { **系统接口**:此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Ethernet。 +**系统能力**:SystemCapability.Communication.NetManager.Ethernet | 名称 | 类型 | 必填 | 说明 | | ------------ | ----------------------- | ---|------------------------------------------------------------ | @@ -409,7 +409,7 @@ ethernet.getAllActiveIfaces().then((data) => { **系统接口**:此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Ethernet。 +**系统能力**:SystemCapability.Communication.NetManager.Ethernet | 名称 | 值 | 说明 | | ------------------------ | ---- | ---------------------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-policy.md b/zh-cn/application-dev/reference/apis/js-apis-net-policy.md index a628c3346a7f923f1c170b340d922fa2336882bc..b585364ba9fcbd70b639acc858858a704d0c7ce9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-policy.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-policy.md @@ -1479,7 +1479,7 @@ policy.on('netBackgroundPolicyChange', (data) => { 后台网络策略。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 参数名 | 值 | 说明 | | ------------------------ | ---- | ---------------------- | @@ -1492,7 +1492,7 @@ policy.on('netBackgroundPolicyChange', (data) => { 计量网络策略。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 参数名 | 类型 | 说明 | | ----------------------- | ----------------------------------- | ------------------------------------------------------------ | @@ -1511,7 +1511,7 @@ policy.on('netBackgroundPolicyChange', (data) => { 限制动作。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 参数名 | 值 | 说明 | | ---------------------- | ----- | ------------ | @@ -1523,7 +1523,7 @@ policy.on('netBackgroundPolicyChange', (data) => { 计量网络规则。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 参数名 | 值 | 说明 | | ---------------------- | ----- | ------------ | @@ -1538,7 +1538,7 @@ policy.on('netBackgroundPolicyChange', (data) => { 提醒类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 参数名 | 值 | 说明 | | ---------------------- | - | ------- | @@ -1549,7 +1549,7 @@ policy.on('netBackgroundPolicyChange', (data) => { 应用对应的网络策略。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 +**系统能力**:SystemCapability.Communication.NetManager.Core | 参数名 | 值 | 说明 | | ---------------------- | ----- | ------------ | diff --git a/zh-cn/application-dev/reference/apis/js-apis-observer.md b/zh-cn/application-dev/reference/apis/js-apis-observer.md index 0e0708d456af551f68b2c3b9348dcfccdc0c6ba1..2ce5d1b826742fc78922a62d5afb4dd29c5b9fd2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-observer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-observer.md @@ -705,7 +705,7 @@ observer.off('simStateChange'); SIM卡锁类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.StateRegistry。 +**系统能力**:SystemCapability.Telephony.StateRegistry | 名称 | 值 | 说明 | | ----------- | ---- | ----------------- | @@ -728,11 +728,11 @@ SIM卡锁类型。 SIM卡类型和状态。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.StateRegistry。 +**系统能力**:SystemCapability.Telephony.StateRegistry | 名称 | 类型 | 必填 | 说明 | | ------------------- | ----------------------------------- | ---- | -------------------------------------------------------- | -| type | [CardType](js-apis-sim.md#cardtype) | 是 | SIM卡类型,参考sim的[CardType](js-apis-sim.md#cardtype)。 | -| state | [SimState](js-apis-sim.md#simstate) | 是 | SIM卡状态,参考sim的[SimState](js-apis-sim.md#simstate)。 | +| type | [CardType](js-apis-sim.md#cardtype7) | 是 | SIM卡类型。 | +| state | [SimState](js-apis-sim.md#simstate) | 是 | SIM卡状态。 | | reason8+ | [LockReason](#lockreason8) | 是 | SIM卡锁类型。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-radio.md b/zh-cn/application-dev/reference/apis/js-apis-radio.md index 80d1801bcda2eac7589d69c97596537e3f983154..8d7a979cd11d6d5e0f468677580f5ea6232ad584 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-radio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-radio.md @@ -2491,7 +2491,7 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { 无线接入技术。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | ------------------------- | ---- | ------------------------------------------------------------ | @@ -2514,7 +2514,7 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { 网络信号强度信息对象。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | --------------- | --------------------------- | ---- | ------------------ | @@ -2526,7 +2526,7 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { 网络类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | -------------------- | ---- | ------------------------------------------------------------ | @@ -2542,7 +2542,7 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { 网络注册状态。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | -------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ | @@ -2561,7 +2561,7 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { 网络注册状态。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | ----------------------------- | ---- | -------------------------- | @@ -2575,7 +2575,7 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { 非独立组网状态。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | -------------------------- | ---- | ---------------------------------------------------------- | @@ -2591,7 +2591,7 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { 选网模式。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | --------------------------- | ---- | -------------- | @@ -2605,7 +2605,7 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | --------------------------------------------------------- | ---- | --------------------------------------------- | @@ -2650,7 +2650,7 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ----------------- | --------------------------------------- | ---- | ------------------------------------------------------------ | @@ -2666,7 +2666,7 @@ CDMA小区信息。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | --------- | ------ | ---- | ------------ | @@ -2682,7 +2682,7 @@ GSM小区信息。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | -------------------- | @@ -2699,7 +2699,7 @@ LTE小区信息。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ------------- | ------- | ---- | ----------------------- | @@ -2718,7 +2718,7 @@ NR小区信息。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ---------------- | @@ -2735,7 +2735,7 @@ TD-SCDMA小区信息。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------------ | @@ -2752,7 +2752,7 @@ WCDMA小区信息。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------------ | @@ -2769,7 +2769,7 @@ NR的选择模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | -------------------- | ---- | ---------------------------------- | @@ -2784,7 +2784,7 @@ NR的选择模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ---------------------- | ------------------------------------------------- | ---- | -------------- | @@ -2797,7 +2797,7 @@ NR的选择模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | --------------- | --------------------------------------------------- | ---- | -------------- | @@ -2812,7 +2812,7 @@ NR的选择模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | ----------------- | ---- | ---------------- | @@ -2827,7 +2827,7 @@ NR的选择模式。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ------------------ | --------------------------------------------- | ---- | -------------------------------------- | @@ -2842,7 +2842,7 @@ IMS注册状态。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | ---------------- | ---- | -------- | @@ -2855,7 +2855,7 @@ IMS注册技术。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | ----------------------- | ---- | --------------- | @@ -2870,7 +2870,7 @@ IMS注册信息。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ----------- | ---------------------------- | ---- | ------------- | @@ -2883,7 +2883,7 @@ IMS服务类型。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | ---------- | ---- | ---------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-sim.md b/zh-cn/application-dev/reference/apis/js-apis-sim.md index 408bdbf7e5132abfbd8c03275b91d164c6c1ce54..84b8819489f66df5b952a0bec859e4d93e80307a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-sim.md +++ b/zh-cn/application-dev/reference/apis/js-apis-sim.md @@ -3865,7 +3865,7 @@ try { SIM卡状态。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | --------------------- | ---- | ---------------------------------------------------------- | @@ -3880,7 +3880,7 @@ SIM卡状态。 卡类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | ----- | ----- | ----- | @@ -3901,7 +3901,7 @@ SIM卡状态。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | -------- | ---- | ----------- | @@ -3914,7 +3914,7 @@ SIM卡状态。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | -------- | ---- | ---------- | @@ -3927,7 +3927,7 @@ SIM卡状态。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | ------------ | ---- | ----------------------------------------------- | @@ -3948,7 +3948,7 @@ SIM卡状态。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | --------------- | ------ | ---- | --------------------- | @@ -3961,7 +3961,7 @@ SIM卡状态。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | -------- | @@ -3975,7 +3975,7 @@ SIM卡状态。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | -------- | -------------------------------- | ---- | ------------- | @@ -3988,7 +3988,7 @@ Icc账户信息。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ---------- | ------- | ---- | ---------------- | @@ -4006,7 +4006,7 @@ Icc账户信息。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ---- | @@ -4019,7 +4019,7 @@ Icc账户信息。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 类型 | 必填 | 说明 | | ------------ | ------ | ---- | ---------- | @@ -4034,7 +4034,7 @@ Icc账户信息。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | --------------- | ---- | ---------- | @@ -4047,7 +4047,7 @@ Icc账户信息。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 +**系统能力**:SystemCapability.Telephony.CoreService | 名称 | 值 | 说明 | | ------------------------------------------------------- | ------------------------------------------------------ | -------------------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-sms.md b/zh-cn/application-dev/reference/apis/js-apis-sms.md index 79dc88086eb5aa15f9bfcbf9c9535b58fd09b5ab..7d534126be576c6ac9dd266ae8e1f1a466e8e3b6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-sms.md +++ b/zh-cn/application-dev/reference/apis/js-apis-sms.md @@ -1453,7 +1453,7 @@ promise.then(data => { 短信实例。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ------------------------ | --------------------------------------- | ---- | ------------------------------------------------------------ | @@ -1474,7 +1474,7 @@ promise.then(data => { 短信类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | ---------------- | ---- | ---------------------------------------- | @@ -1489,7 +1489,7 @@ promise.then(data => { 发送短信的参数和回调。根据SendMessageOptions中的可选参数content的值判断短信类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ---------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | @@ -1506,7 +1506,7 @@ promise.then(data => { 回调实例。返回短信发送结果、存储已发送短信的URI和是否为长短信的最后一部分。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ---------- | ------------------------------- | ---- | ----------------------------------------------------------------------------------------- | @@ -1519,7 +1519,7 @@ promise.then(data => { 回调实例,返回短信送达报告。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ---- | ------------------- | ---- | -------------- | @@ -1530,7 +1530,7 @@ promise.then(data => { 短信发送结果。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | ------------------------------------ | ---- | ------------------------------------------------------ | @@ -1545,7 +1545,7 @@ promise.then(data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ----------- | ------------------------------------------------------------ | ---- | ---------- | @@ -1559,7 +1559,7 @@ promise.then(data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ---------------- | ------------------------------------ | ---- | ------------ | @@ -1585,7 +1585,7 @@ promise.then(data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ------------- | ---------------------------------- | ---- | -------- | @@ -1600,7 +1600,7 @@ promise.then(data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | --------------- | ---------------------------------- | ---- | -------- | @@ -1621,7 +1621,7 @@ promise.then(data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ------------- | ---------------------------------- | ---- | -------- | @@ -1635,7 +1635,7 @@ promise.then(data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | -------------- | ------------------------------------ | ---- | -------- | @@ -1660,7 +1660,7 @@ promise.then(data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ---------- | ---------------------------------- | ---- | -------- | @@ -1677,7 +1677,7 @@ promise.then(data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ---------- | ---------------------------------- | ---- | -------- | @@ -1694,7 +1694,7 @@ promise.then(data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ----------------------- | ------------------------------------ | ---- | ------------------ | @@ -1715,7 +1715,7 @@ promise.then(data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ------- | ---------------------------- | ---- | ------ | @@ -1728,7 +1728,7 @@ promise.then(data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | ------------------------- | ---- | -------------------- | @@ -1748,7 +1748,7 @@ promise.then(data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | ---------- | ---- | -------------- | @@ -1762,7 +1762,7 @@ promise.then(data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | --------------- | ---- | ----------- | @@ -1777,7 +1777,7 @@ promise.then(data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | --------------- | ------ | ------------------- | @@ -1802,7 +1802,7 @@ promise.then(data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | ---------- | ---- | -------- | @@ -1816,7 +1816,7 @@ promise.then(data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | ------- | ---- | ---- | @@ -1829,7 +1829,7 @@ promise.then(data => { **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | -------------- | -------------------- | ---- | ------------ | @@ -1845,7 +1845,7 @@ SIM卡消息状态。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | ------------------------- | ---- | --------------------------- | @@ -1861,7 +1861,7 @@ SIM卡消息状态。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | --------- | ---- | ---- | @@ -1874,7 +1874,7 @@ SIM卡消息状态。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 值 | 说明 | | -------------------- | ---- | ------------ | @@ -1889,7 +1889,7 @@ SIM卡消息选项。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ------ | -------------------------------------- | ---- | -------------- | @@ -1904,7 +1904,7 @@ SIM卡消息选项。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | --------- | -------------------------------------- | ---- | -------------- | @@ -1920,7 +1920,7 @@ SIM卡短消息。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ---------------- | -------------------------------------- | ---- | ------------- | @@ -1934,7 +1934,7 @@ SIM卡短消息。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | --------- | ---------------------------------- | ---- | ------ | @@ -1950,7 +1950,7 @@ SIM卡短消息。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | ------------- | ---------------------------------- | ---- | -------- | @@ -1965,7 +1965,7 @@ SIM卡短消息。 **系统接口:** 此接口为系统接口。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.SmsMms。 +**系统能力**:SystemCapability.Telephony.SmsMms | 名称 | 类型 | 必填 | 说明 | | -------------------- | ---------------------------------------- | ---- | ------------ | diff --git a/zh-cn/application-dev/reference/apis/js-apis-socket.md b/zh-cn/application-dev/reference/apis/js-apis-socket.md index 532cde6b6ef44a6097fed6c0cad2feccce0635d9..7c005e050863732e1af8ea6b4003135aeac1a1fe 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-socket.md +++ b/zh-cn/application-dev/reference/apis/js-apis-socket.md @@ -656,7 +656,7 @@ udp.off('error'); 目标地址信息。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ------------------------------------------------------------ | @@ -668,7 +668,7 @@ udp.off('error'); UDPSocket发送参数。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | ------- | ---------------------------------- | ---- | -------------- | @@ -679,7 +679,7 @@ UDPSocket发送参数。 UDPSocket连接的其他属性。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | ----------------- | ------- | ---- | -------------------------------- | @@ -693,7 +693,7 @@ UDPSocket连接的其他属性。 Socket的状态信息。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | ----------- | ------- | ---- | ---------- | @@ -705,7 +705,7 @@ Socket的状态信息。 Socket的连接信息。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ------------------------------------------------------------ | @@ -1560,7 +1560,7 @@ tcp.off('error'); TCPSocket连接的参数。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | ------- | ---------------------------------- | ---- | -------------------------- | @@ -1571,7 +1571,7 @@ TCPSocket连接的参数。 TCPSocket发送请求的参数。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ------------------------------------------------------------ | @@ -1582,7 +1582,7 @@ TCPSocket发送请求的参数。 TCPSocket连接的其他属性。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | ----------------- | ------- | ---- | ------------------------------------------------------------ | diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-cipher.md b/zh-cn/application-dev/reference/apis/js-apis-system-cipher.md index d3177f567f6c1d9f7fc12832273cb17456a4a2d1..b87349eb95221cd68f45e90b7665ceef1e7d3a49 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-cipher.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-cipher.md @@ -4,7 +4,7 @@ > > 本模块首批接口从API version 3开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > -> 从API version 9开始废弃, 建议使用[cryptoFramework-Cipher](js-apis-cryptoFramework.md#Cipher)替代。 +> 从API version 9开始废弃, 建议使用[@ohos.security.cryptoFramework的Cipher](js-apis-cryptoFramework.md#Cipher)替代。 ## 导入模块 diff --git a/zh-cn/application-dev/reference/apis/js-apis-telephony-data.md b/zh-cn/application-dev/reference/apis/js-apis-telephony-data.md index 4c45003ae56d2bd5b253901faa994088caeabd98..60975406d50dcddf6f4c49360693f89289ee178c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-telephony-data.md +++ b/zh-cn/application-dev/reference/apis/js-apis-telephony-data.md @@ -754,7 +754,7 @@ promise.then((data) => { 描述蜂窝数据流类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CellularData。 +**系统能力**:SystemCapability.Telephony.CellularData | 名称 | 值 | 说明 | | ---------------------- | ---- | ------------------------------------------ | @@ -768,7 +768,7 @@ promise.then((data) => { 描述蜂窝数据链路连接状态。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CellularData。 +**系统能力**:SystemCapability.Telephony.CellularData | 名称 | 值 | 说明 | | ----------------------- | ---- | -------------------------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-webSocket.md b/zh-cn/application-dev/reference/apis/js-apis-webSocket.md index 44f660731b199285cc744066b702934a6513c17f..b73344ad3ad60ecd0cc36dcec11c15cdd14c2b96 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-webSocket.md +++ b/zh-cn/application-dev/reference/apis/js-apis-webSocket.md @@ -645,7 +645,7 @@ ws.off('error'); 建立WebSocket连接时,可选参数的类型和说明。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------------------------------------------------------------ | @@ -656,7 +656,7 @@ ws.off('error'); 关闭WebSocket连接时,可选参数的类型和说明。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 名称 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------------------------------------------------------------ | @@ -667,7 +667,7 @@ ws.off('error'); 发送给服务端的错误码可以自行定义,下面的列表仅供参考。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 +**系统能力**:SystemCapability.Communication.NetStack | 值 | 说明 | | :-------- | :----------------- |