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

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

Merge pull request !16136 from shawn_he/14820-b
# HTTP Data Request # HTTP Data Request
## Use Cases ## When to Use
An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
...@@ -14,40 +14,49 @@ For details about how to apply for permissions, see [Access Control Development] ...@@ -14,40 +14,49 @@ For details about how to apply for permissions, see [Access Control Development]
The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md). The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md).
| API | Description | | API | Description |
| ----------------------------------------- | --------------------------------------------------------- | | ----------------------------------------- | ----------------------------------- |
| createHttp() | Creates an HTTP request. | | createHttp() | Creates an HTTP request. |
| request() | Initiates an HTTP request to a given URL. | | request() | Initiates an HTTP request to a given URL. |
| destroy() | Destroys an HTTP request. | | request2()<sup>10+</sup> | Initiates an HTTP network request based on the URL and returns a streaming response.|
| destroy() | Destroys an HTTP request. |
| on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. | | on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. |
| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events. | | off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events.|
| once\('headersReceive'\)<sup>8+</sup> | Registers a one-time observer for HTTP Response Header events.|
| on\('dataReceive'\)<sup>10+</sup> | Registers an observer for events indicating receiving of HTTP streaming responses. |
| off\('dataReceive'\)<sup>10+</sup> | Unregisters the observer for events indicating receiving of HTTP streaming responses. |
| on\('dataEnd'\)<sup>10+</sup> | Registers an observer for events indicating completion of receiving HTTP streaming responses. |
| off\('dataEnd'\)<sup>10+</sup> | Unregisters the observer for events indicating completion of receiving HTTP streaming responses.|
| on\('dataProgress'\)<sup>10+</sup> | Registers an observer for events indicating progress of receiving HTTP streaming responses. |
| off\('dataProgress'\)<sup>10+</sup> | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.|
## How to Develop ## How to Develop
1. Import the required HTTP module. 1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Create an **HttpRequest** object. 2. Call **createHttp()** to create an **HttpRequest** object.
3. (Optional) Listen for HTTP Response Header events. 3. Call **httpRequest.on()** to subscribe to HTTP response header events. This API returns a response earlier than the request. You can subscribe to HTTP response header events based on service requirements.
4. Initiate an HTTP request to a given URL. 4. Call **httpRequest.request()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
5. (Optional) Process the HTTP Response Header event and the return result of the HTTP request. 5. Parse the returned result based on service requirements.
6. Call **off()** to unsubscribe from HTTP response header events.
7. Call **httpRequest.destroy()** to release resources after the request is processed.
```js ```js
// Import the http namespace.
import http from '@ohos.net.http'; import http from '@ohos.net.http';
// Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused. // Each httpRequest corresponds to an HTTP request task and cannot be reused.
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
// This API is used to listen for the HTTP Response Header event, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP Response Header events.
// Subscribe to the HTTP response header, which is returned earlier than HttpRequest. You can subscribe to HTTP Response Header events based on service requirements. // on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+
httpRequest.on('headersReceive', (header) => { httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header)); console.info('header: ' + JSON.stringify(header));
}); });
httpRequest.request( httpRequest.request(
// Set the URL of the HTTP request. You need to define the URL. Set the parameters of the request in extraData. // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL", "EXAMPLE_URL",
{ {
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add the header field based on service requirements. // You can add header fields based on service requirements.
header: { header: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
...@@ -55,21 +64,33 @@ httpRequest.request( ...@@ -55,21 +64,33 @@ httpRequest.request(
extraData: { extraData: {
"data": "data to send", "data": "data to send",
}, },
connectTimeout: 60000, // Optional. The default value is 60000, in ms. expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
usingCache: true, // Optional. The default value is true.
priority: 1, // Optional. The default value is 1.
connectTimeout: 60000 // Optional. The default value is 60000, in ms.
readTimeout: 60000, // Optional. The default value is 60000, in ms. readTimeout: 60000, // Optional. The default value is 60000, in ms.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10.
}, (err, data) => { }, (err, data) => {
if (!err) { if (!err) {
// data.result contains the HTTP response. Parse the response based on service requirements. // data.result carries the HTTP response. Parse the response based on service requirements.
console.info('Result:' + data.result); console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + data.responseCode); console.info('code:' + JSON.stringify(data.responseCode));
// data.header contains the HTTP response header. Parse the content based on service requirements. // data.header carries the HTTP response header. Parse the content based on service requirements.
console.info('header:' + JSON.stringify(data.header)); console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+ console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
} else { } else {
console.info('error:' + JSON.stringify(err)); console.info('error:' + JSON.stringify(err));
// Call the destroy() method to destroy the request if it is no longer needed. // Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy(); httpRequest.destroy();
} }
} }
); );
``` ```
## Samples
The following sample is provided to help you better understand how to develop the HTTP data request feature:
- [`HTTP`: Data Request (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http)
- [HTTP Communication (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH)
# Socket Connection # Socket Connection
## Introduction
## Use Cases The Socket Connection module allows an application to transmit data over a Socket connection through the TCP, UDP, or TLS protocol.
Your application can transmit data through Socket connections. Currently, the TCP and UDP protocols are supported. ## Basic Concepts
- Socket: An abstraction of endpoints for bidirectional communication between application processes running on different hosts in a network.
- TCP: Transmission Control Protocol, which is a byte stream–based transport layer communication protocol that is connection-oriented and reliable.
- UDP: User Datagram Protocol, which is a simple datagram-oriented transport layer communication protocol.
- TLS: Transport Layer Security, which is a protocol that ensures the data confidentiality and integrity between communication programs.
## When to Use
Applications transmit data over TCP, UDP, or TLS Socket connections. The main application scenarios are as follows:
- Implementing data transmission over TCP/UDP Socket connections
- Implementing encrypted data transmission over TLS Socket connections
## Available APIs ## Available APIs
The Socket connection function is mainly implemented by the Socket module. The following table describes the related APIs. For the complete list of APIs and example code, see [Socket Connection](../reference/apis/js-apis-socket.md).
Socket connection functions are mainly implemented by the **socket** module. The following table describes the related APIs.
| API| Description | | API| Description|
| -------- | -------- | | -------- | -------- |
| constructUDPSocketInstance() | Creates a **UDPSocket** object. | | constructUDPSocketInstance() | Creates a **UDPSocket** object.|
| constructTCPSocketInstance() | Creates a **TCPSocket** object. | | constructTCPSocketInstance() | Creates a **TCPSocket** object.|
| bind() | Binds the IP address and port number. | | bind() | Binds the IP address and port number.|
| send() | Sends data.| | send() | Sends data.|
| close() | Closes a Socket connection. | | close() | Closes a Socket connection.|
| getState() | Obtains the Socket connection status. | | getState() | Obtains the Socket connection status.|
| connect() | Connects to the specified IP address and port. This function is supported only for TCP. | | connect() | Connects to the specified IP address and port. This function is supported only for TCP.|
| getRemoteAddress() | Obtains the peer address of the Socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API. | | getRemoteAddress() | Obtains the peer address of the Socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API.|
| on(type:&nbsp;'message') | Enables listening for **message** events of the Socket connection. | | on(type:&nbsp;'message') | Subscribes to **message** events of the Socket connection.|
| off(type:&nbsp;'message') | Disables listening for **message** events of the Socket connection. | | off(type:&nbsp;'message') | Unsubscribes from **message** events of the Socket connection.|
| on(type:&nbsp;'close') | Enables listening for **close** events of the Socket connection. | | on(type:&nbsp;'close') | Subscribes to **close** events of the Socket connection.|
| off(type:&nbsp;'close') | Disables listening for **close** events of the Socket connection. | | off(type:&nbsp;'close') | Unsubscribes from **close** events of the Socket connection.|
| on(type:&nbsp;'error') | Enables listening for **error** events of the Socket connection. | | on(type:&nbsp;'error') | Subscribes to **error** events of the Socket connection.|
| off(type:&nbsp;'error') | Disables listening for **error** events of the Socket connection. | | off(type:&nbsp;'error') | Unsubscribes from **error** events of the Socket connection.|
| on(type:&nbsp;'listening') | Enables listening for **listening** events of the UDPSocket connection. | | on(type:&nbsp;'listening') | Subscribes to **listening** events of the UDP Socket connection. |
| off(type:&nbsp;'listening') | Disables listening for **listening** events of the UDPSocket connection. | | off(type:&nbsp;'listening') | Unsubscribes from **listening** events of the UDP Socket connection. |
| on(type:&nbsp;'connect') | Enables listening for **connect** events of the TCPSocket connection. | | on(type:&nbsp;'connect') | Subscribes to **connect** events of the TCP Socket connection. |
| off(type:&nbsp;'connect') | Disables listening for **connect** events of the TCPSocket connection. | | off(type:&nbsp;'connect') | Unsubscribes from **connect** events of the TCP Socket connection.|
TLS Socket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs.
| API| Description|
| -------- | -------- |
| constructTLSSocketInstance() | Creates a **TLSSocket** object.|
| bind() | Binds the IP address and port number.|
| close(type:&nbsp;'error') | Closes a Socket connection.|
| connect() | Sets up a connection to the specified IP address and port number.|
| getCertificate() | Obtains an object representing the local certificate.|
| getCipherSuite() | Obtains a list containing information about the negotiated cipher suite.|
| getProtocol() | Obtains a string containing the SSL/TLS protocol version negotiated for the current connection.|
| getRemoteAddress() | Obtains the peer address of the TLS Socket connection.|
| getRemoteCertificate() | Obtains an object representing a peer certificate.|
| getSignatureAlgorithms() | Obtains a list containing signature algorithms shared between the server and client, in descending order of priority.|
| getState() | Obtains the TLS Socket connection status.|
| off(type:&nbsp;'close') | Unsubscribes from **close** events of the TLS Socket connection.|
| off(type:&nbsp;'error') | Unsubscribes from **error** events of the TLS Socket connection.|
| off(type:&nbsp;'message') | Unsubscribes from **message** events of the TLS Socket connection.|
| on(type:&nbsp;'close') | Subscribes to **close** events of the TLS Socket connection.|
| on(type:&nbsp;'error') | Subscribes to **error** events of the TLS Socket connection.|
| on(type:&nbsp;'message') | Subscribes to **message** events of the TLS Socket connection.|
| send() | Sends data.|
| setExtraOptions() | Sets other properties of the TLS Socket connection.|
## How to Develop ## Transmitting Data over TCP/UDP Socket Connections
The implementation is similar for UDPSocket and TCPSocket. The following uses the TCPSocket as an example. The implementation is similar for UDP Socket and TCP Socket connections. The following uses data transmission over a TCP Socket connection as an example.
1. Import the required Socket module. 1. Import the required **socket** module.
2. Create a **TCPSocket** object. 2. Create a **TCPSocket** object.
3. (Optional) Enable listening for TCPSocket events. 3. (Optional) Subscribe to TCP Socket connection events.
4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system. 4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system.
...@@ -48,15 +85,15 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -48,15 +85,15 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
6. Send data. 6. Send data.
7. Enable the TCPSocket connection to be automatically closed after use. 7. Enable the TCP Socket connection to be automatically closed after use.
```js ```js
import socket from '@ohos.net.socket' import socket from '@ohos.net.socket'
// Create a TCPSocket object. // Create a TCPSocket object.
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
// Enable listening for TCPSocket events. // Subscribe to TCP Socket connection events.
tcp.on('message', value => { tcp.on('message', value => {
console.log("on message") console.log("on message")
let buffer = value.message let buffer = value.message
...@@ -73,7 +110,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -73,7 +110,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
tcp.on('close', () => { tcp.on('close', () => {
console.log("on close") console.log("on close")
}); });
// Bind the local IP address and port number. // Bind the local IP address and port number.
let bindAddress = { let bindAddress = {
address: '192.168.xx.xx', address: '192.168.xx.xx',
...@@ -86,6 +123,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -86,6 +123,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
return; return;
} }
console.log('bind success'); console.log('bind success');
// Set up a connection to the specified IP address and port number. // Set up a connection to the specified IP address and port number.
let connectAddress = { let connectAddress = {
address: '192.168.xx.xx', address: '192.168.xx.xx',
...@@ -100,6 +138,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -100,6 +138,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
return; return;
} }
console.log('connect success'); console.log('connect success');
// Send data. // Send data.
tcp.send({ tcp.send({
data: 'Hello, server!' data: 'Hello, server!'
...@@ -112,7 +151,8 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -112,7 +151,8 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
}) })
}); });
}); });
// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket events.
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
setTimeout(() => { setTimeout(() => {
tcp.close((err) => { tcp.close((err) => {
console.log('close socket.') console.log('close socket.')
...@@ -122,3 +162,167 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -122,3 +162,167 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
tcp.off('close'); tcp.off('close');
}, 30 * 1000); }, 30 * 1000);
``` ```
## Implementing Encrypted Data Transmission over TLS Socket Connections
### How to Develop
TLS Socket connection process on the client:
1. Import the required **socket** module.
2. Bind the IP address and port number of the server.
3. For two-way authentication, upload the client CA certificate and digital certificate. For one-way authentication, upload the client CA certificate.
4. Create a **TLSSocket** object.
5. (Optional) Subscribe to TLS Socket connection events.
6. Send data.
7. Enable the TLS Socket connection to be automatically closed after use.
```js
import socket from '@ohos.net.socket'
// Create a TLS Socket connection (for two-way authentication).
let tlsTwoWay = socket.constructTLSSocketInstance();
// Subscribe to TLS Socket connection events.
tcp.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0; i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log("on connect received:" + str)
});
tcp.on('connect', () => {
console.log("on connect")
});
tcp.on('close', () => {
console.log("on close")
});
// Bind the local IP address and port number.
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
// Set the communication parameters.
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
// Set up a connection to the specified IP address and port number.
address: {
address: "192.168.xx.xxx",
port: xxxx, // Port
family: 1,
},
// Set the parameters used for authentication during communication.
secureOptions: {
key: "xxxx", // Key
cert: "xxxx", // Digital certificate
ca: ["xxxx"], // CA certificate
passwd: "xxxx", // Password for generating the key
protocols: [socket.Protocol.TLSv12], // Communication protocol
useRemoteCipherPrefer: true, // Whether to preferentially use the peer cipher suite
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // Signature algorithm
cipherSuite: "AES256-SHA256", // Cipher suite
},
};
// Set up a connection.
tlsTwoWay.connect(options, (err, data) => {
console.error(err);
console.log(data);
});
// Enable the TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events.
tls.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
tls.off('message');
tls.off('connect');
tls.off('close');
});
// Create a TLS Socket connection (for one-way authentication).
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
// Subscribe to TLS Socket connection events.
tcp.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0;i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log("on connect received:" + str)
});
tcp.on('connect', () => {
console.log("on connect")
});
tcp.on('close', () => {
console.log("on close")
});
// Bind the local IP address and port number.
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
// Set the communication parameters.
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"], // CA certificate
cipherSuite: "AES256-SHA256", // Cipher suite
},
};
// Set up a connection.
tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err);
console.log(data);
});
// Enable the TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events.
tls.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
tls.off('message');
tls.off('connect');
tls.off('close');
});
```
## Samples
The following samples are provided to help you better understand how to develop Socket connection features:
- [`Socket`: Socket Connection (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket)
- [UDP Socket (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/UdpDemoOH)
- [TCP Socket (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/TcpSocketDemo)
...@@ -77,43 +77,48 @@ When designing a color picker, you can have the mouse pointer switched to the co ...@@ -77,43 +77,48 @@ When designing a color picker, you can have the mouse pointer switched to the co
5. Set the mouse pointer to the default style. 5. Set the mouse pointer to the default style.
```js ```js
import pointer from '@ohos.multimodalInput.pointer';
import window from '@ohos.window'; import window from '@ohos.window';
// 1. Enable the color pickup function. // 1. Enable the color pickup function.
// 2. Obtain the window ID. // 2. Obtain the window ID.
window.getTopWindow((error, windowClass) => { window.getLastWindow(this.context, (error, windowClass) => {
windowClass.getProperties((error, data) => { if (error.code) {
var windowId = data.id; console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
if (windowId < 0) { return;
console.log(`Invalid windowId`); }
return; var windowId = windowClass.getWindowProperties().id;
} if (windowId < 0) {
try { console.log(`Invalid windowId`);
// 3. Set the mouse pointer to the color picker style. return;
pointer.setPointerStyle(windowId, pointer.PointerStyle.COLOR_SUCKER).then(() => { }
console.log(`Successfully set mouse pointer style`); try {
}); // 3. Set the mouse pointer to the color picker style.
} catch (error) { pointer.setPointerStyle(windowId, pointer.PointerStyle.COLOR_SUCKER).then(() => {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(message)}`); console.log(`Successfully set mouse pointer style`);
} });
}); } catch (error) {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(`message`)}`);
}
}); });
// 4. End color pickup. // 4. End color pickup.
window.getTopWindow((error, windowClass) => { window.getLastWindow(this.context, (error, windowClass) => {
windowClass.getProperties((error, data) => { if (error.code) {
var windowId = data.id; console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
if (windowId < 0) { return;
console.log(`Invalid windowId`); }
return; var windowId = windowClass.getWindowProperties().id;
} if (windowId < 0) {
try { console.log(`Invalid windowId`);
// 5. Set the mouse pointer to the default style. return;
pointer.setPointerStyle(windowId, pointer.PointerStyle.DEFAULT).then(() => { }
console.log(`Successfully set mouse pointer style`); try {
}); // 5. Set the mouse pointer to the default style.
} catch (error) { pointer.setPointerStyle(windowId, pointer.PointerStyle.DEFAULT).then(() => {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(message)}`); console.log(`Successfully set mouse pointer style`);
} });
}); } catch (error) {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(`message`)}`);
}
}); });
``` ```
...@@ -12,11 +12,11 @@ Application error management APIs are provided by the **errorManager** module. F ...@@ -12,11 +12,11 @@ Application error management APIs are provided by the **errorManager** module. F
| API | Description | | API | Description |
| ------------------------------------------------------------ | ---------------------------------------------------- | | ------------------------------------------------------------ | ---------------------------------------------------- |
| registerErrorObserver(observer: ErrorObserver): number | Registers an observer for application errors. A callback will be invoked when an application error is detected. This API works in a synchronous manner. The return value is the SN of the registered observer.| | on(type: "error", observer: ErrorObserver): number | Registers an observer for application errors. A callback will be invoked when an application error is detected. This API works in a synchronous manner. The return value is the SN of the registered observer.|
| unregisterErrorObserver(observerId: number, callback: AsyncCallback\<void\>): void | Unregisters an observer in callback mode. The number passed to this API is the SN of the registered observer. | | off(type: "error", observerId: number, callback: AsyncCallback\<void\>): void | Unregisters an observer in callback mode. The number passed to this API is the SN of the registered observer. |
| unregisterErrorObserver(observerId: number): Promise\<void\> | Unregisters an observer in promise mode. The number passed to this API is the SN of the registered observer. | | off(type: "error", observerId: number): Promise\<void\> | Unregisters an observer in promise mode. The number passed to this API is the SN of the registered observer. |
When an asynchronous callback is used, the return value can be processed directly in the callback. If a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Result Codes for Unregistering an Observer](#result-codes-for-unregistering-an-observer). When an asynchronous callback is used, the return value can be processed directly in the callback. If a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Result Codes for Unregistering an Observer](#result codes-for-unregistering-an-observer).
**Table 2** Description of the ErrorObserver API **Table 2** Description of the ErrorObserver API
...@@ -36,7 +36,7 @@ When an asynchronous callback is used, the return value can be processed directl ...@@ -36,7 +36,7 @@ When an asynchronous callback is used, the return value can be processed directl
## Development Example ## Development Example
```ts ```ts
import Ability from '@ohos.application.Ability' import UIAbility from '@ohos.app.ability.UIAbility';
import errorManager from '@ohos.app.ability.errorManager'; import errorManager from '@ohos.app.ability.errorManager';
let registerId = -1; let registerId = -1;
...@@ -45,15 +45,16 @@ let callback = { ...@@ -45,15 +45,16 @@ let callback = {
console.log(errMsg); console.log(errMsg);
} }
} }
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate") console.log("[Demo] EntryAbility onCreate")
registerId = errorManager.on("error", callback); registerId = errorManager.on("error", callback);
globalThis.abilityWant = want; globalThis.abilityWant = want;
} }
onDestroy() { onDestroy() {
console.log("[Demo] MainAbility onDestroy") console.log("[Demo] EntryAbility onDestroy")
errorManager.off("error", registerId, (result) => { errorManager.off("error", registerId, (result) => {
console.log("[Demo] result " + result.code + ";" + result.message) console.log("[Demo] result " + result.code + ";" + result.message)
}); });
...@@ -61,7 +62,7 @@ export default class MainAbility extends Ability { ...@@ -61,7 +62,7 @@ export default class MainAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
// Main window is created for this ability. // Main window is created for this ability.
console.log("[Demo] MainAbility onWindowStageCreate") console.log("[Demo] EntryAbility onWindowStageCreate")
windowStage.loadContent("pages/index", (err, data) => { windowStage.loadContent("pages/index", (err, data) => {
if (err.code) { if (err.code) {
...@@ -74,17 +75,17 @@ export default class MainAbility extends Ability { ...@@ -74,17 +75,17 @@ export default class MainAbility extends Ability {
onWindowStageDestroy() { onWindowStageDestroy() {
// Main window is destroyed to release UI resources. // Main window is destroyed to release UI resources.
console.log("[Demo] MainAbility onWindowStageDestroy") console.log("[Demo] EntryAbility onWindowStageDestroy")
} }
onForeground() { onForeground() {
// Ability is brought to the foreground. // Ability is brought to the foreground.
console.log("[Demo] MainAbility onForeground") console.log("[Demo] EntryAbility onForeground")
} }
onBackground() { onBackground() {
// Ability is brought back to the background. // Ability is brought back to the background.
console.log("[Demo] MainAbility onBackground") console.log("[Demo] EntryAbility onBackground")
} }
}; };
``` ```
# @ohos.i18n (Internationalization) # @ohos.i18n (Internationalization)
The **i18n** module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402. This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402.
The [intl](js-apis-intl.md) module provides basic i18n capabilities through the standard i18n APIs defined in ECMA 402. It works with the i18n module to provide a complete suite of i18n capabilities. The [Intl](js-apis-intl.md) module provides basic I18N capabilities through the standard I18N APIs defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities.
> **NOTE** > **NOTE**
> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> >
> - This module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402. For details about the basic i18n capabilities, see [intl](js-apis-intl.md). > - This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. For details about the basic I18N capabilities, see [Intl](js-apis-intl.md).
## Modules to Import ## Modules to Import
...@@ -42,7 +42,7 @@ Obtains the localized script for the specified country. ...@@ -42,7 +42,7 @@ Obtains the localized script for the specified country.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -81,7 +81,7 @@ Obtains the localized script for the specified language. ...@@ -81,7 +81,7 @@ Obtains the localized script for the specified language.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -112,7 +112,7 @@ Obtains the list of system languages. For details about languages, see [Instanti ...@@ -112,7 +112,7 @@ Obtains the list of system languages. For details about languages, see [Instanti
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -149,7 +149,7 @@ Obtains the list of countries and regions supported for the specified language. ...@@ -149,7 +149,7 @@ Obtains the list of countries and regions supported for the specified language.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -187,7 +187,7 @@ Checks whether the system language matches the specified region. ...@@ -187,7 +187,7 @@ Checks whether the system language matches the specified region.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -218,7 +218,7 @@ Obtains the system language. For details about languages, see [Instantiating the ...@@ -218,7 +218,7 @@ Obtains the system language. For details about languages, see [Instantiating the
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -239,7 +239,7 @@ static setSystemLanguage(language: string): void ...@@ -239,7 +239,7 @@ static setSystemLanguage(language: string): void
Sets the system language. Currently, this API does not support real-time updating of the system language. Sets the system language. Currently, this API does not support real-time updating of the system language.
**System API**: This is a system API. This is a system API.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION **Permission required**: ohos.permission.UPDATE_CONFIGURATION
...@@ -253,7 +253,7 @@ Sets the system language. Currently, this API does not support real-time updatin ...@@ -253,7 +253,7 @@ Sets the system language. Currently, this API does not support real-time updatin
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -284,7 +284,7 @@ Obtains the system region. For details about system regions, see [Instantiating ...@@ -284,7 +284,7 @@ Obtains the system region. For details about system regions, see [Instantiating
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -305,7 +305,7 @@ static setSystemRegion(region: string): void ...@@ -305,7 +305,7 @@ static setSystemRegion(region: string): void
Sets the system region. Sets the system region.
**System API**: This is a system API. This is a system API.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION **Permission required**: ohos.permission.UPDATE_CONFIGURATION
...@@ -319,7 +319,7 @@ Sets the system region. ...@@ -319,7 +319,7 @@ Sets the system region.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -350,7 +350,7 @@ Obtains the system locale. For details about system locales, see [Instantiating ...@@ -350,7 +350,7 @@ Obtains the system locale. For details about system locales, see [Instantiating
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -371,7 +371,7 @@ static setSystemLocale(locale: string): void ...@@ -371,7 +371,7 @@ static setSystemLocale(locale: string): void
Sets the system locale. Sets the system locale.
**System API**: This is a system API. This is a system API.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION **Permission required**: ohos.permission.UPDATE_CONFIGURATION
...@@ -385,7 +385,7 @@ Sets the system locale. ...@@ -385,7 +385,7 @@ Sets the system locale.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -416,7 +416,7 @@ Checks whether the 24-hour clock is used. ...@@ -416,7 +416,7 @@ Checks whether the 24-hour clock is used.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -437,7 +437,7 @@ static set24HourClock(option: boolean): void ...@@ -437,7 +437,7 @@ static set24HourClock(option: boolean): void
Sets the 24-hour clock. Sets the 24-hour clock.
**System API**: This is a system API. This is a system API.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION **Permission required**: ohos.permission.UPDATE_CONFIGURATION
...@@ -451,7 +451,7 @@ Sets the 24-hour clock. ...@@ -451,7 +451,7 @@ Sets the 24-hour clock.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -473,7 +473,7 @@ static addPreferredLanguage(language: string, index?: number): void ...@@ -473,7 +473,7 @@ static addPreferredLanguage(language: string, index?: number): void
Adds a preferred language to the specified position on the preferred language list. Adds a preferred language to the specified position on the preferred language list.
**System API**: This is a system API. This is a system API.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION **Permission required**: ohos.permission.UPDATE_CONFIGURATION
...@@ -488,7 +488,7 @@ Adds a preferred language to the specified position on the preferred language li ...@@ -488,7 +488,7 @@ Adds a preferred language to the specified position on the preferred language li
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -512,7 +512,7 @@ static removePreferredLanguage(index: number): void ...@@ -512,7 +512,7 @@ static removePreferredLanguage(index: number): void
Deletes a preferred language from the specified position on the preferred language list. Deletes a preferred language from the specified position on the preferred language list.
**System API**: This is a system API. This is a system API.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION **Permission required**: ohos.permission.UPDATE_CONFIGURATION
...@@ -526,7 +526,7 @@ Deletes a preferred language from the specified position on the preferred langua ...@@ -526,7 +526,7 @@ Deletes a preferred language from the specified position on the preferred langua
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -547,7 +547,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -547,7 +547,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getPreferredLanguageList(): Array&lt;string&gt; static getPreferredLanguageList(): Array&lt;string&gt;
Obtains the preferred language list. Obtains the list of preferred languages.
**System capability**: SystemCapability.Global.I18n **System capability**: SystemCapability.Global.I18n
...@@ -555,11 +555,11 @@ Obtains the preferred language list. ...@@ -555,11 +555,11 @@ Obtains the preferred language list.
| Type | Description | | Type | Description |
| ------------------- | --------- | | ------------------- | --------- |
| Array&lt;string&gt; | Preferred language list.| | Array&lt;string&gt; | List of preferred languages.|
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -590,7 +590,7 @@ Obtains the first language in the preferred language list. ...@@ -590,7 +590,7 @@ Obtains the first language in the preferred language list.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -621,7 +621,7 @@ Obtains the preferred language of an application. ...@@ -621,7 +621,7 @@ Obtains the preferred language of an application.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -642,7 +642,7 @@ static setUsingLocalDigit(flag: boolean): void ...@@ -642,7 +642,7 @@ static setUsingLocalDigit(flag: boolean): void
Specifies whether to enable use of local digits. Specifies whether to enable use of local digits.
**System API**: This is a system API. This is a system API.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION **Permission required**: ohos.permission.UPDATE_CONFIGURATION
...@@ -652,11 +652,11 @@ Specifies whether to enable use of local digits. ...@@ -652,11 +652,11 @@ Specifies whether to enable use of local digits.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------- | ---- | ------------------------------- | | ---- | ------- | ---- | ------------------------------- |
| flag | boolean | Yes | Whether to enable the local digit switch. The value **true** means to enable the local digit switch, and the value **false** indicates the opposite.| | flag | boolean | Yes | Whether to turn on the local digit switch. The value **true** means to turn on the local digit switch, and the value **false** indicates the opposite.|
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -687,7 +687,7 @@ Checks whether use of local digits is enabled. ...@@ -687,7 +687,7 @@ Checks whether use of local digits is enabled.
**Error codes** **Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
...@@ -1059,7 +1059,7 @@ Creates a **PhoneNumberFormat** object. ...@@ -1059,7 +1059,7 @@ Creates a **PhoneNumberFormat** object.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------- | | ------- | ---------------------------------------- | ---- | ---------------- |
| country | string | Yes | Country or region to which the phone number to be formatted belongs.| | country | string | Yes | Country or region to which the phone number to be formatted belongs.|
| options | [PhoneNumberFormatOptions](#phonenumberformatoptions8) | No | Options of the **PhoneNumberFormat** object. | | options | [PhoneNumberFormatOptions](#phonenumberformatoptions9) | No | Options of the **PhoneNumberFormat** object. |
**Example** **Example**
```js ```js
...@@ -1149,7 +1149,7 @@ Obtains the home location of a phone number. ...@@ -1149,7 +1149,7 @@ Obtains the home location of a phone number.
``` ```
## PhoneNumberFormatOptions<sup>8+</sup> ## PhoneNumberFormatOptions<sup>9+</sup>
Defines the options for this PhoneNumberFormat object. Defines the options for this PhoneNumberFormat object.
...@@ -1194,7 +1194,7 @@ Creates an **IndexUtil** object. ...@@ -1194,7 +1194,7 @@ Creates an **IndexUtil** object.
**Example** **Example**
```js ```js
let indexUtil= I18n.getInstance("zh-CN"); let indexUtil = I18n.getInstance("zh-CN");
``` ```
...@@ -1267,7 +1267,7 @@ Obtains the index of a text object. ...@@ -1267,7 +1267,7 @@ Obtains the index of a text object.
**Example** **Example**
```js ```js
let indexUtil= I18n.getInstance("zh-CN"); let indexUtil = I18n.getInstance("zh-CN");
let index = indexUtil.getIndex("hi"); // index = "H" let index = indexUtil.getIndex("hi"); // index = "H"
``` ```
...@@ -1382,7 +1382,7 @@ Puts the [BreakIterator](#breakiterator8) object to the first text boundary, whi ...@@ -1382,7 +1382,7 @@ Puts the [BreakIterator](#breakiterator8) object to the first text boundary, whi
**Example** **Example**
```js ```js
let iterator = i18n.getLineInstance("en"); let iterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit."); iterator.setLineBreakText("Apple is my favorite fruit.");
let firstPos = iterator.first(); // firstPos = 0 let firstPos = iterator.first(); // firstPos = 0
``` ```
...@@ -1689,7 +1689,7 @@ Obtains the list of time zone city IDs supported by the system. ...@@ -1689,7 +1689,7 @@ Obtains the list of time zone city IDs supported by the system.
static getCityDisplayName(cityID: string, locale: string): string static getCityDisplayName(cityID: string, locale: string): string
Obtains the localized representation of a time zone city in the specified locale. Obtains the localized display of a time zone city in the specified locale.
**System capability**: SystemCapability.Global.I18n **System capability**: SystemCapability.Global.I18n
...@@ -2363,7 +2363,7 @@ This API is supported since API version 8 and is deprecated since API version 9. ...@@ -2363,7 +2363,7 @@ This API is supported since API version 8 and is deprecated since API version 9.
getPreferredLanguageList(): Array&lt;string&gt; getPreferredLanguageList(): Array&lt;string&gt;
Obtains the preferred language list. Obtains the list of preferred languages.
This API is supported since API version 8 and is deprecated since API version 9. You are advised to use [System.getPreferredLanguageList](#getpreferredlanguagelist9) instead. This API is supported since API version 8 and is deprecated since API version 9. You are advised to use [System.getPreferredLanguageList](#getpreferredlanguagelist9) instead.
...@@ -2373,7 +2373,7 @@ This API is supported since API version 8 and is deprecated since API version 9. ...@@ -2373,7 +2373,7 @@ This API is supported since API version 8 and is deprecated since API version 9.
| Type | Description | | Type | Description |
| ------------------- | --------- | | ------------------- | --------- |
| Array&lt;string&gt; | Preferred language list.| | Array&lt;string&gt; | List of preferred languages.|
**Example** **Example**
```js ```js
......
...@@ -67,7 +67,7 @@ Creates a **Locale** object. ...@@ -67,7 +67,7 @@ Creates a **Locale** object.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | -------------------------------- | ---- | ---------------------------- | | -------------------- | -------------------------------- | ---- | ---------------------------- |
| locale | string | Yes | A string containing locale information, including the language, optional script, and region. For details about the international standards and combination modes for the language, script, and country or region, see [intl Development](../../internationalization/intl-guidelines.md#setting-locale-information).| | locale | string | Yes | A string containing locale information, including the language, optional script, and region. For details about the international standards and combination modes for the language, script, and country or region, see [intl Development](../../internationalization/intl-guidelines.md#setting-locale-information).|
| options<sup>9+</sup> | [LocaleOptions](#localeoptions6) | No | Options for creating the **Locale** object. | | options<sup>9+</sup> | [LocaleOptions](#localeoptions9) | No | Options for creating the **Locale** object. |
**Example** **Example**
```js ```js
...@@ -159,7 +159,7 @@ Minimizes information of the **Locale** object. If the script and locale informa ...@@ -159,7 +159,7 @@ Minimizes information of the **Locale** object. If the script and locale informa
``` ```
## LocaleOptions<sup>6+</sup> ## LocaleOptions<sup>9+</sup>
Represents the locale options. Represents the locale options.
...@@ -206,7 +206,7 @@ Creates a **DateTimeOptions** object for the specified locale. ...@@ -206,7 +206,7 @@ Creates a **DateTimeOptions** object for the specified locale.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | ------------------------------------ | ---- | ---------------------------- | | -------------------- | ------------------------------------ | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options<sup>9+</sup> | [DateTimeOptions](#datetimeoptions6) | No | Options for creating a **DateTimeFormat** object. | | options<sup>9+</sup> | [DateTimeOptions](#datetimeoptions9) | No | Options for creating a **DateTimeFormat** object. |
**Example** **Example**
```js ```js
...@@ -298,7 +298,7 @@ Obtains the formatting options for **DateTimeFormat** object. ...@@ -298,7 +298,7 @@ Obtains the formatting options for **DateTimeFormat** object.
| Type | Description | | Type | Description |
| ------------------------------------ | ----------------------------- | | ------------------------------------ | ----------------------------- |
| [DateTimeOptions](#datetimeoptions6) | Formatting options for **DateTimeFormat** objects.| | [DateTimeOptions](#datetimeoptions9) | Formatting options for **DateTimeFormat** objects.|
**Example** **Example**
```js ```js
...@@ -310,7 +310,7 @@ Obtains the formatting options for **DateTimeFormat** object. ...@@ -310,7 +310,7 @@ Obtains the formatting options for **DateTimeFormat** object.
``` ```
## DateTimeOptions<sup>6+</sup> ## DateTimeOptions<sup>9+</sup>
Provides the options for the **DateTimeFormat** object. Provides the options for the **DateTimeFormat** object.
...@@ -370,7 +370,7 @@ Creates a **NumberFormat** object for the specified locale. ...@@ -370,7 +370,7 @@ Creates a **NumberFormat** object for the specified locale.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | -------------------------------- | ---- | ---------------------------- | | -------------------- | -------------------------------- | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options<sup>9+</sup> | [NumberOptions](#numberoptions6) | No | Options for creating a **NumberFormat** object. | | options<sup>9+</sup> | [NumberOptions](#numberoptions9) | No | Options for creating a **NumberFormat** object. |
**Example** **Example**
```js ```js
...@@ -420,7 +420,7 @@ Obtains the options of the **NumberFormat** object. ...@@ -420,7 +420,7 @@ Obtains the options of the **NumberFormat** object.
| Type | Description | | Type | Description |
| -------------------------------- | --------------------------- | | -------------------------------- | --------------------------- |
| [NumberOptions](#numberoptions6) | Formatting options for **NumberFormat** objects.| | [NumberOptions](#numberoptions9) | Formatting options for **NumberFormat** objects.|
**Example** **Example**
...@@ -433,7 +433,7 @@ Obtains the options of the **NumberFormat** object. ...@@ -433,7 +433,7 @@ Obtains the options of the **NumberFormat** object.
``` ```
## NumberOptions<sup>6+</sup> ## NumberOptions<sup>9+</sup>
Defines the device capability. Defines the device capability.
...@@ -493,7 +493,7 @@ Creates a **Collator** object. ...@@ -493,7 +493,7 @@ Creates a **Collator** object.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | ------------------------------------ | ---- | ---------------------------- | | -------------------- | ------------------------------------ | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options<sup>9+</sup> | [CollatorOptions](#collatoroptions8) | No | Options for creating a **Collator** object. | | options<sup>9+</sup> | [CollatorOptions](#collatoroptions9) | No | Options for creating a **Collator** object. |
**Example** **Example**
```js ```js
...@@ -544,7 +544,7 @@ Returns properties reflecting the locale and collation options of a **Collator** ...@@ -544,7 +544,7 @@ Returns properties reflecting the locale and collation options of a **Collator**
| Type | Description | | Type | Description |
| ------------------------------------ | ----------------- | | ------------------------------------ | ----------------- |
| [CollatorOptions](#collatoroptions8) | Properties of the **Collator** object.| | [CollatorOptions](#collatoroptions9) | Properties of the **Collator** object.|
**Example** **Example**
```js ```js
...@@ -556,7 +556,7 @@ Returns properties reflecting the locale and collation options of a **Collator** ...@@ -556,7 +556,7 @@ Returns properties reflecting the locale and collation options of a **Collator**
``` ```
## CollatorOptions<sup>8+</sup> ## CollatorOptions<sup>9+</sup>
Represents the properties of a **Collator** object. Represents the properties of a **Collator** object.
...@@ -604,7 +604,7 @@ Creates a **PluralRules** object to obtain the singular-plural type of numbers. ...@@ -604,7 +604,7 @@ Creates a **PluralRules** object to obtain the singular-plural type of numbers.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | ---------------------------------------- | ---- | ---------------------------- | | -------------------- | ---------------------------------------- | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options<sup>9+</sup> | [PluralRulesOptions](#pluralrulesoptions8) | No | Options for creating a **PluralRules** object. | | options<sup>9+</sup> | [PluralRulesOptions](#pluralrulesoptions9) | No | Options for creating a **PluralRules** object. |
**Example** **Example**
```js ```js
...@@ -647,7 +647,7 @@ Obtains a string that represents the singular-plural type of the specified numbe ...@@ -647,7 +647,7 @@ Obtains a string that represents the singular-plural type of the specified numbe
``` ```
## PluralRulesOptions<sup>8+</sup> ## PluralRulesOptions<sup>9+</sup>
Represents the properties of a **PluralRules** object. Represents the properties of a **PluralRules** object.
...@@ -695,7 +695,7 @@ Creates a **RelativeTimeFormat** object. ...@@ -695,7 +695,7 @@ Creates a **RelativeTimeFormat** object.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | ---------------------------------------- | ---- | ---------------------------- | | -------------------- | ---------------------------------------- | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options<sup>9+</sup> | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions8) | No | Options for creating a **RelativeTimeFormat** object. | | options<sup>9+</sup> | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions9) | No | Options for creating a **RelativeTimeFormat** object. |
**Example** **Example**
```js ```js
...@@ -787,7 +787,7 @@ Obtains the formatting options for **RelativeTimeFormat** objects. ...@@ -787,7 +787,7 @@ Obtains the formatting options for **RelativeTimeFormat** objects.
``` ```
## RelativeTimeFormatInputOptions<sup>8+</sup> ## RelativeTimeFormatInputOptions<sup>9+</sup>
Represents the properties of a **RelativeTimeFormat** object. Represents the properties of a **RelativeTimeFormat** object.
......
此差异已折叠。
...@@ -2,7 +2,8 @@ ...@@ -2,7 +2,8 @@
The **pointer** module provides APIs related to pointer attribute management. The **pointer** module provides APIs related to pointer attribute management.
> **NOTE**<br> > **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
...@@ -237,6 +238,8 @@ Obtains the mouse movement speed. This API uses a promise to return the result. ...@@ -237,6 +238,8 @@ Obtains the mouse movement speed. This API uses a promise to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.Pointer **System capability**: SystemCapability.MultimodalInput.Input.Pointer
**System API**: This is a system API.
**Return value** **Return value**
| Name | Description | | Name | Description |
...@@ -263,8 +266,6 @@ Obtains the mouse pointer style. This API uses an asynchronous callback to retur ...@@ -263,8 +266,6 @@ Obtains the mouse pointer style. This API uses an asynchronous callback to retur
**System capability**: SystemCapability.MultimodalInput.Input.Pointer **System capability**: SystemCapability.MultimodalInput.Input.Pointer
**System API**: This is a system API.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
...@@ -277,21 +278,23 @@ Obtains the mouse pointer style. This API uses an asynchronous callback to retur ...@@ -277,21 +278,23 @@ Obtains the mouse pointer style. This API uses an asynchronous callback to retur
```js ```js
import window from '@ohos.window'; import window from '@ohos.window';
window.getTopWindow((error, win) => { window.getLastWindow(this.context, (error, win) => {
win.getProperties((error, properties) => { if (error.code) {
let windowId = properties.id; console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
if (windowId < 0) { return;
console.log(`Invalid windowId`); }
return; let windowId = win.getWindowProperties().id;
} if (windowId < 0) {
try { console.log(`Invalid windowId`);
pointer.getPointerStyle(windowId, (error, style) => { return;
console.log(`Get pointer style success, style: ${JSON.stringify(style)}`); }
}); try {
} catch (error) { pointer.getPointerStyle(windowId, (error, style) => {
console.log(`Get pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); console.log(`Get pointer style success, style: ${JSON.stringify(style)}`);
} });
}); } catch (error) {
console.log(`Get pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
}); });
``` ```
...@@ -320,21 +323,23 @@ Obtains the mouse pointer style. This API uses a promise to return the result. ...@@ -320,21 +323,23 @@ Obtains the mouse pointer style. This API uses a promise to return the result.
```js ```js
import window from '@ohos.window'; import window from '@ohos.window';
window.getTopWindow((error, win) => { window.getLastWindow(this.context, (error, win) => {
win.getProperties((error, properties) => { if (error.code) {
let windowId = properties.id; console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
if (windowId < 0) { return;
console.log(`Invalid windowId`); }
return; let windowId = win.getWindowProperties().id;
} if (windowId < 0) {
try { console.log(`Invalid windowId`);
pointer.getPointerStyle(windowId).then((style) => { return;
console.log(`Get pointer style success, style: ${JSON.stringify(style)}`); }
}); try {
} catch (error) { pointer.getPointerStyle(windowId).then((style) => {
console.log(`Get pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); console.log(`Get pointer style success, style: ${JSON.stringify(style)}`);
} });
}); } catch (error) {
console.log(`Get pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
}); });
``` ```
...@@ -359,21 +364,23 @@ Sets the mouse pointer style. This API uses an asynchronous callback to return t ...@@ -359,21 +364,23 @@ Sets the mouse pointer style. This API uses an asynchronous callback to return t
```js ```js
import window from '@ohos.window'; import window from '@ohos.window';
window.getTopWindow((error, win) => { window.getLastWindow(this.context, (error, win) => {
win.getProperties((error, properties) => { if (error.code) {
let windowId = properties.id; console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
if (windowId < 0) { return;
console.log(`Invalid windowId`); }
return; let windowId = win.getWindowProperties().id;
} if (windowId < 0) {
try { console.log(`Invalid windowId`);
pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS, error => { return;
console.log(`Set pointer style success`); }
}); try {
} catch (error) { pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS, error => {
console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); console.log(`Set pointer style success`);
} });
}); } catch (error) {
console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
}); });
``` ```
## pointer.setPointerStyle<sup>9+</sup> ## pointer.setPointerStyle<sup>9+</sup>
...@@ -397,21 +404,23 @@ Sets the mouse pointer style. This API uses a promise to return the result. ...@@ -397,21 +404,23 @@ Sets the mouse pointer style. This API uses a promise to return the result.
```js ```js
import window from '@ohos.window'; import window from '@ohos.window';
window.getTopWindow((error, win) => { window.getLastWindow(this.context, (error, win) => {
win.getProperties((error, properties) => { if (error.code) {
let windowId = properties.id; console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
if (windowId < 0) { return;
console.log(`Invalid windowId`); }
return; let windowId = win.getWindowProperties().id;
} if (windowId < 0) {
try { console.log(`Invalid windowId`);
pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS).then(() => { return;
console.log(`Set pointer style success`); }
}); try {
} catch (error) { pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS).then(() => {
console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); console.log(`Set pointer style success`);
} });
}); } catch (error) {
console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
}); });
``` ```
## PointerStyle<sup>9+</sup> ## PointerStyle<sup>9+</sup>
...@@ -444,8 +453,8 @@ Enumerates mouse pointer styles. ...@@ -444,8 +453,8 @@ Enumerates mouse pointer styles.
| HAND_POINTING | 19 | Hand-shaped pointer |![Hand_Poniting.png](./figures/Hand_Pointing.png)| | HAND_POINTING | 19 | Hand-shaped pointer |![Hand_Poniting.png](./figures/Hand_Pointing.png)|
| HELP | 20 | Help |![Help.png](./figures/Help.png)| | HELP | 20 | Help |![Help.png](./figures/Help.png)|
| MOVE | 21 | Move |![Move.png](./figures/Move.png)| | MOVE | 21 | Move |![Move.png](./figures/Move.png)|
| RESIZE_LEFT_RIGHT | 22 | Left-and-right resizing|![Resize_Left_Right.png](./figures/Resize_Left_Right.png)| | RESIZE_LEFT_RIGHT | 22 | Left and right resizing|![Resize_Left_Right.png](./figures/Resize_Left_Right.png)|
| RESIZE_UP_DOWN | 23 | Up-and-down resizing|![Resize_Up_Down.png](./figures/Resize_Up_Down.png)| | RESIZE_UP_DOWN | 23 | Up and down resizing|![Resize_Up_Down.png](./figures/Resize_Up_Down.png)|
| SCREENSHOT_CHOOSE | 24 | Screenshot crosshair|![Screenshot_Cross.png](./figures/Screenshot_Cross.png)| | SCREENSHOT_CHOOSE | 24 | Screenshot crosshair|![Screenshot_Cross.png](./figures/Screenshot_Cross.png)|
| SCREENSHOT_CURSOR | 25 | Screenshot cursor |![Screenshot_Cursor.png](./figures/Screenshot_Cursor.png)| | SCREENSHOT_CURSOR | 25 | Screenshot cursor |![Screenshot_Cursor.png](./figures/Screenshot_Cursor.png)|
| TEXT_CURSOR | 26 | Text cursor |![Text_Cursor.png](./figures/Text_Cursor.png)| | TEXT_CURSOR | 26 | Text cursor |![Text_Cursor.png](./figures/Text_Cursor.png)|
......
...@@ -19,8 +19,9 @@ Since API version 9, the stage model allows an application to obtain a **Resourc ...@@ -19,8 +19,9 @@ Since API version 9, the stage model allows an application to obtain a **Resourc
For details about how to reference context in the stage model, see [Context in the Stage Model](../..//application-models/application-context-stage.md). For details about how to reference context in the stage model, see [Context in the Stage Model](../..//application-models/application-context-stage.md).
```ts ```ts
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
let context = this.context; let context = this.context;
let resourceManager = context.resourceManager; let resourceManager = context.resourceManager;
......
# @system.fetch (Data Request) # @system.fetch (Data Request)
> **NOTE** > **NOTE**
>
> - The APIs of this module are no longer maintained since API version 6. You are advised to use [`@ohos.net.http`](js-apis-http.md) instead. > - The APIs of this module are no longer maintained since API version 6. You are advised to use [`@ohos.net.http`](js-apis-http.md) instead.
> >
> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -15,7 +14,7 @@ import fetch from '@system.fetch'; ...@@ -15,7 +14,7 @@ import fetch from '@system.fetch';
``` ```
## fetch.fetch ## fetch.fetch<sup>3+</sup>
fetch(Object): void fetch(Object): void
...@@ -31,9 +30,9 @@ Obtains data through a network. ...@@ -31,9 +30,9 @@ Obtains data through a network.
| header | Object | No| Request header.| | header | Object | No| Request header.|
| method | string | No| Request method. The default value is **GET**. The value can be **OPTIONS**, **GET**, **HEAD**, **POST**, **PUT**, **DELETE **or **TRACE**.| | method | string | No| Request method. The default value is **GET**. The value can be **OPTIONS**, **GET**, **HEAD**, **POST**, **PUT**, **DELETE **or **TRACE**.|
| responseType | string | No| Response type. The return type can be text or JSON. By default, the return type is determined based on **Content-Type** in the header returned by the server. For details, see return values in the **success** callback.| | responseType | string | No| Response type. The return type can be text or JSON. By default, the return type is determined based on **Content-Type** in the header returned by the server. For details, see return values in the **success** callback.|
| success | Function | No| Called when the data is obtained successfully. The return value is [FetchResponse](#fetchresponse). | | success | Function | No| Called when the API call is successful. The return value is defined by [FetchResponse](#fetchresponse).|
| fail | Function | No| Called when the data failed to be obtained.| | fail | Function | No| Called when API call has failed.|
| complete | Function | No| Called when the execution is complete.| | complete | Function | No| Called when the API call is complete.|
**Table 1** Mapping between data and Content-Type **Table 1** Mapping between data and Content-Type
...@@ -46,11 +45,11 @@ Obtains data through a network. ...@@ -46,11 +45,11 @@ Obtains data through a network.
## FetchResponse ## FetchResponse
| Name| Type| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| code | number | Server status code.| | code | number | Yes| No| Server status code.|
| data | string \| Object | The data type is determined by **responseType**. For details, see the mapping between **responseType** and **data** in **success** callback.| | data | string \| Object | Yes| No| The type of the returned data is determined by **responseType**. For details, see the mapping between **responseType** and **data** in **success** callback.|
| headers | Object | All headers in the response from the server.| | headers | Object | Yes| No| All headers in the response from the server.|
**Table 2** Mapping between responseType and data in success callback **Table 2** Mapping between responseType and data in success callback
...@@ -85,8 +84,8 @@ export default { ...@@ -85,8 +84,8 @@ export default {
``` ```
> **NOTE**<br/> > **NOTE**
> HTTPS is supported by default. To support HTTP, you need to add **"network"** to the **config.json** file, and set the attribute **"cleartextTraffic"** to **true**. That is: > HTTPS is supported by default. To support HTTP, you need to add **"network"** to the **config.json** file, and set the attribute **"cleartextTraffic"** to **true**. That is:
> >
> ``` > ```
> { > {
......
# Network State # @system.network (Network State)
> **NOTE**<br> > **NOTE**
> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.telephony.observer`](js-apis-observer.md) instead. > - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.telephony.observer`](js-apis-observer.md).
> >
> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -31,17 +31,17 @@ Obtains the network type. ...@@ -31,17 +31,17 @@ Obtains the network type.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| success | Function | No | Called when the execution is successful. The return value is [FetchResponse](#fetchresponse). | | success | Function | No| Called when the API call is successful. The return value is defined by [NetworkResponse](#networkresponse).|
| fail | Function | No | Called when the operation fails. | | fail | Function | No| Called when API call has failed.|
| complete | Function | No | Called when the execution is complete. | | complete | Function | No| Called when the API call is complete.|
One of the following error codes will be returned if the operation fails. One of the following error codes will be returned if the API call has failed.
| Error Code | Description | | Error Code| Description|
| -------- | -------- | | -------- | -------- |
| 602 | The current permission is not declared. | | 602 | The current permission is not declared.|
**Example** **Example**
...@@ -71,17 +71,17 @@ Listens to the network connection state. If this method is called multiple times ...@@ -71,17 +71,17 @@ Listens to the network connection state. If this method is called multiple times
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| success | Function | No | Called when the network connection state changes. The return value is [FetchResponse](#fetchresponse). | | success | Function | No| Called when the network state changes. The return value is defined by [NetworkResponse](#networkresponse).|
| fail | Function | No | Called when the multimedia volume fails to be obtained. | | fail | Function | No| Called when API call has failed.|
One of the following error codes will be returned if the listening fails. One of the following error codes will be returned if the API call has failed.
| Error Code | Description | | Error Code| Description|
| -------- | -------- | | -------- | -------- |
| 602 | The current permission is not declared. | | 602 | The current permission is not declared.|
| 200 | The subscription fails. | | 200 | Subscription failed.|
**Example** **Example**
...@@ -122,7 +122,9 @@ export default { ...@@ -122,7 +122,9 @@ export default {
## NetworkResponse ## NetworkResponse
| Name | Type | Description | **System capability**: SystemCapability.Communication.NetManager.Core
| -------- | -------- | -------- |
| metered | boolean | Whether the billing is based on the data volume. | | Name| Type| Mandatory| Description|
| type | string | Network type. The value can be **2G**, **3G**, **4G**, **5G**, **WiFi**, or **none**. | | -------- | -------- | -------- | -------- |
\ No newline at end of file | metered | boolean | No|Whether to charge by traffic.|
| type | string | Yes|Network type. The value can be **2G**, **3G**, **4G**, **5G**, **WiFi**, or **none**.|
...@@ -8,8 +8,10 @@ There are two types of updates: SD card update and over the air (OTA) update. ...@@ -8,8 +8,10 @@ There are two types of updates: SD card update and over the air (OTA) update.
- The OTA update depends on the server deployed by the device manufacturer for managing update packages. The OTA server IP address is passed by the caller. The request interface is fixed and developed by the device manufacturer. - The OTA update depends on the server deployed by the device manufacturer for managing update packages. The OTA server IP address is passed by the caller. The request interface is fixed and developed by the device manufacturer.
> **NOTE** > **NOTE**
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. >
> - The APIs provided by this module are system APIs. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The APIs provided by this module are system APIs.
## Modules to Import ## Modules to Import
...@@ -2034,7 +2036,7 @@ Enumerates update states. ...@@ -2034,7 +2036,7 @@ Enumerates update states.
| WAITING_INSTALL | 30 | Waiting for installation. | | WAITING_INSTALL | 30 | Waiting for installation. |
| UPDATING | 31 | Updating. | | UPDATING | 31 | Updating. |
| WAITING_APPLY | 40 | Waiting for applying the update. | | WAITING_APPLY | 40 | Waiting for applying the update. |
| APPLYING | 21 | Applying the update. | | APPLYING | 41 | Applying the update. |
| UPGRADE_SUCCESS | 50 | Update succeeded.| | UPGRADE_SUCCESS | 50 | Update succeeded.|
| UPGRADE_FAIL | 51 | Update failed.| | UPGRADE_FAIL | 51 | Update failed.|
...@@ -2056,7 +2058,7 @@ Enumerates event IDs. ...@@ -2056,7 +2058,7 @@ Enumerates event IDs.
| Name | Value | Description | | Name | Value | Description |
| ---------------------- | ---------- | ------ | | ---------------------- | ---------- | ------ |
| EVENT_TASK_BASE | 0x01000000 | Task event. | | EVENT_TASK_BASE | EventClassify.TASK | Task event. |
| EVENT_TASK_RECEIVE | 0x01000001 | Task received. | | EVENT_TASK_RECEIVE | 0x01000001 | Task received. |
| EVENT_TASK_CANCEL | 0x01000010 | Task cancelled. | | EVENT_TASK_CANCEL | 0x01000010 | Task cancelled. |
| EVENT_DOWNLOAD_WAIT | 0x01000011 | Waiting for download. | | EVENT_DOWNLOAD_WAIT | 0x01000011 | Waiting for download. |
......
# @ohos.usbV9 (USB Management) # @ohos.usbV9 (USB)
The **usb** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as port management, and function switch and query on the device side. The USB module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as port management, and function switch and query on the device side.
> **NOTE**<br> > **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs provided by this module are no longer maintained since API version 9. You are advised to use [`@ohos.usbManager`](js-apis-usbManager.md) instead. >
> The APIs provided by this module are no longer maintained since API version 9. You are advised to use [`@ohos.usbManager`](js-apis-usbManager.md).
## Modules to Import ## Modules to Import
...@@ -30,7 +32,7 @@ Obtains the list of USB devices connected to the host. If no device is connected ...@@ -30,7 +32,7 @@ Obtains the list of USB devices connected to the host. If no device is connected
```js ```js
let devicesList = usb.getDevices(); let devicesList = usb.getDevices();
console.log(`devicesList = ${JSON.stringify(devicesList)}`); console.log(`devicesList = ${devicesList}`);
// devicesList is a list of USB devices. // devicesList is a list of USB devices.
// A simple example of devicesList is provided as follows: // A simple example of devicesList is provided as follows:
[ [
...@@ -87,7 +89,7 @@ console.log(`devicesList = ${JSON.stringify(devicesList)}`); ...@@ -87,7 +89,7 @@ console.log(`devicesList = ${JSON.stringify(devicesList)}`);
connectDevice(device: USBDevice): Readonly&lt;USBDevicePipe&gt; connectDevice(device: USBDevice): Readonly&lt;USBDevicePipe&gt;
Connects to a USB device based on the device list obtained by using **getDevices()**. Connects to the USB device based on the device information returned by **getDevices()**.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and device information, and then call [usb.requestRight](#usbrequestright) to request the device access permission. Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and device information, and then call [usb.requestRight](#usbrequestright) to request the device access permission.
...@@ -119,13 +121,12 @@ For details about the error codes, see [USB Error Codes](../errorcodes/errorcode ...@@ -119,13 +121,12 @@ For details about the error codes, see [USB Error Codes](../errorcodes/errorcode
let devicesList = usb.getDevices(); let devicesList = usb.getDevices();
if (devicesList.length == 0) { if (devicesList.length == 0) {
console.log(`device list is empty`); console.log(`device list is empty`);
return;
} }
let device = devicesList[0]; let device = devicesList[0];
usb.requestRight(device.name); usb.requestRight(device.name);
let devicepipe = usb.connectDevice(device); let devicepipe = usb.connectDevice(device);
console.log(`devicepipe = ${JSON.stringify(devicepipe)}`); console.log(`devicepipe = ${devicepipe}`);
``` ```
## usb.hasRight ## usb.hasRight
...@@ -134,7 +135,7 @@ hasRight(deviceName: string): boolean ...@@ -134,7 +135,7 @@ hasRight(deviceName: string): boolean
Checks whether the application has the permission to access the device. Checks whether the application has the permission to access the device.
The value **true** is returned if the device access permission is available; the value **false** is returned otherwise. Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise.
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
...@@ -183,7 +184,7 @@ Requests the temporary permission for the application to access a USB device. Th ...@@ -183,7 +184,7 @@ Requests the temporary permission for the application to access a USB device. Th
```js ```js
let devicesName="1-1"; let devicesName="1-1";
usb.requestRight(devicesName).then((ret) => { usb.requestRight(devicesName).then((ret) => {
console.log(`requestRight = ${JSON.stringify(ret)}`); console.log(`requestRight = ${ret}`);
}); });
``` ```
...@@ -211,7 +212,7 @@ Removes the permission for the application to access a USB device. ...@@ -211,7 +212,7 @@ Removes the permission for the application to access a USB device.
```js ```js
let devicesName="1-1"; let devicesName="1-1";
if (usb.removeRight(devicesName) { if usb.removeRight(devicesName) {
console.log(`Succeed in removing right`); console.log(`Succeed in removing right`);
} }
``` ```
...@@ -246,7 +247,7 @@ Adds the permission for the application to access a USB device. ...@@ -246,7 +247,7 @@ Adds the permission for the application to access a USB device.
```js ```js
let devicesName = "1-1"; let devicesName = "1-1";
let bundleName = "com.example.hello"; let bundleName = "com.example.hello";
if (usb.addRight(bundleName, devicesName) { if usb.addRight(bundleName, devicesName) {
console.log(`Succeed in adding right`); console.log(`Succeed in adding right`);
} }
``` ```
...@@ -455,8 +456,9 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ...@@ -455,8 +456,9 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
**Example** **Example**
```js ```js
usb.controlTransfer(devicepipe, USBControlParams).then((ret) => { let param = new usb.USBControlParams();
console.log(`controlTransfer = ${JSON.stringify(ret)}`); usb.controlTransfer(devicepipe, param).then((ret) => {
console.log(`controlTransfer = ${ret}`);
}) })
``` ```
...@@ -492,7 +494,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ...@@ -492,7 +494,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
// Pass the obtained USB device as a parameter to usb.connectDevice. Then, call usb.connectDevice to connect the USB device. // Pass the obtained USB device as a parameter to usb.connectDevice. Then, call usb.connectDevice to connect the USB device.
// Call usb.claimInterface to claim the USB interface. After that, call usb.bulkTransfer to start bulk transfer. // Call usb.claimInterface to claim the USB interface. After that, call usb.bulkTransfer to start bulk transfer.
usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => { usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => {
console.log(`bulkTransfer = ${JSON.stringify(ret)}`); console.log(`bulkTransfer = ${ret}`);
}); });
``` ```
...@@ -579,7 +581,7 @@ Converts the USB function list in the numeric mask format to a string in Device ...@@ -579,7 +581,7 @@ Converts the USB function list in the numeric mask format to a string in Device
**Example** **Example**
```js ```js
let funcs = ACM | ECM; let funcs = usb.ACM | usb.ECM;
let ret = usb.usbFunctionsToString(funcs); let ret = usb.usbFunctionsToString(funcs);
``` ```
...@@ -608,7 +610,7 @@ Sets the current USB function list in Device mode. ...@@ -608,7 +610,7 @@ Sets the current USB function list in Device mode.
**Example** **Example**
```js ```js
let funcs = HDC; let funcs = usb.HDC;
let ret = usb.setCurrentFunctions(funcs); let ret = usb.setCurrentFunctions(funcs);
``` ```
...@@ -711,7 +713,12 @@ Sets the role types supported by a specified port, which can be **powerRole** (f ...@@ -711,7 +713,12 @@ Sets the role types supported by a specified port, which can be **powerRole** (f
**Example** **Example**
```js ```js
let ret = usb.getSupportedModes(0); let portId = 1;
usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => {
console.info('usb setPortRoles successfully.');
}).catch(err => {
console.error('usb setPortRoles failed: ' + err.code + ' message: ' + err.message);
});
``` ```
## USBEndpoint ## USBEndpoint
...@@ -722,14 +729,14 @@ Represents the USB endpoint from which data is sent or received. You can obtain ...@@ -722,14 +729,14 @@ Represents the USB endpoint from which data is sent or received. You can obtain
| Name | Type | Mandatory |Description | | Name | Type | Mandatory |Description |
| ------------- | ------------------------------------------- | ------------- |------------- | | ------------- | ------------------------------------------- | ------------- |------------- |
| address | number | Yes | Endpoint address. | | address | number | Yes|Endpoint address. |
| attributes | number | Yes | Endpoint attributes. | | attributes | number | Yes|Endpoint attributes. |
| interval | number | Yes | Endpoint interval. | | interval | number | Yes|Endpoint interval. |
| maxPacketSize | number | Yes | Maximum size of data packets on the endpoint. | | maxPacketSize | number | Yes|Maximum size of data packets on the endpoint. |
| direction | [USBRequestDirection](#usbrequestdirection) | Yes | Endpoint direction. | | direction | [USBRequestDirection](#usbrequestdirection) | Yes|Endpoint direction. |
| number | number | Yes | Endpoint number. | | number | number | Yes|Endpoint number. |
| type | number | Yes | Endpoint type. | | type | number | Yes|Endpoint type. |
| interfaceId | number | Yes | Unique ID of the interface to which the endpoint belongs.| | interfaceId | number | Yes|Unique ID of the interface to which the endpoint belongs.|
## USBInterface ## USBInterface
...@@ -739,13 +746,13 @@ Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **U ...@@ -739,13 +746,13 @@ Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **U
| Name | Type | Mandatory |Description | | Name | Type | Mandatory |Description |
| ---------------- | ---------------------------------------- | ------------- |--------------------- | | ---------------- | ---------------------------------------- | ------------- |--------------------- |
| id | number | Yes | Unique ID of the USB interface. | | id | number | Yes|Unique ID of the USB interface. |
| protocol | number | Yes | Interface protocol. | | protocol | number | Yes|Interface protocol. |
| clazz | number | Yes | Device type. | | clazz | number | Yes|Device type. |
| subClass | number | Yes | Device subclass. | | subClass | number | Yes|Device subclass. |
| alternateSetting | number | Yes | Settings for alternating between descriptors of the same USB interface.| | alternateSetting | number | Yes|Settings for alternating between descriptors of the same USB interface.|
| name | string | Yes | Interface name. | | name | string | Yes|Interface name. |
| endpoints | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Yes | Endpoints that belong to the USB interface. | | endpoints | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Yes|Endpoints that belong to the USB interface. |
## USBConfig ## USBConfig
...@@ -755,13 +762,13 @@ Represents the USB configuration. One [USBDevice](#usbdevice) can contain multip ...@@ -755,13 +762,13 @@ Represents the USB configuration. One [USBDevice](#usbdevice) can contain multip
| Name | Type | Mandatory |Description | | Name | Type | Mandatory |Description |
| -------------- | ------------------------------------------------ | --------------- |--------------- | | -------------- | ------------------------------------------------ | --------------- |--------------- |
| id | number | Yes | Unique ID of the USB configuration. | | id | number | Yes|Unique ID of the USB configuration. |
| attributes | number | Yes | Configuration attributes. | | attributes | number | Yes|Configuration attributes. |
| maxPower | number | Yes | Maximum power consumption, in mA. | | maxPower | number | Yes|Maximum power consumption, in mA. |
| name | string | Yes | Configuration name, which can be left empty. | | name | string | Yes|Configuration name, which can be left empty. |
| isRemoteWakeup | boolean | Yes | Support for remote wakeup.| | isRemoteWakeup | boolean | Yes|Support for remote wakeup.|
| isSelfPowered | boolean | Yes | Support for independent power supplies.| | isSelfPowered | boolean | Yes| Support for independent power supplies.|
| interfaces | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Yes | Supported interface attributes. | | interfaces | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Yes|Supported interface attributes. |
## USBDevice ## USBDevice
...@@ -771,19 +778,19 @@ Represents the USB device information. ...@@ -771,19 +778,19 @@ Represents the USB device information.
| Name | Type | Mandatory |Description | | Name | Type | Mandatory |Description |
| ---------------- | ------------------------------------ | ---------- |---------- | | ---------------- | ------------------------------------ | ---------- |---------- |
| busNum | number | Yes | Bus address. | | busNum | number | Yes|Bus address. |
| devAddress | number | Yes | Device address. | | devAddress | number | Yes|Device address. |
| serial | string | Yes | Sequence number. | | serial | string | Yes|Sequence number. |
| name | string | Yes | Device name. | | name | string | Yes|Device name. |
| manufacturerName | string | Yes | Device manufacturer. | | manufacturerName | string | Yes| Device manufacturer. |
| productName | string | Yes | Product name. | | productName | string | Yes|Product name. |
| version | string | Yes | Version number. | | version | string | Yes|Version number. |
| vendorId | number | Yes | Vendor ID. | | vendorId | number | Yes|Vendor ID. |
| productId | number | Yes | Product ID. | | productId | number | Yes|Product ID. |
| clazz | number | Yes | Device class. | | clazz | number | Yes|Device class. |
| subClass | number | Yes | Device subclass. | | subClass | number | Yes|Device subclass. |
| protocol | number | Yes | Device protocol code. | | protocol | number | Yes|Device protocol code. |
| configs | Array&lt;[USBConfig](#usbconfig)&gt; | Yes | Device configuration descriptor information.| | configs | Array&lt;[USBConfig](#usbconfig)&gt; | Yes|Device configuration descriptor information.|
## USBDevicePipe ## USBDevicePipe
...@@ -804,12 +811,12 @@ Represents control transfer parameters. ...@@ -804,12 +811,12 @@ Represents control transfer parameters.
| Name | Type | Mandatory |Description | | Name | Type | Mandatory |Description |
| ------- | ----------------------------------------------- | ---------------- |---------------- | | ------- | ----------------------------------------------- | ---------------- |---------------- |
| request | number | Yes | Request type. | | request | number | Yes |Request type. |
| target | [USBRequestTargetType](#usbrequesttargettype) | Yes | Request target type. | | target | [USBRequestTargetType](#usbrequesttargettype) | Yes |Request target type. |
| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes | Control request type. | | reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes |Control request type. |
| value | number | Yes | Request parameter value. | | value | number | Yes |Request parameter value. |
| index | number | Yes | Index of the request parameter value.| | index | number | Yes |Index of the request parameter value.|
| data | Uint8Array | Yes | Buffer for writing or reading data. | | data | Uint8Array | Yes |Buffer for writing or reading data. |
## USBPort ## USBPort
...@@ -821,9 +828,9 @@ Represents a USB port. ...@@ -821,9 +828,9 @@ Represents a USB port.
| Name | Type | Mandatory |Description | | Name | Type | Mandatory |Description |
| -------------- | ------------------------------- | ------------------- |------------------------ | | -------------- | ------------------------------- | ------------------- |------------------------ |
| id | number | Yes | Unique identifier of a USB port. | | id | number | Yes |Unique identifier of a USB port. |
| supportedModes | [PortModeType](#portmodetype) | Yes | Numeric mask combination for the supported mode list.| | supportedModes | [PortModeType](#portmodetype) | Yes |Numeric mask combination for the supported mode list.|
| status | [USBPortStatus](#usbportstatus) | Yes | USB port role. | | status | [USBPortStatus](#usbportstatus) | Yes |USB port role. |
## USBPortStatus ## USBPortStatus
...@@ -835,9 +842,9 @@ Enumerates USB port roles. ...@@ -835,9 +842,9 @@ Enumerates USB port roles.
| Name | Type| Mandatory |Description | | Name | Type| Mandatory |Description |
| ---------------- | -------- | ---------------- |---------------------- | | ---------------- | -------- | ---------------- |---------------------- |
| currentMode | number | Yes | Current USB mode. | | currentMode | number | Yes|Current USB mode. |
| currentPowerRole | number | Yes | Current power role. | | currentPowerRole | number | Yes |Current power role. |
| currentDataRole | number | Yes | Current data role.| | currentDataRole | number | Yes |Current data role.|
## USBRequestTargetType ## USBRequestTargetType
...@@ -845,12 +852,12 @@ Enumerates request target types. ...@@ -845,12 +852,12 @@ Enumerates request target types.
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Value | Description | | Name | Value | Description |
| ---------------------------- | ----- | ----------- | | ---------------------------- | ---- | ------ |
| USB_REQUEST_TARGET_DEVICE | 0 | Device | | USB_REQUEST_TARGET_DEVICE | 0 | Device|
| USB_REQUEST_TARGET_INTERFACE | 1 | Interface | | USB_REQUEST_TARGET_INTERFACE | 1 | Interface|
| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint | | USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint|
| USB_REQUEST_TARGET_OTHER | 3 | Other | | USB_REQUEST_TARGET_OTHER | 3 | Other|
## USBControlRequestType ## USBControlRequestType
......
...@@ -30,7 +30,7 @@ Obtains the list of USB devices connected to the host. If no device is connected ...@@ -30,7 +30,7 @@ Obtains the list of USB devices connected to the host. If no device is connected
```js ```js
let devicesList = usb.getDevices(); let devicesList = usb.getDevices();
console.log(`devicesList = ${JSON.stringify(devicesList)}`); cconsole.log(`devicesList = ${devicesList}`);
// devicesList is a list of USB devices. // devicesList is a list of USB devices.
// A simple example of devicesList is provided as follows: // A simple example of devicesList is provided as follows:
[ [
...@@ -119,13 +119,12 @@ For details about the error codes, see [USB Error Codes](../errorcodes/errorcode ...@@ -119,13 +119,12 @@ For details about the error codes, see [USB Error Codes](../errorcodes/errorcode
let devicesList = usb.getDevices(); let devicesList = usb.getDevices();
if (devicesList.length == 0) { if (devicesList.length == 0) {
console.log(`device list is empty`); console.log(`device list is empty`);
return;
} }
let device = devicesList[0]; let device = devicesList[0];
usb.requestRight(device.name); usb.requestRight(device.name);
let devicepipe = usb.connectDevice(device); let devicepipe = usb.connectDevice(device);
console.log(`devicepipe = ${JSON.stringify(devicepipe)}`); console.log(`devicepipe = ${devicepipe}`);
``` ```
## usb.hasRight ## usb.hasRight
...@@ -155,7 +154,7 @@ Checks whether the user, for example, the application or system, has the device ...@@ -155,7 +154,7 @@ Checks whether the user, for example, the application or system, has the device
```js ```js
let devicesName="1-1"; let devicesName="1-1";
let bool = usb.hasRight(devicesName); let bool = usb.hasRight(devicesName);
console.log(bool); console.log(`${bool}`);
``` ```
## usb.requestRight ## usb.requestRight
...@@ -183,7 +182,7 @@ Requests the temporary permission for the application to access a USB device. Th ...@@ -183,7 +182,7 @@ Requests the temporary permission for the application to access a USB device. Th
```js ```js
let devicesName="1-1"; let devicesName="1-1";
usb.requestRight(devicesName).then((ret) => { usb.requestRight(devicesName).then((ret) => {
console.log(`requestRight = ${JSON.stringify(ret)}`); console.log(`requestRight = ${ret}`);
}); });
``` ```
...@@ -211,7 +210,7 @@ Removes the permission for the application to access a USB device. ...@@ -211,7 +210,7 @@ Removes the permission for the application to access a USB device.
```js ```js
let devicesName="1-1"; let devicesName="1-1";
if (usb.removeRight(devicesName) { if usb.removeRight(devicesName) {
console.log(`Succeed in removing right`); console.log(`Succeed in removing right`);
} }
``` ```
...@@ -246,7 +245,7 @@ Adds the permission for the application to access a USB device. ...@@ -246,7 +245,7 @@ Adds the permission for the application to access a USB device.
```js ```js
let devicesName = "1-1"; let devicesName = "1-1";
let bundleName = "com.example.hello"; let bundleName = "com.example.hello";
if (usb.addRight(bundleName, devicesName) { if usb.addRight(bundleName, devicesName) {
console.log(`Succeed in adding right`); console.log(`Succeed in adding right`);
} }
``` ```
...@@ -455,8 +454,9 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ...@@ -455,8 +454,9 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
**Example** **Example**
```js ```js
usb.controlTransfer(devicepipe, USBControlParams).then((ret) => { let param = new usb.USBControlParams();
console.log(`controlTransfer = ${JSON.stringify(ret)}`); usb.controlTransfer(devicepipe, param).then((ret) => {
console.log(`controlTransfer = ${ret}`);
}) })
``` ```
...@@ -492,7 +492,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ...@@ -492,7 +492,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
// Pass the obtained USB device as a parameter to usb.connectDevice. Then, call usb.connectDevice to connect the USB device. // Pass the obtained USB device as a parameter to usb.connectDevice. Then, call usb.connectDevice to connect the USB device.
// Call usb.claimInterface to claim the USB interface. After that, call usb.bulkTransfer to start bulk transfer. // Call usb.claimInterface to claim the USB interface. After that, call usb.bulkTransfer to start bulk transfer.
usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => { usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => {
console.log(`bulkTransfer = ${JSON.stringify(ret)}`); console.log(`bulkTransfer = ${ret}`);
}); });
``` ```
...@@ -579,7 +579,7 @@ Converts the USB function list in the numeric mask format to a string in Device ...@@ -579,7 +579,7 @@ Converts the USB function list in the numeric mask format to a string in Device
**Example** **Example**
```js ```js
let funcs = ACM | ECM; let funcs = usb.ACM | usb.ECM;
let ret = usb.usbFunctionsToString(funcs); let ret = usb.usbFunctionsToString(funcs);
``` ```
...@@ -608,7 +608,7 @@ Sets the current USB function list in Device mode. ...@@ -608,7 +608,7 @@ Sets the current USB function list in Device mode.
**Example** **Example**
```js ```js
let funcs = HDC; let funcs = usb.HDC;
usb.setCurrentFunctions(funcs).then(() => { usb.setCurrentFunctions(funcs).then(() => {
console.info('usb setCurrentFunctions successfully.'); console.info('usb setCurrentFunctions successfully.');
}).catch(err => { }).catch(err => {
...@@ -716,7 +716,7 @@ Sets the role types supported by a specified port, which can be **powerRole** (f ...@@ -716,7 +716,7 @@ Sets the role types supported by a specified port, which can be **powerRole** (f
```js ```js
let portId = 1; let portId = 1;
usb.usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => { usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => {
console.info('usb setPortRoles successfully.'); console.info('usb setPortRoles successfully.');
}).catch(err => { }).catch(err => {
console.error('usb setPortRoles failed: ' + err.code + ' message: ' + err.message); console.error('usb setPortRoles failed: ' + err.code + ' message: ' + err.message);
......
...@@ -47,6 +47,12 @@ ...@@ -47,6 +47,12 @@
- [File Management Error Codes](errorcode-filemanagement.md) - [File Management Error Codes](errorcode-filemanagement.md)
- Network Management - Network Management
- [Upload and Download Error Codes](errorcode-request.md) - [Upload and Download Error Codes](errorcode-request.md)
- [HTTP Error Codes](errorcode-net-http.md)
- [Socket Error Codes](errorcode-net-socket.md)
- [Network Connection Management Error Codes](errorcode-net-connection.md)
- [Ethernet Connection Error Codes](errorcode-net-ethernet.md)
- [Network Sharing Error Codes](errorcode-net-sharing.md)
- [Policy Management Error Codes](errorcode-net-policy.md)
- Connectivity - Connectivity
- [NFC Error Codes](errorcode-nfc.md) - [NFC Error Codes](errorcode-nfc.md)
- [RPC Error Codes](errorcode-rpc.md) - [RPC Error Codes](errorcode-rpc.md)
......
# 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.
...@@ -74,6 +74,7 @@ Before using the Docker environment, perform the following operations: ...@@ -74,6 +74,7 @@ Before using the Docker environment, perform the following operations:
> >
> You do not need to obtain the source code for the HPM-based Docker environment. > You do not need to obtain the source code for the HPM-based Docker environment.
3. Perform subsequent operations as a user who has the root permission or has been granted the permission to use Docker.
## Standalone Docker Environment<a name="section2858536103611"></a> ## Standalone Docker Environment<a name="section2858536103611"></a>
......
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册