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

!18543 翻译已完成 17745+17746+17529+17948+17973+17999+18102+18211+18142+18388+18394+18389+18226

Merge pull request !18543 from shawn_he/18388-d
......@@ -60,7 +60,7 @@ For the complete list of APIs and example code, see [Network Sharing](../referen
4. Return the callback for successfully starting network sharing.
```js
// Import the sharing namespace from @ohos.net.sharing.
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
// Subscribe to network sharing state changes.
......@@ -85,7 +85,7 @@ sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
4. Return the callback for successfully stopping network sharing.
```js
// Import the sharing namespace from @ohos.net.sharing.
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
// Subscribe to network sharing state changes.
......@@ -110,7 +110,7 @@ sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
4. Call **stopSharing** to stop network sharing of the specified type and clear the data volume of network sharing.
```js
// Import the sharing namespace from @ohos.net.sharing.
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
// Call startSharing to start network sharing of the specified type.
......
......@@ -87,81 +87,81 @@ The implementation is similar for UDPSocket and TCPSocket connections. The follo
7. Enable the TCPSocket connection to be automatically closed after use.
```js
import socket from '@ohos.net.socket'
// Create a TCPSocket object.
let tcp = socket.constructTCPSocketInstance();
// Subscribe to TCPSocket 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.
let bindAddress = {
address: '192.168.xx.xx',
port: 1234, // Bound port, for example, 1234.
family: 1
};
tcp.bind(bindAddress, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
// Set up a connection to the specified IP address and port number.
let connectAddress = {
address: '192.168.xx.xx',
port: 5678, // Connection port, for example, 5678.
family: 1
};
tcp.connect({
address: connectAddress, timeout: 6000
}, err => {
if (err) {
console.log('connect fail');
return;
}
console.log('connect success');
// Send data.
tcp.send({
data: 'Hello, server!'
}, err => {
if (err) {
console.log('send fail');
return;
}
console.log('send success');
})
});
});
// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket connection events.
setTimeout(() => {
tcp.close((err) => {
console.log('close socket.')
});
tcp.off('message');
tcp.off('connect');
tcp.off('close');
}, 30 * 1000);
```
```js
import socket from '@ohos.net.socket'
// Create a TCPSocket object.
let tcp = socket.constructTCPSocketInstance();
// Subscribe to TCPSocket 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.
let bindAddress = {
address: '192.168.xx.xx',
port: 1234, // Bound port, for example, 1234.
family: 1
};
tcp.bind(bindAddress, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
// Set up a connection to the specified IP address and port number.
let connectAddress = {
address: '192.168.xx.xx',
port: 5678, // Connection port, for example, 5678.
family: 1
};
tcp.connect({
address: connectAddress, timeout: 6000
}, err => {
if (err) {
console.log('connect fail');
return;
}
console.log('connect success');
// Send data.
tcp.send({
data: 'Hello, server!'
}, err => {
if (err) {
console.log('send fail');
return;
}
console.log('send success');
})
});
});
// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket connection events.
setTimeout(() => {
tcp.close((err) => {
console.log('close socket.')
});
tcp.off('message');
tcp.off('connect');
tcp.off('close');
}, 30 * 1000);
```
## Implementing encrypted data transmission over TLSSocket connections
......@@ -184,6 +184,8 @@ TLSSocket connection process on the client:
7. Enable the TLSSocket connection to be automatically closed after use.
```js
import socket from '@ohos.net.socket'
// Create a TLSSocket connection (for two-way authentication).
let tlsTwoWay = socket.constructTLSSocketInstance();
......@@ -206,7 +208,7 @@ tlsTwoWay.on('close', () => {
});
// Bind the local IP address and port number.
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
tlsTwoWay.bind({ address: '192.168.xxx.xxx', port: xxxx, family: 1 }, err => {
if (err) {
console.log('bind fail');
return;
......@@ -278,7 +280,7 @@ tlsTwoWay.on('close', () => {
});
// Bind the local IP address and port number.
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
tlsOneWay.bind({ address: '192.168.xxx.xxx', port: xxxx, family: 1 }, err => {
if (err) {
console.log('bind fail');
return;
......
......@@ -3,6 +3,10 @@
- [Development of Application Event Logging](hiappevent-guidelines.md)
- [Development of Performance Tracing](hitracemeter-guidelines.md)
- [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md)
- [HiLog Development (Native)](hilog-guidelines.md)
- Error Management
- [Development of Error Manager](errormanager-guidelines.md)
- [Development of Application Recovery](apprecovery-guidelines.md)
- Log Management
- [Application Freeze (appfreeze) Log Analysis](appfreeze-guidelines.md)
- [Process Crash (cppcrash) Log Analysis](cppcrash-guidelines.md)
# Application Freeze (appfreeze) Log Analysis
## Introduction
Application freeze (appfreeze) means that an application does not respond to user operations (for example, clicking) within a given period of time. OpenHarmony provides a mechanism for detecting appfreeze faults and generates appfreeze logs for fault analysis.
> **NOTE**
>
> This guide applies only to applications in the stage model.
> Before using this guide, you must have basic knowledge about the JS applications, C++ program stacks, and application-related subsystems.
## How to Obtain
appfreeze log is a type of fault logs managed together with the native process crash, JS application crash, and system process crash logs . You can obtain the log in any of the following ways.
### Collecting Logs by Using Shell
appfreeze logs start with **appfreeze-** in **/data/log/faultlog/faultlogger/**.
The log files are named in the format of **appfreeze-application package name-application UID-time (seconds level)**.
![appfreeze_20230308145160](figures/appfreeze_20230308145160.png)
### Collecting Logs by Using DevEco Studio
DevEco Studio collects device fault logs and saves them to FaultLog.
The logs are displayed by the bundle name, fault, and time.
![appfreeze_20230308145161](figures/appfreeze_20230308145161.png)
### Collecting Logs by Using faultLogger APIs
The FaultLogger module provides APIs to query various fault information. For details, see [@ohos.faultLogger](../reference/apis/js-apis-faultLogger.md).
## appfreeze Detection
Currently, appfreeze detection supports the fault types listed in the following table.
| Fault Type| Description|
| -------- | -------- |
| THREAD_BLOCK_6S | The application main thread times out due to a suspension.|
| APPLICATION_BLOCK_INPUT | The user input response times out.|
| LIFECYCLE_TIMEOUT | Ability lifecycle switching times out.|
| APP_LIFECYCLE_TIMEOUT | Application lifecycle switching times out.|
### Application Main Thread Timeout
If this fault occurs, the main thread of the current application is suspended or too many tasks are executed, affecting task execution smoothness and experience.
Such a fault can be detected as follows: The watchdog thread of the application periodically inserts an activation detection subthread to the main thread and inserts a timeout reporting subthread to its own thread. If activation detection is not executed within 3 seconds, the THREAD_BLOCK_3S event is reported; if activation detection is not executed within 6 seconds, the THREAD_BLOCK_6S event is reported. The two events together form an appfreeze log. The following figure shows the working principle.
![appfreeze_20230308145163](figures/appfreeze_20230308145163.png)
### User Input Response Timeout
This fault affects user experience. If this fault occurs, the system does not respond to a click event within 10 seconds.
Such a fault can be detected as follows: When a user clicks a certain button of the application, the input system sends a click event to the application. If the input system does not receive a response from the application within 10 seconds, a fault event is reported. The following figure shows the working principle.
![appfreeze_20230308145162](figures/appfreeze_20230308145162.png)
### Lifecycle Switching Timeout
This fault refers to an ability lifecycle switching timeout (LIFECYCLE\_TIMEOUT) or an application lifecycle switching timeout (APP\_LIFECYCLE\_TIMEOUT).
The fault occurs during lifecycle switching and affects the switchover between abilities in the current application or the switchover between applications.
Such a fault can be detected as follows: Upon the start of a lifecycle switchover process, the main thread inserts a timeout task to the watchdog thread, and then removes the timeout task when the lifecycle switchover is complete. If the timeout duration expires, a fault event is reported.
![appfreeze_20230308145164](figures/appfreeze_20230308145164.png)
The timeout duration varies according to the lifecycle.
| Lifecycle| Timeout Duration|
| -------- | -------- |
| Load | 10s |
| Terminate | 10s |
| Connect | 3s |
| Disconnect | 0.5s |
| Foreground | 5s |
| Background | 3s |
## appfreeze Log Analysis
To identify the cause of appfreeze, analyze the appfreeze logs together with HiLog logs.
The following example uses main tread suspension as an example to illustrate how to conduct log analysis. You can treat other types of faults in a similar way.
appfreeze logs are divided into several parts, including header information, and general and specific information in the body.
### Log Header Information
| Field| Description|
| -------- | -------- |
| Reason | Reason why the application does not respond. For details, see [appfreeze Detection](#appfreeze-detection).|
| PID | PID of the failed process, which can be used to search for related process information in the log.|
| PACKAGE_NAME | Application package name.|
![appfreeze_20230310105865](figures/appfreeze_20230310105865.png)
### General Information in the Log Body
General information is present in all logs. It contains the fields listed in the following table. You can search for these fields to locate the related information in the log.
| Field| Description|
| -------- | -------- |
| EVENTNAME | One or more fault events that constitute the cause of main thread suspension.|
| TIMESTAMP | Time when the fault event reported. You can narrow down the time range for viewing HiLog logs based on the timeout duration described in [appfreeze Detection](#appfreeze-detection).|
| PID | PID of the failed process, which can be used with the timestamp and timeout duration to search for related process information in the log.|
| PACKAGE_NAME | Application package name.|
| MSG | Dump information or description of the fault.|
| OpenStacktraceCatcher | Stack trace information of the process.|
| BinderCatcher | Information about IPC calls between a process and other system processes, such as the call waiting time.|
| PeerBinder Stacktrace | Information about stack trace of the peer process.|
| cpuusage | CPU usage of the device.|
| memory | Memory usage of the process.|
The following is an example process stack of OpenStacktraceCatcher.
In this example, when the stack surface window sends events through IPC, the process is stuck in the IPC communication phase.
![appfreeze_20230310105869](figures/appfreeze_20230310105869.png)
Example BinderCatcher information:
In the following example, process 1561 sends an IPC request to process 685 but does not receive any response within 10 seconds.
![appfreeze_20230310105868](figures/appfreeze_20230310105868.png)
Example PeerBinder Stacktrace information:
The following example shows the stack information of process 685, which is suspended at the peer end.
![appfreeze_20230310105870](figures/appfreeze_20230310105870.png)
Example CPU usage information:
The following example shows the CPU usage information of the device.
![appfreeze_20230310105871](figures/appfreeze_20230310105871.png)
Example memory usage information:
The following example shows the memory usage information of the process.
![appfreeze_20230310105872](figures/appfreeze_20230310105872.png)
### Specific Information in the Log Body (Application Main Thread Timeout)
According to [Application Main Thread Timeout] (#application-main-thread-timeout), the log in which **Reason** is **THREAD\_BLOCK\_6S** consists of two parts: THREAD\_BLOCK\_3S and THREAD\_BLOCK\_6S. By comparing the two parts, you can determine whether the appfreeze is due to a suspension or an excess number of tasks.
THREAD\_BLOCK\_3S is followed by THREAD\_BLOCK\_6S in the log. You can use the **EVENTNAME** field to search for the locations of the two events in the log.
Both events contain the **MSG** field, which stores information about the processing queue of the main thread when the suspension occurs. Hence, you can view the status of the event processing queue of the main thread at the two time points.
The example log shows that the event carrying **05:06:18.145** in the low-priority queue is being processed, and it is present in both the THREAD_BLOCK_3S and THREAD_BLOCK_6S. This indicates that the main thread suspension is not caused by an excess number of tasks.
Because THREAD_BLOCK_6S indicates a main thread suspension, you only need to analyze the stack information of the main thread (the ID of the main thread is the same as the process ID). In the example log, the main thread stack is run in the JS through ArkUI and therefore it can be concluded that the suspension occurs in the JS. Because stack is present in both THREAD_BLOCK_3S and THREAD_BLOCK_6S in the same position, the JS suspension is not caused by an excess number of tasks.
THREAD_BLOCK_3S:
![appfreeze_20230310105866](figures/appfreeze_20230310105866.png)
THREAD_BLOCK_6S:
![appfreeze_20230310105867](figures/appfreeze_20230310105867.png)
Then, you can check for the code segment being executed on the application side based on the HiLog log.
Generally, you can view the [general information in the log body](#general-information-in-the-log-body) to check for the cause of the suspension, for example, IPC suspension, high CPU usage, memory leakage, or high memory usage.
### Specific Information in the Log Body (User Input Response Timeout)
If **Reason** is **APPLICATION\_BLOCK\_INPUT**, no response is received within 10 seconds after a user click.
You can find the event description in **MSG**.
For details, see [General Information in the Log Body](#general-information-in-the-log-body). Note that there is a high probability that the main thread is suspended in the case of no response to the user input. You can compare the stack and BinderCatcher information in two log records for further analysis. If there is no log record indicating a main thread suspension, a large number of other events may exist before the input event. This may not cause a main thread suspension but can probably result in no response to user input.
### Specific Information in the Log Body (Lifecycle Switching Timeout)
For a lifecycle switching timeout, **Reason** can be **LIFECYCLE\_TIMEOUT** or **APP\_LIFECYCLE\_TIMEOUT**.
**LIFECYCLE\_TIMEOUT** indicates a lifecycle switching timeout at the ability level, and **APP\_LIFECYCLE\_TIMEOUT** indicates a lifecycle switching timeout at the application level.
MSG indicates the lifecycle that encounters a timeout.
In this example, **LIFECYCLE\_TIMEOUT** indicates that the timeout occurs during switching of the ability to the background, and **APP\_LIFECYCLE\_TIMEOUT** indicates that the timeout occurs in the application termination phase. You can locate related HiLog logs according to the timeout duration described in [Lifecycle Switching Timeout] (#lifecycle-switching-timeout).
LIFECYCLE_TIMEOUT:
![appfreeze_20230310105873](figures/appfreeze_20230310105873.png)
APP_LIFECYCLE_TIMEOUT:
![appfreeze_20230310105874](figures/appfreeze_20230310105874.png)
For details about other log information, see [General Information in the Log Body](#general-information-in-the-log-body). Note that there is a high probability that the main thread is suspended during lifecycle switching. You can compare the stack and BinderCatcher information in two log records for further analysis.
......@@ -40,7 +40,9 @@ Fault management is an important way for applications to deliver a better user e
- Fault query is the process of calling APIs of [faultLogger](../reference/apis/js-apis-faultLogger.md) to obtain the fault information.
The figure below does not illustrate the time when [faultLogger](../reference/apis/js-apis-faultLogger.md) is called. You can refer to the [LastExitReason](../reference/apis/js-apis-app-ability-abilityConstant.md#abilityconstantlastexitreason) passed during application initialization to determine whether to call [faultLogger](../reference/apis/js-apis-faultLogger.md) to query information about the previous fault.
![Fault rectification process](./figures/fault_rectification.png)
It is recommended that you call [errorManager](../reference/apis/js-apis-app-ability-errorManager.md) to handle the exception. After the processing is complete, you can call the **saveAppState** API and restart the application.
If you do not register [ErrorObserver](../reference/apis/js-apis-inner-application-errorObserver.md) or enable application recovery, the application process will exit according to the default processing logic of the system. Users can restart the application from the home screen.
If you have enabled application recovery, the recovery framework first checks whether application state saving is supported and whether the application state saving is enabled. If so, the recovery framework invokes [onSaveState](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonsavestate) of the [Ability](../reference/apis/js-apis-app-ability-uiAbility.md). Finally, the application is restarted.
......
# cppcrash Log Analysis
## Introduction
A process crash refers to a C/C++ runtime crash. The FaultLogger module of OpenHarmony provides capabilities such as process crash detection, log collection, log storage, and log reporting, helping you to locate faults more effectively.
In this document, you'll be guided through how to implement process crash detection, crash log collection, and crash log analysis. Before getting started, make sure you have basic knowledge about C/C++ program stacks.
## Process Crash Detection
Process crash detection is implemented based on the Linux signal mechanism. Currently, C/C++ crash exception signals listed in the following table are supported.
| Signal Value| Signal| Description| Trigger Cause|
| ------ | --------- | --------------- | ------------------------------------------- |
| 4 | SIGILL | Invalid instruction | An invalid, incorrectly formatted, unknown, or privileged instruction is executed.|
| 5 | SIGTRAP | Breakpoint or trap | An exception occurs or a trap instruction is executed.|
| 6 | SIGABRT | Process abort | The process is aborted abnormally. Generally, this problem occurs if the process calls the `abort()` function of the standard function library.|
| 7 | SIGBUS | Illegal memory access | The process accesses an aligned or nonexistent physical address.|
| 8 | SIGFPE | Floating-point exception | The process performs an incorrect arithmetic operation, for example, a 0 divisor, floating point overflow, or integer overflow.|
| 11 | SIGSEGV | Invalid memory access | The process accesses an invalid memory reference.|
| 16 | SIGSTKFLT | Stack error | The processor performs an incorrect stack operation, such as a pop when the stack is empty or a push when the stack is full.|
| 31 | SIGSYS | Incorrect system call | An incorrect or invalid parameter is used in a system call.|
## Crash Log Collection
Process crash log is the fault log managed together with the app freeze and JS application crash logs by the FaultLogger module. You can collect process crash logs in any of the following ways:
### Collecting Logs by Using Shell
- Fault logs in the `/data/log/faultlog/faultlogger/` directory of the device. The log files are named in the format of `cppcrash-process name-process UID-time (seconds level)`. They contain only information such as the device name, system version, and process crash call stack.
![cppcrash-faultlogger-log](figures/20230407112159.png)
- Fault logs in the `/data/log/faultlog/temp/` directory of the device. The log files are named in the format of `cppcrash-process name-process PID-system timestamp (seconds level)`. In addition to basic information, they also contain information such as the stack memory and process maps at the time of process crash.
![cppcrash-temp-log](figures/20230407111853.png)
### Collecting Logs by Using DevEco Studio
DevEco Studio collects process crash logs from `/data/log/faultlog/faultlogger/` to FaultLog, where logs are displayed by process name, fault, and time.
![DevEco Studio cppcrash](figures/20230407112620.png)
### Collecting Logs by Using faultLogger APIs
The FaultLogger module provides APIs to query various fault information. For details, see [@ohos.faultLogger](../reference/apis/js-apis-faultLogger.md).
## Process Crash Log Analysis
### Log Format
The following is an example process crash log archived by DevEco Studio in FaultLog:
```
Generated by HiviewDFX@OpenHarmony
==================================================================
Device info:OpenHarmony 3.2 <- Device information
Build info:OpenHarmony 4.0.5.5 <- Version information
Module name:crasher_c <- Module name
Pid:1205 <- Process ID
Uid:0 <- User ID
Reason:Signal:SIGSEGV(SEGV_ACCERR)@0x0042d33d <- Exception information
Thread name:crasher <- Abnormal thread
#00 pc 0000332c /data/crasher(TriggerSegmentFaultException+15)(8bc37ceb8d6169e919d178fdc7f5449e) <- Call stack
#01 pc 000035c7 /data/crasher(ParseAndDoCrash+277)(8bc37ceb8d6169e919d178fdc7f5449e)
#02 pc 00003689 /data/crasher(main+39)(8bc37ceb8d6169e919d178fdc7f5449e)
#03 pc 000c3b08 /system/lib/ld-musl-arm.so.1(__libc_start_main+116)
#04 pc 000032f8 /data/crasher(_start_c+112)(8bc37ceb8d6169e919d178fdc7f5449e)
#05 pc 00003284 /data/crasher(_start+32)(8bc37ceb8d6169e919d178fdc7f5449e)
...
```
### Locating Faults Through Logs
1. Determine the faulty module and fault type based on fault logs.
Generally, you can identify the faulty module based on the crash process name and identify the crash cause based on the signal. Besides, you can restore the function call chain of the crash stack based on the method name in the stack.
In the example, **SIGSEGV** is thrown by the Linux kernel because of access to an invalid memory address. The problem occurs in the **TriggerSegmentFaultException** function.
In most scenarios, a crash is caused by the top layer of the crash stack, such as null pointer access and proactive program abort.
If the cause cannot be located through the call stack, you need to check for other faults, for example, memory corruption or stack overflow.
2. Use the addr2line tool of Linux to parse the code line number to restore the call stack at the time of process crash.
When using the addr2line tool to parse the code line number of the crash stack, make sure that binary files with debugging information is used. Generally, such files are generated during version build or application build.
Application binary files are located in DevEco Studio's temporary directory for application build, for example, `build/default/intermediates/libs`.
System binary files are stored in the directories listed below. For versions that are directly obtained, the binary files are archived in the image package.
```
\code root directory\out\product\lib.unstripped
\code root directory\out\product\exe.unstripped
```
You can run `apt-get install addr2line` to install the addr2line tool on Linux.
On On DevEco Studio, you can also use the llvm-addr2line tool archived in the SDK to parse code line numbers. The usage method is the same.
The following example shows how to use the addr2line tool to parse the code line number based on the offset address:
```
root:~/OpenHarmony/out/rk3568/exe.unstripped/hiviewdfx/faultloggerd$ addr2line -e crasher 0000332c
base/hiviewdfx/faultloggerd/tools/crasher/dfx_crasher.c:57
```
In this example, the crash is caused by assignment of a value to an unwritable area. It is in code line 57 in the **dfx_crasher.c** file. You can modify it to avoid the crash.
If the obtained code line number is seemingly incorrect, you can fine-tune the address (for example, subtract the address by 1) or disable some compilation optimization items. It is known that the obtained code line number may be incorrect when Link Time Optimization (LTO) is enabled.
# HiLog Development (Native)
## Introduction
HiLog is the log system of OpenHarmony that provides logging for the system framework, services, and applications to record information on user operations and system running status.
> **NOTE**
>
> This development guide is applicable only when you use Native APIs for application development. For details about the APIs, see [HiLog Native API Reference](../reference/native-apis/_hi_log.md).
## Available APIs
| API/Macro| Description|
| -------- | -------- |
| int OH_LOG_Print(LogType type, LogLevel level, unsigned int domain, const char *tag, const char *fmt, ...) | Outputs logs based on the specified log type, log level, service domain, log tag, and variable parameters determined by the format specifier and privacy identifier in the printf format.<br>Input arguments: See [Parameter Description](#parameter-description).<br>Output arguments: None<br>Return value: total number of bytes if log printing is successful; **-1** otherwise.|
| #define OH_LOG_DEBUG(type, ...) ((void)OH_LOG_Print((type), LOG_DEBUG, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__))| Outputs DEBUG logs. This is a function-like macro.|
| #define OH_LOG_INFO(type, ...) ((void)OH_LOG_Print((type), LOG_INFO, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs INFO logs. This is a function-like macro.|
| #define OH_LOG_WARN(type, ...) ((void)OH_LOG_Print((type), LOG_WARN, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs WARN logs. This is a function-like macro.|
| #define OH_LOG_ERROR(type, ...) ((void)OH_LOG_Print((type), LOG_ERROR, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs ERROR logs. This is a function-like macro.|
| #define OH_LOG_FATAL(type, ...) ((void)OH_LOG_Print((type), LOG_FATAL, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs FATAL logs. This is a function-like macro.|
| bool OH_LOG_IsLoggable(unsigned int domain, const char *tag, LogLevel level) | Checks whether logs of the specified service domain, tag, and level can be printed.<br>Input arguments: See [Parameter Description](#parameter-description).<br>Output arguments: none<br>Return value: **true** if the specified logs can be printed; **false** otherwise.|
## Parameter Description
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| type | enum | Yes | Log printing type. The default value is **LOG_APP** for application logs.|
| level | enum | Yes | Log printing level. For details, see [Log Level](#loglevel).|
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.<br>You can define the value as required. |
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| fmt | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **\<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
## LogLevel
Log level.
| Name | Value | Description |
| ----- | ------ | ------------------------------------------------------------ |
| DEBUG | 3 | Log level used to record more detailed process information than INFO logs to help developers analyze service processes and locate faults.|
| INFO | 4 | Log level used to record key service process nodes and exceptions that occur during service running,<br>Log level used to record information about unexpected exceptions, such as network signal loss and login failure.<br>These logs should be recorded by the dominant module in the service to avoid repeated logging conducted by multiple invoked modules or low-level functions.|
| WARN | 5 | Log level used to record severe, unexpected faults that have little impact on users and can be rectified by the programs themselves or through simple operations.|
| ERROR | 6 | Log level used to record program or functional errors that affect the normal running or use of the functionality and can be fixed at a high cost, for example, by resetting data.|
| FATAL | 7 | Log level used to record program or functionality crashes that cannot be rectified.
## Development Example
1. Add the link of **libhilog_ndk.z.so** to **CMakeLists.txt**:
```
target_link_libraries(entry PUBLIC libhilog_ndk.z.so)
```
2. Include the **hilog** header file in the source file, and define the **domain** and **tag** macros.
```c++
#include "hilog/log.h"
```
```c++
#undef LOG_DOMAIN
#undef LOG_TAG
#define LOG_DOMAIN 0x3200 // Global domain, which identifies the service domain.
#define LOG_TAG "MY_TAG" // Global tag, which identifies the module log tag.
```
3. Print logs. For example, to print ERROR logs, use the following code:
```c++
OH_LOG_ERROR(LOG_APP, "Failed to visit %{private}s, reason:%{public}d.", url, errno);
```
4. View the output log information.
```
12-11 12:21:47.579 2695 2695 E A03200/MY_TAG: Failed to visit <private>, reason:11.
```
......@@ -18,7 +18,7 @@ import batteryStats from '@ohos.batteryStatistics';
getBatteryStats(): Promise<Array&lt;BatteryStatsInfo&gt;>
Obtains the power consumption information list, using a promise to return the result.
Obtains the power consumption information list. This API uses a promise to return the result.
**System API**: This is a system API.
......@@ -34,9 +34,9 @@ Obtains the power consumption information list, using a promise to return the re
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message |
| -------- | -------------- |
| 4600101 | Operation failed. Cannot connect to service.|
| Code | Error Message |
|---------|---------|
| 4600101 | If connecting to the service failed. |
**Example**
......@@ -64,15 +64,15 @@ Obtains the power consumption information list. This API uses an asynchronous ca
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback<Array<[BatteryStatsInfo](#batterystatsinfo)>> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the array of power consumption information obtained. If the operation failed, **err** is an error object.|
| callback | AsyncCallback<Array<[BatteryStatsInfo](#batterystatsinfo)>> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the array of power consumption information obtained (that is, **Array<[BatteryStatsInfo](#batterystatsinfo)>>**). If the operation failed, **err** is an error object.|
**Error codes**
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message |
| -------- | -------------- |
| 4600101 | Operation failed. Cannot connect to service.|
| Code | Error Message |
|---------|---------|
| 4600101 | If connecting to the service failed. |
**Example**
......@@ -112,9 +112,9 @@ Obtains the power consumption of an application.
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message |
| -------- | -------------- |
| 4600101 | Operation failed. Cannot connect to service.|
| Code | Error Message |
|---------|---------|
| 4600101 | If connecting to the service failed. |
**Example**
......@@ -153,9 +153,9 @@ Obtains the proportion of the power consumption of an application.
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message |
| -------- | -------------- |
| 4600101 | Operation failed. Cannot connect to service.|
| Code | Error Message |
|---------|---------|
| 4600101 | If connecting to the service failed. |
**Example**
......@@ -194,15 +194,15 @@ Obtains the power consumption of a hardware unit according to the consumption ty
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message |
| -------- | -------------- |
| 4600101 | Operation failed. Cannot connect to service.|
| Code | Error Message |
|---------|---------|
| 4600101 | If connecting to the service failed. |
**Example**
```js
try {
var value = batteryStats.getHardwareUnitPowerValue(ConsumptionType.CONSUMPTION_TYPE_SCREEN);
var value = batteryStats.getHardwareUnitPowerValue(batteryStats.ConsumptionType.CONSUMPTION_TYPE_SCREEN);
console.info('battery statistics value of hardware is: ' + value);
} catch(err) {
console.error('get battery statistics percent of hardware failed, err: ' + err);
......@@ -235,15 +235,15 @@ Obtains the proportion of the power consumption of a hardware unit according to
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message |
| -------- | -------------- |
| 4600101 | Operation failed. Cannot connect to service.|
| Code | Error Message |
|---------|---------|
| 4600101 | If connecting to the service failed. |
**Example**
```js
try {
var percent = batteryStats.getHardwareUnitPowerPercent(ConsumptionType.CONSUMPTION_TYPE_SCREEN);
var percent = batteryStats.getHardwareUnitPowerPercent(batteryStats.ConsumptionType.CONSUMPTION_TYPE_SCREEN);
console.info('battery statistics percent of hardware is: ' + percent);
} catch(err) {
console.error('get battery statistics percent of hardware failed, err: ' + err);
......
......@@ -22,7 +22,7 @@ Sets the screen brightness.
**System API**: This is a system API.
**System capability**: SystemCapability.PowerManager.DisplayPowerManager
**System capability:** SystemCapability.PowerManager.DisplayPowerManager
**Parameters**
......@@ -34,9 +34,9 @@ Sets the screen brightness.
For details about the error codes, see [Screen Brightness Error Codes](../errorcodes/errorcode-brightness.md).
| Code | Error Message |
| ID | Error Message |
|---------|---------|
| 4700101 | Operation failed. Cannot connect to service.|
| 4700101 | If connecting to the service failed. |
**Example**
......
# @ohos.bytrace (Performance Tracing)
The **bytrace** module implements performance tracing for processes.
> **NOTE**
> - The APIs of this module are no longer maintained since API version 8. It is recommended that you use the APIs of [hiTraceMeter](js-apis-hitracemeter.md) instead.
> - The APIs of this module are no longer maintained since API version 8. You are advised to use [`@ohos.hiTraceMeter`](js-apis-hitracemeter.md).
> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```js
```js
import bytrace from '@ohos.bytrace';
```
## bytrace.startTrace
startTrace(name: string, taskId: number, expectedTime?: number): void
......@@ -20,10 +19,9 @@ startTrace(name: string, taskId: number, expectedTime?: number): void
Marks the start of a timeslice trace task.
> **NOTE**
>
> If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same taskId can be used. For details, see the bytrace.finishTrace example.
> If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same task ID can be used. For details, see the bytrace.finishTrace example.
**System capability**: SystemCapability.Developtools.Bytrace
**System capability**: SystemCapability.HiviewDFX.HiTrace
**Parameters**
......@@ -31,17 +29,16 @@ Marks the start of a timeslice trace task.
| -------- | -------- | -------- | -------- |
| name | string | Yes| Name of a timeslice trace task.|
| taskId | number | Yes| ID of a timeslice trace task.|
| expectedTime | number | No| Expected duration of the trace, in ms.|
| expectedTime | number | No| Expected duration of the trace, in ms. Optional. By default, this parameter is left blank.|
**Example**
```js
```js
bytrace.startTrace("myTestFunc", 1);
bytrace.startTrace("myTestFunc", 1, 5); // The expected duration of the trace is 5 ms.
```
## bytrace.finishTrace
finishTrace(name: string, taskId: number): void
......@@ -49,10 +46,9 @@ finishTrace(name: string, taskId: number): void
Marks the end of a timeslice trace task.
> **NOTE**
>
> To stop a trace task, the values of name and task ID in **finishTrace** must be the same as those in **startTrace**.
**System capability**: SystemCapability.Developtools.Bytrace
**System capability**: SystemCapability.HiviewDFX.HiTrace
**Parameters**
......@@ -64,15 +60,15 @@ Marks the end of a timeslice trace task.
**Example**
```js
```js
bytrace.finishTrace("myTestFunc", 1);
```
```
// Start track tasks with the same name concurrently.
// Start trace tasks with the same name concurrently.
bytrace.startTrace("myTestFunc", 1);
// Service flow
bytrace.startTrace("myTestFunc", 2); // The second trace task starts while the first task is still running. The first and second tasks have the same name but different task IDs.
bytrace.startTrace("myTestFunc", 2); // The second trace task starts while the first task is still running. The first and second tasks have the same name but different task IDs.
// Service flow
bytrace.finishTrace("myTestFunc", 1);
// Service flow
......@@ -80,34 +76,33 @@ bytrace.finishTrace("myTestFunc", 2);
```
```
// Start track tasks with the same name at different times.
// Start trace tasks with the same name in serial mode.
bytrace.startTrace("myTestFunc", 1);
// Service flow
bytrace.finishTrace("myTestFunc", 1); // The first trace task ends.
bytrace.finishTrace("myTestFunc", 1); // The first trace task ends.
// Service flow
bytrace.startTrace("myTestFunc", 1); // The second trace task starts after the first task ends. The two tasks have the same name and task ID.
bytrace.startTrace("myTestFunc", 1); // The second trace task starts after the first task ends. The two tasks have the same name and task ID.
// Service flow
bytrace.finishTrace("myTestFunc", 1);
```
## bytrace.traceByValue
traceByValue(name: string, count: number): void
Defines the variable that indicates the number of timeslice trace tasks.
Defines a numeric variable that indicates the number of timeslice trace tasks.
**System capability**: SystemCapability.HiviewDFX.HiTrace
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| name | string | Yes| Name of the variable.|
| count | number | Yes| Value of the variable.|
| name | string | Yes| Name of the numeric variable.|
| count | number | Yes| Value of the numeric variable.|
**Example**
```js
```js
let traceCount = 3;
bytrace.traceByValue("myTestCount", traceCount);
traceCount = 4;
......
......@@ -64,6 +64,9 @@ httpRequest.request(
);
```
> **NOTE**
> If the data in **console.info()** contains a newline character, the data will be truncated.
## http.createHttp
createHttp(): HttpRequest
......@@ -97,7 +100,7 @@ request(url: string, callback: AsyncCallback\<HttpResponse\>):void
Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API supports only transfer of data not greater than 5 MB.
> This API supports only receiving of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET
......@@ -148,7 +151,7 @@ request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpR
Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API supports only transfer of data not greater than 5 MB.
> This API supports only receiving of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET
......@@ -234,7 +237,7 @@ request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\>
Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result.
> **NOTE**
> This API supports only transfer of data not greater than 5 MB.
> This API supports only receiving of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET
......@@ -330,7 +333,7 @@ Destroys an HTTP request.
httpRequest.destroy();
```
### on('headerReceive')
### on('headerReceive')<sup>(deprecated)</sup>
on(type: 'headerReceive', callback: AsyncCallback\<Object\>): void
......@@ -356,7 +359,7 @@ httpRequest.on('headerReceive', (data) => {
});
```
### off('headerReceive')
### off('headerReceive')<sup>(deprecated)</sup>
off(type: 'headerReceive', callback?: AsyncCallback\<Object\>): void
......@@ -462,12 +465,12 @@ Specifies the type and value range of the optional parameters in the HTTP reques
| Name | Type | Mandatory| Description |
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method | [RequestMethod](#requestmethod) | No | Request method. The default value is **GET**. |
| extraData | string<sup>6+</sup> \| Object<sup>6+</sup> \| ArrayBuffer<sup>8+</sup> | No | Additional data for sending a request. This parameter is not used by default.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request and is encoded in UTF-8 format.<sup>6+</sup><br>- If the HTTP request uses the GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter serves as a supplement to HTTP request parameters. Parameters of the string type need to be encoded before being passed to the HTTP request. Parameters of the object type do not need to be precoded and will be directly concatenated to the URL. Parameters of the ArrayBuffer type will not be concatenated to the URL.<sup>6+</sup> |
| extraData | string<sup>6+</sup> \| Object<sup>6+</sup> \| ArrayBuffer<sup>8+</sup> | No | Additional data for sending a request. This parameter is not used by default.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request and is encoded in UTF-8 format. If **'Content-Type'** is **'application/x-www-form-urlencoded'**, the data in the request body must be encoded in the format of **key1=value1&key2=value2&key3=value3** after URL transcoding.<sup>6+</sup><br>- If the HTTP request uses the GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter serves as a supplement to HTTP request parameters. Parameters of the string type need to be encoded before being passed to the HTTP request. Parameters of the object type do not need to be precoded and will be directly concatenated to the URL. Parameters of the ArrayBuffer type will not be concatenated to the URL.<sup>6+</sup> |
| expectDataType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | No | Type of the returned data. This parameter is not used by default. If this parameter is set, the system returns the specified type of data preferentially.|
| usingCache<sup>9+</sup> | boolean | No | Whether to use the cache. The default value is **true**. |
| priority<sup>9+</sup> | number | No | Priority. The value range is \[0, 1000]. The default value is **0**. |
| priority<sup>9+</sup> | number | No | Priority. The value range is [1,1000]. The default value is **1**. |
| header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. |
| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. |
| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms.<br>The value **0** indicates no timeout.|
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
| usingProtocol<sup>9+</sup> | [HttpProtocol](#httpprotocol9) | No | Protocol. The default value is automatically specified by the system. |
......
......@@ -15,7 +15,7 @@ import connection from '@ohos.net.connection'
createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection
Creates a **NetConnection** object. **netSpecifier** specifies the network, and **timeout** specifies the timeout interval in ms. **timeout** is configurable only when **netSpecifier** is specified. If neither of them is present, the default network is used.
Creates a **NetConnection** object. **netSpecifier** specifies the network, and **timeout** specifies the timeout duration in ms. **timeout** is configurable only when **netSpecifier** is specified. If neither of them is present, the default network is used.
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -23,8 +23,8 @@ Creates a **NetConnection** object. **netSpecifier** specifies the network, and
| Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| netSpecifier | [NetSpecifier](#netspecifier) | No | Network specifier. If this parameter is not set, the default network is used. |
| timeout | number | No | Timeout interval for obtaining the network specified by **netSpecifier**. This parameter is valid only when **netSpecifier** is set.|
| netSpecifier | [NetSpecifier](#netspecifier) | No | Network specifier, which specifies the characteristics of a network. If this parameter is not set or is set to **undefined**, the default network is used. |
| timeout | number | No | Timeout duration for obtaining the network specified by **netSpecifier**. This parameter is valid only when **netSpecifier** is specified. The default value is **0** if **netSpecifier** is **undefined**.|
**Return value**
......@@ -1116,9 +1116,9 @@ netCon.unregister(function (error) {
on(type: 'netBlockStatusChange', callback: Callback&lt;{ netHandle: NetHandle, blocked: boolean }&gt;): void
Registers a listener for **netBlockStatusChange** events.
Registers a listener for **netBlockStatusChange** events. This API uses an asynchronous callback to return the result.
**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
**Model restriction**: Before you call this API, make sure that you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -1206,7 +1206,7 @@ Registers a listener for **netConnectionPropertiesChange** events.
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed to **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.|
| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the network handle (**netHandle**) and conection information (**connectionProperties**).|
| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the network handle (**netHandle**) and connection information (**connectionProperties**).|
**Example**
......
......@@ -416,7 +416,7 @@ Registers an observer for NIC hot swap events. This API uses an asynchronous cal
**Example**
```js
ethernet.on('interfaceStateChange', (data) => {
ethernet.on('interfaceStateChange', (data) => {
console.log('on interfaceSharingStateChange: ' + JSON.stringify(data));
});
```
......
......@@ -36,7 +36,7 @@ For details about the error codes, see [Power Manager Error Codes](../errorcodes
| ID | Error Message |
|---------|---------|
| 4900101 | Operation failed. Cannot connect to service.|
| 4900101 | If connecting to the service failed. |
**Example**
......@@ -72,7 +72,7 @@ For details about the error codes, see [Power Manager Error Codes](../errorcodes
| ID | Error Message |
|---------|---------|
| 4900101 | Operation failed. Cannot connect to service.|
| 4900101 | If connecting to the service failed. |
**Example**
......@@ -88,7 +88,7 @@ try {
isActive(): boolean
Checks whether the current device is active.
Checks whether the current device is active. In the active state, the screen is on if the device has a screen and the device is not in sleep state if the device does not have a screen.
**System capability:** SystemCapability.PowerManager.PowerManager.Core
......@@ -98,7 +98,7 @@ For details about the error codes, see [Power Manager Error Codes](../errorcodes
| ID | Error Message |
|---------|---------|
| 4900101 | Operation failed. Cannot connect to service.|
| 4900101 | If connecting to the service failed. |
**Example**
......@@ -133,7 +133,7 @@ For details about the error codes, see [Power Manager Error Codes](../errorcodes
| ID | Error Message |
|---------|---------|
| 4900101 | Operation failed. Cannot connect to service.|
| 4900101 | If connecting to the service failed. |
**Example**
......@@ -161,7 +161,7 @@ For details about the error codes, see [Power Manager Error Codes](../errorcodes
| ID | Error Message |
|---------|---------|
| 4900101 | Operation failed. Cannot connect to service.|
| 4900101 | If connecting to the service failed. |
**Example**
......@@ -193,7 +193,7 @@ For details about the error codes, see [Power Manager Error Codes](../errorcodes
| ID | Error Message |
|---------|---------|
| 4900101 | Operation failed. Cannot connect to service.|
| 4900101 | If connecting to the service failed. |
**Example**
......@@ -231,7 +231,7 @@ For details about the error codes, see [Power Manager Error Codes](../errorcodes
| ID | Error Message |
|---------|---------|
| 4900101 | Operation failed. Cannot connect to service.|
| 4900101 | If connecting to the service failed. |
**Example**
......@@ -275,7 +275,7 @@ For details about the error codes, see [Power Manager Error Codes](../errorcodes
| ID | Error Message |
|---------|---------|
| 4900101 | Operation failed. Cannot connect to service.|
| 4900101 | If connecting to the service failed. |
**Example**
......
# @ohos.resourceManager (Resource Manager)
The Resource Manager module provides APIs to obtain information about application resources based on the current configuration, including the language, region, screen direction, MCC/MNC, as well as device capability and density.
The **resourceManager** module provides APIs to obtain information about application resources based on the current configuration, including the language, region, screen direction, MCC/MNC, as well as device capability and density.
> **NOTE**
>
......@@ -13,7 +13,7 @@ The Resource Manager module provides APIs to obtain information about applicatio
import resourceManager from '@ohos.resourceManager';
```
## Instruction
## How to Use
Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. For the FA model, you need to import the required bundle and then call the [getResourceManager](#resourcemanagergetresourcemanager) API to obtain a **ResourceManager** object.
For details about how to reference context in the stage model, see [Context in the Stage Model](../..//application-models/application-context-stage.md).
......@@ -171,12 +171,12 @@ Enumerates the device types.
| Name | Value | Description |
| -------------------- | ---- | ---- |
| DEVICE_TYPE_PHONE | 0x00 | Phone |
| DEVICE_TYPE_TABLET | 0x01 | Tablet |
| DEVICE_TYPE_CAR | 0x02 | Head unit |
| DEVICE_TYPE_PC | 0x03 | PC |
| DEVICE_TYPE_TV | 0x04 | TV |
| DEVICE_TYPE_WEARABLE | 0x06 | Wearable |
| DEVICE_TYPE_PHONE | 0x00 | Phone. |
| DEVICE_TYPE_TABLET | 0x01 | Tablet. |
| DEVICE_TYPE_CAR | 0x02 | Head unit. |
| DEVICE_TYPE_PC | 0x03 | PC. |
| DEVICE_TYPE_TV | 0x04 | TV. |
| DEVICE_TYPE_WEARABLE | 0x06 | Wearable. |
## ScreenDensity
......@@ -278,7 +278,7 @@ Defines the capability of accessing application resources.
> **NOTE**
>
> - The APIs involved in **ResourceManager** are applicable only to the TypeScript-based declarative development paradigm.
> - The methods involved in **ResourceManager** are applicable only to the TypeScript-based declarative development paradigm.
>
> - Resource files are defined in the **resources** directory of the project. You can obtain the resource ID using **$r(resource address).id**, for example, **$r('app.string.test').id**.
......@@ -1658,7 +1658,7 @@ Obtains the string corresponding to the specified resource name. This API uses a
| Type | Description |
| --------------------- | ---------- |
| Promise&lt;string&gt; | String corresponding to the resource name.|
| Promise&lt;string&gt; | Promise used to return the result.|
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
......@@ -2036,7 +2036,7 @@ Obtains the string corresponding to the specified resource ID. This API returns
| Type | Description |
| ------ | ----------- |
| string | Promise used to return the result.|
| string | String corresponding to the specified resource ID.|
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
......@@ -2075,7 +2075,7 @@ Obtains the string corresponding to the specified resource object. This API retu
| Type | Description |
| ------ | ---------------- |
| string | Promise used to return the result.|
| string | String corresponding to the specified resource object.|
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
......
......@@ -77,7 +77,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
```
## backgroundTaskManager.getRemainingDelayTime:callback
## backgroundTaskManager.getRemainingDelayTime
getRemainingDelayTime(requestId: number, callback: AsyncCallback&lt;number&gt;): void
......@@ -126,7 +126,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
```
## backgroundTaskManager.getRemainingDelayTime:promise
## backgroundTaskManager.getRemainingDelayTime
getRemainingDelayTime(requestId: number): Promise&lt;number&gt;
......@@ -220,7 +220,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
```
## backgroundTaskManager.startBackgroundRunning:callback
## backgroundTaskManager.startBackgroundRunning
startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback&lt;void&gt;): void
......@@ -298,7 +298,7 @@ export default class EntryAbility extends UIAbility {
};
```
## backgroundTaskManager.startBackgroundRunning:promise
## backgroundTaskManager.startBackgroundRunning
startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise&lt;void&gt;
......@@ -377,7 +377,7 @@ export default class EntryAbility extends UIAbility {
};
```
## backgroundTaskManager.stopBackgroundRunning:callback
## backgroundTaskManager.stopBackgroundRunning
stopBackgroundRunning(context: Context, callback: AsyncCallback&lt;void&gt;): void
......@@ -431,7 +431,7 @@ export default class EntryAbility extends UIAbility {
};
```
## backgroundTaskManager.stopBackgroundRunning:promise
## backgroundTaskManager.stopBackgroundRunning
stopBackgroundRunning(context: Context): Promise&lt;void&gt;
......
# @ohos.runningLock (Runninglock)
# @ohos.runningLock (Running Lock)
The **runningLock** module provides APIs for creating, querying, holding, and releasing running locks.
> **NOTE**<br>
> **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......@@ -15,7 +16,7 @@ import runningLock from '@ohos.runningLock';
isSupported(type: RunningLockType): boolean;
Checks whether a specified type of **RunningLock** is supported.
Checks whether the specified type of **RunningLock** is supported. This API uses an asynchronous callback to return the result.
**System capability:** SystemCapability.PowerManager.PowerManager.Core
......@@ -25,7 +26,7 @@ Checks whether a specified type of **RunningLock** is supported.
| ------ | ----------------------------------- | ---- | -------------------- |
| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object.|
**Return value**
**Return Value**
| Type | Description |
| ------- | --------------------------------------- |
......@@ -35,9 +36,9 @@ Checks whether a specified type of **RunningLock** is supported.
For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md).
| Code | Error Message |
| ID | Error Message |
|---------|---------|
| 4900101 | Operation failed. Cannot connect to service.|
| 4900101 | If connecting to the service failed. |
**Example**
......@@ -72,9 +73,9 @@ Creates a **RunningLock** object.
For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md).
| Code | Error Message |
| ID | Error Message |
|---------|----------|
| 4900101 | Operation failed. Cannot connect to service.|
| 4900101 | If connecting to the service failed. |
**Example**
......@@ -105,7 +106,7 @@ Creates a **RunningLock** object.
| name | string | Yes | Name of the **RunningLock** object. |
| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object to be created.|
**Return value**
**Return Value**
| Type | Description |
| ------------------------------------------ | ------------------------------------ |
......@@ -115,9 +116,9 @@ Creates a **RunningLock** object.
For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md).
| Code | Error Message |
| ID | Error Message |
|---------|----------|
| 4900101 | Operation failed. Cannot connect to service.|
| 4900101 | If connecting to the service failed. |
**Example**
......@@ -135,10 +136,9 @@ runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND)
isRunningLockTypeSupported(type: RunningLockType, callback: AsyncCallback&lt;boolean&gt;): void
> NOTE<br>
> This API is deprecated since API version 9. You are advised to use [runningLock.isSupported](#runninglockissupported9) instead.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [runningLock.isSupported](#runninglockissupported9).
Checks whether a specified type of **RunningLock** is supported. This API uses an asynchronous callback to return the result.
Checks whether the specified type of **RunningLock** is supported. This API uses an asynchronous callback to return the result. This API uses an asynchronous callback to return the result.
**System capability:** SystemCapability.PowerManager.PowerManager.Core
......@@ -147,7 +147,7 @@ Checks whether a specified type of **RunningLock** is supported. This API uses a
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object. |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the query result obtained, where the value **true** indicates that **RunningLock** is supported and **false** indicates the opposite. Otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the query result obtained, where the value **true** indicates that the specified type of **RunningLock** is supported and **false** indicates the opposite. Otherwise, **err** is an error object.|
**Example**
......@@ -165,10 +165,9 @@ runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND, (
isRunningLockTypeSupported(type: RunningLockType): Promise&lt;boolean>
> NOTE<br>
> This API is deprecated since API version 9. You are advised to use [runningLock.isSupported](#runninglockissupported9) instead.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [runningLock.isSupported](#runninglockissupported9).
Checks whether a specified type of **RunningLock** is supported. This API uses a promise to return the result.
Checks whether the specified type of **RunningLock** is supported. This API uses an asynchronous callback to return the result. This API uses a promise to return the result.
**System capability:** SystemCapability.PowerManager.PowerManager.Core
......@@ -178,7 +177,7 @@ Checks whether a specified type of **RunningLock** is supported. This API uses a
| ------ | ----------------------------------- | ---- | -------------------- |
| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object.|
**Return value**
**Return Value**
| Type | Description |
| ---------------------- | ---------------------------------------------------- |
......@@ -200,8 +199,7 @@ runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND)
createRunningLock(name: string, type: RunningLockType, callback: AsyncCallback&lt;RunningLock&gt;): void
> NOTE<br>
> This API is deprecated since API version 9. You are advised to use [runningLock.create](#runninglockcreate9) instead.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [runningLock.create](#runninglockcreate9).
Creates a **RunningLock** object.
......@@ -233,8 +231,7 @@ runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.B
createRunningLock(name: string, type: RunningLockType): Promise&lt;RunningLock&gt;
> NOTE<br>
> This API is deprecated since API version 9. You are advised to use [runningLock.create](#runninglockcreate9) instead.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [runningLock.create](#runninglockcreate9).
Creates a **RunningLock** object.
......@@ -249,7 +246,7 @@ Creates a **RunningLock** object.
| name | string | Yes | Name of the **RunningLock** object. |
| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object to be created.|
**Return value**
**Return Value**
| Type | Description |
| ------------------------------------------ | ------------------------------------ |
......@@ -269,7 +266,7 @@ runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.B
## RunningLock
Represents a **RunningLock** object.
Defines a **RunningLock** object.
### hold<sup>9+</sup>
......@@ -291,9 +288,9 @@ Locks and holds a **RunningLock** object.
For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md).
| Code | Error Message |
| ID | Error Message |
|---------|----------|
| 4900101 | Operation failed. Cannot connect to service.|
| 4900101 | If connecting to the service failed. |
**Example**
......@@ -327,9 +324,9 @@ Releases a **RunningLock** object.
For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md).
| Code | Error Message |
| ID | Error Message |
|---------|----------|
| 4900101 | Operation failed. Cannot connect to service.|
| 4900101 | If connecting to the service failed. |
**Example**
......@@ -357,7 +354,7 @@ Checks the hold status of the **Runninglock** object.
**System capability:** SystemCapability.PowerManager.PowerManager.Core
**Return value**
**Return Value**
| Type | Description |
| ------- | ------------------------------------------------------------ |
......@@ -367,9 +364,9 @@ Checks the hold status of the **Runninglock** object.
For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md).
| Code | Error Message |
| ID | Error Message |
|---------|---------|
| 4900101 | Operation failed. Cannot connect to service.|
| 4900101 | If connecting to the service failed. |
**Example**
......@@ -393,8 +390,7 @@ runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND)
lock(timeout: number): void
> NOTE<br>
> This API is deprecated since API version 9. You are advised to use [RunningLock.hold](#hold9) instead.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [RunningLock.hold](#hold9).
Locks and holds a **RunningLock** object.
......@@ -425,8 +421,7 @@ runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.B
unlock(): void
> NOTE<br>
> This API is deprecated since API version 9. You are advised to use [RunningLock.unhold](#unhold9) instead.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [RunningLock.unhold](#unhold9).
Releases a **RunningLock** object.
......@@ -451,14 +446,13 @@ runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.B
isUsed(): boolean
> NOTE<br>
> This API is deprecated since API version 9. You are advised to use [RunningLock.isHolding](#isholding9) instead.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [RunningLock.isHolding](#isholding9).
Checks the hold status of the **Runninglock** object.
**System capability:** SystemCapability.PowerManager.PowerManager.Core
**Return value**
**Return Value**
| Type | Description |
| ------- | ------------------------------------------------------------ |
| boolean | The value **true** indicates that the **Runninglock** object is held; and the value **false** indicates that the **Runninglock** object is released.|
......@@ -482,7 +476,7 @@ Enumerates the types of **RunningLock** objects.
**System capability:** SystemCapability.PowerManager.PowerManager.Core
| Name | Value | Description |
| ------------------------ | ---- | -------------------------------------- |
| BACKGROUND | 1 | A lock that prevents the system from hibernating when the screen is off. |
| PROXIMITY_SCREEN_CONTROL | 2 | A lock that determines whether to turn on or off the screen based on the distance away from the screen.|
| Name | Value | Description |
| --------------------------------- | ---- | ------------------------------------------------------------ |
| BACKGROUND<sup>(deprecated)</sup> | 1 | A lock that prevents the system from hibernating when the screen is off.<br>**NOTE**<br>This parameter is supported since API version 7 and deprecated since API version 10.|
| PROXIMITY_SCREEN_CONTROL | 2 | A lock that determines whether to turn on or off the screen based on the distance away from the screen. |
......@@ -42,6 +42,9 @@ bind(address: NetAddress, callback: AsyncCallback\<void\>): void
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is used for the client to create a socket.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
......@@ -79,6 +82,9 @@ bind(address: NetAddress): Promise\<void\>
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result.
> **NOTE**
> This API is used for the client to create a socket.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
......@@ -733,6 +739,9 @@ bind(address: NetAddress, callback: AsyncCallback\<void\>): void
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is used for the client to create a socket.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
......@@ -770,6 +779,9 @@ bind(address: NetAddress): Promise\<void\>
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result.
> **NOTE**
> This API is used for the client to create a socket.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
......@@ -1605,7 +1617,7 @@ Binds the IP address and port number. This API uses an asynchronous callback to
**Example**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
tls.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => {
if (err) {
console.log('bind fail');
return;
......@@ -1648,7 +1660,7 @@ Binds the IP address and port number. This API uses a promise to return the resu
**Example**
```js
let promise = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1});
let promise = tls.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 });
promise.then(() => {
console.log('bind success');
}).catch(err => {
......@@ -1680,7 +1692,7 @@ Obtains the status of the TLSSocket connection. This API uses an asynchronous ca
**Example**
```js
let promise = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
let promise = tls.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => {
if (err) {
console.log('bind fail');
return;
......@@ -1720,7 +1732,7 @@ Obtains the status of the TLSSocket connection. This API uses a promise to retur
**Example**
```js
let promiseBind = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1});
let promiseBind = tls.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 });
promiseBind.then(() => {
console.log('bind success');
}).catch((err) => {
......@@ -1760,7 +1772,7 @@ Sets other properties of the TCPSocket connection after successful binding of th
**Example**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
tls.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => {
if (err) {
console.log('bind fail');
return;
......@@ -1772,7 +1784,7 @@ tls.setExtraOptions({
keepAlive: true,
OOBInline: true,
TCPNoDelay: true,
socketLinger: {on: true, linger: 10},
socketLinger: { on: true, linger: 10 },
receiveBufferSize: 1000,
sendBufferSize: 1000,
reuseAddress: true,
......@@ -1784,7 +1796,6 @@ tls.setExtraOptions({
}
console.log('setExtraOptions success');
});
```
### setExtraOptions<sup>9+</sup>
......@@ -1818,7 +1829,7 @@ Sets other properties of the TCPSocket connection after successful binding of th
**Example**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
tls.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => {
if (err) {
console.log('bind fail');
return;
......@@ -1829,7 +1840,7 @@ let promise = tls.setExtraOptions({
keepAlive: true,
OOBInline: true,
TCPNoDelay: true,
socketLinger: {on: true, linger: 10},
socketLinger: { on: true, linger: 10 },
receiveBufferSize: 1000,
sendBufferSize: 1000,
reuseAddress: true,
......@@ -1842,6 +1853,191 @@ promise.then(() => {
});
```
### on('message')
on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}>): void;
Subscribes to **message** events of the TLSSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event|
| callback | Callback\<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}\> | Yes | Callback used to return the result.<br> **message**: received message.<br>**remoteInfo**: socket connection information.|
**Example**
```js
let tls = socket.constructTLSSocketInstance();
tls.on('message', value => {
for (var i = 0; i < value.message.length; i++) {
let messages = value.message[i]
let message = String.fromCharCode(messages);
let messageView = '';
messageView += item;
}
console.log('on message message: ' + JSON.stringify(messageView));
console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
});
```
### off('message')
off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
Unsubscribes from **message** events of the TLSSocket connection. This API uses an asynchronous callback to return the result.
> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. **message**: received message.<br>**remoteInfo**: socket connection information.|
**Example**
```js
let tls = socket.constructTLSSocketInstance();
let callback = value => {
for (var i = 0; i < value.message.length; i++) {
let messages = value.message[i]
let message = String.fromCharCode(messages);
let messageView = '';
messageView += item;
}
console.log('on message message: ' + JSON.stringify(messageView));
console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
}
tls.on('message', callback);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tls.off('message', callback);
```
### on('connect' | 'close')
on(type: 'connect' | 'close', callback: Callback\<void\>): void
Enables listening for connection or close events of the TLSSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event|
| callback | Callback\<void\> | Yes | Callback used to return the result. |
**Example**
```js
let tls = socket.constructTLSSocketInstance();
tls.on('connect', () => {
console.log("on connect success")
});
tls.on('close', () => {
console.log("on close success")
});
```
### off('connect' | 'close')
off(type: 'connect' | 'close', callback?: Callback\<void\>): void
Disables listening for connection or close events of the TLSSocket connection. This API uses an asynchronous callback to return the result.
> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event|
| callback | Callback\<void\> | No | Callback used to return the result. |
**Example**
```js
let tls = socket.constructTLSSocketInstance();
let callback1 = () => {
console.log("on connect success");
}
tls.on('connect', callback1);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tls.off('connect', callback1);
tls.off('connect');
let callback2 = () => {
console.log("on close success");
}
tls.on('close', callback2);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tls.off('close', callback2);
```
### on('error')
on(type: 'error', callback: ErrorCallback): void
Enables listening for error events of the TLSSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event|
| callback | ErrorCallback | Yes | Callback used to return the result. |
**Example**
```js
let tls = socket.constructTLSSocketInstance();
tls.on('error', err => {
console.log("on error, err:" + JSON.stringify(err))
});
```
### off('error')
off(type: 'error', callback?: ErrorCallback): void
Disables listening for error events of the TLSSocket connection. This API uses an asynchronous callback to return the result.
> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event|
| callback | ErrorCallback | No | Callback used to return the result. |
**Example**
```js
let tls = socket.constructTLSSocketInstance();
let callback = err => {
console.log("on error, err:" + JSON.stringify(err));
}
tls.on('error', callback);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tls.off('error', callback);
```
### connect<sup>9+</sup>
connect(options: TLSConnectOptions, callback: AsyncCallback\<void\>): void
......@@ -1881,7 +2077,7 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after
```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => {
tlsTwoWay.bind({ address: '192.168.xxx.xxx', port: 8080, family: 1 }, err => {
if (err) {
console.log('bind fail');
return;
......@@ -1912,7 +2108,7 @@ tlsTwoWay.connect(options, (err, data) => {
});
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => {
tlsOneWay.bind({ address: '192.168.xxx.xxx', port: 8080, family: 1 }, err => {
if (err) {
console.log('bind fail');
return;
......@@ -1980,7 +2176,7 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after
```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => {
tlsTwoWay.bind({ address: '192.168.xxx.xxx', port: 8080, family: 1 }, err => {
if (err) {
console.log('bind fail');
return;
......@@ -2012,7 +2208,7 @@ tlsTwoWay.connect(options).then(data => {
});
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => {
tlsOneWay.bind({ address: '192.168.xxx.xxx', port: 8080, family: 1 }, err => {
if (err) {
console.log('bind fail');
return;
......
......@@ -2,7 +2,8 @@
The **thermal** module provides thermal level-related callback and query APIs to obtain the information required for thermal control.
> **NOTE**<br>
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......@@ -29,9 +30,9 @@ Subscribes to thermal level changes.
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-thermal.md).
| Code | Error Message |
| ID | Error Message |
|---------|---------|
| 4800101 | Operation failed. Cannot connect to service.|
| 4800101 | If connecting to the service failed. |
**Example**
......@@ -58,15 +59,15 @@ Unsubscribes from thermal level changes.
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------------------------------------------- |
| callback | Callback&lt;void&gt; | No | Callback used to return the result. No value is returned. If this parameter is not set, this API unsubscribes from all callbacks.|
| callback | Callback&lt;void&gt; | No | Callback that returns no value. If this parameter is not set, this API unsubscribes from all callbacks.|
**Error codes**
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-thermal.md).
| Code | Error Message |
| ID | Error Message |
|---------|---------|
| 4800101 | Operation failed. Cannot connect to service.|
| 4800101 | If connecting to the service failed. |
**Example**
......@@ -93,15 +94,15 @@ Obtains the current thermal level.
| Type | Description |
| ------------ | ------------ |
| ThermalLevel | Thermal level obtained.|
| ThermalLevel | Thermal level.|
**Error codes**
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-thermal.md).
| Code | Error Message |
| ID | Error Message |
|---------|---------|
| 4800101 | Operation failed. Cannot connect to service.|
| 4800101 | If connecting to the service failed. |
**Example**
......@@ -118,8 +119,7 @@ try {
subscribeThermalLevel(callback: AsyncCallback&lt;ThermalLevel&gt;): void
> NOTE<br>
> This API is deprecated since API version 9. You are advised to use [thermal.registerThermalLevelCallback](#thermalregisterthermallevelcallback9) instead.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [thermal.registerThermalLevelCallback](#thermalregisterthermallevelcallback9).
Subscribes to thermal level changes.
......@@ -143,8 +143,7 @@ thermal.subscribeThermalLevel((level) => {
unsubscribeThermalLevel(callback?: AsyncCallback\<void>): void
> NOTE<br>
> This API is deprecated since API version 9. You are advised to use [thermal.unregisterThermalLevelCallback](#thermalunregisterthermallevelcallback9) instead.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [thermal.unregisterThermalLevelCallback](#thermalunregisterthermallevelcallback9).
Unsubscribes from thermal level changes.
......@@ -154,7 +153,7 @@ Unsubscribes from thermal level changes.
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ---------------------------------------------- |
| callback | AsyncCallback&lt;void&gt; | No | Callback used to return the result. No value is returned. If this parameter is not set, this API unsubscribes from all callbacks.|
| callback | AsyncCallback&lt;void&gt; | No | Callback that returns no value. If this parameter is not set, this API unsubscribes from all callbacks.|
**Example**
......@@ -168,8 +167,7 @@ thermal.unsubscribeThermalLevel(() => {
getThermalLevel(): ThermalLevel
> NOTE<br>
> This API is deprecated since API version 9. You are advised to use [thermal.getLevel](#thermalgetlevel9) instead.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [thermal.getLevel](#thermalgetlevel9).
Obtains the current thermal level.
......
......@@ -115,7 +115,7 @@ The procedure is as follows:
hidumper -s 3008
```
9. Run the **hidumper -e** command to obtain the crash information generated by the FaultLoger module.
9. Run the **hidumper -e** command to obtain the crash information generated by the FaultLogger module.
```
hidumper -e
......@@ -163,6 +163,22 @@ The procedure is as follows:
```
hidumper --mem [pid]
```
The following table describes the parameters in the first column of the command output when the PID of the process is specified.
| Name | Description|
|----------------|----|
| GL | GPU memory. |
| Graph | Graphics memory. |
| ark ts heap | Memory usage of the ArkTS heap. |
| guard | Memory occupied by the protection section. |
| native heap | Heap memory. |
| AnonPage other | Memory occupied by other pages that are not mapped to files. |
| stack | Stack memory. |
| .hap | Memory occupied by the application. |
| .db | Memory occupied by the **.db** files loaded by processes. |
| .so | Memory occupied by the **.so** dynamic library files loaded by processes. |
| .ttf | Memory occupied by the **.ttf** font files loaded by processes. |
| dev | Memory occupied by the files that are named with the **/dev** prefix and loaded by processes. |
| FilePage other | Memory occupied by other pages that are mapped to files. |
17. Run the **hidumper --zip** command to compress data to the **/data/dumper** directory.
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册