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

!22885 翻译已完成21857+21753+21895+21984+22009+22026+22089+21777+21969+22266+22361+22381+22456+22540

Merge pull request !22885 from shawn_he/21878-d
# HTTP Data Request
## When to Use
## Overview
An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
......@@ -18,7 +18,7 @@ The following table provides only a simple description of the related APIs. For
| ----------------------------------------- | ----------------------------------- |
| createHttp() | Creates an HTTP request. |
| request() | Initiates an HTTP request to a given URL. |
| request2()<sup>10+</sup> | Initiates an HTTP network request based on the URL and returns a streaming response.|
| requestInStream()<sup>10+</sup> | Initiates an HTTP network request to a given URL and returns a streaming response.|
| destroy() | Destroys an HTTP request. |
| on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. |
| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events.|
......@@ -27,8 +27,8 @@ The following table provides only a simple description of the related APIs. For
| 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.|
| on\('dataReceiveProgress'\)<sup>10+</sup> | Registers an observer for events indicating progress of receiving HTTP streaming responses. |
| off\('dataReceiveProgress'\)<sup>10+</sup> | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.|
## How to Develop request APIs
......@@ -53,6 +53,7 @@ httpRequest.on('headersReceive', (header) => {
});
httpRequest.request(
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
{
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add header fields based on service requirements.
......@@ -81,7 +82,7 @@ httpRequest.request(
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy();
} else {
console.info('error:' + JSON.stringify(err));
console.error('error:' + JSON.stringify(err));
// Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Call the destroy() method to release resources after HttpRequest is complete.
......@@ -91,12 +92,12 @@ httpRequest.request(
);
```
## How to Develop request2 APIs
## How to Develop requestInStream APIs
1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Call **createHttp()** to create an **HttpRequest** object.
3. Depending on your need, call **on()** of the **HttpRequest** object to subscribe to HTTP response header events as well as events indicating receiving of HTTP streaming responses, progress of receiving HTTP streaming responses, and completion of receiving HTTP streaming responses.
4. Call **request2()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
4. Call **requestInStream()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
5. Parse the returned response code as needed.
6. Call **off()** of the **HttpRequest** object to unsubscribe from the related events.
7. Call **httpRequest.destroy()** to release resources after the request is processed.
......@@ -122,11 +123,11 @@ httpRequest.on('dataEnd', () => {
console.info('No more data in response, data receive end');
});
// Subscribe to events indicating progress of receiving HTTP streaming responses.
httpRequest.on('dataProgress', (data) => {
console.log("dataProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize);
httpRequest.on('dataReceiveProgress', (data) => {
console.log("dataReceiveProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize);
});
httpRequest.request2(
httpRequest.requestInStream(
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
{
......@@ -146,14 +147,14 @@ httpRequest.request2(
readTimeout: 60000, // Optional. The default value is 60000, in ms. If a large amount of data needs to be transmitted, you are advised to set this parameter to a larger value to ensure normal data transmission.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
}, (err, data) => {
console.info('error:' + JSON.stringify(err));
console.error('error:' + JSON.stringify(err));
console.info('ResponseCode :' + JSON.stringify(data));
// Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Unregister the observer for events indicating receiving of HTTP streaming responses.
httpRequest.off('dataReceive');
// Unregister the observer for events indicating progress of receiving HTTP streaming responses.
httpRequest.off('dataProgress');
httpRequest.off('dataReceiveProgress');
// Unregister the observer for events indicating completion of receiving HTTP streaming responses.
httpRequest.off('dataEnd');
// Call the destroy() method to release resources after HttpRequest is complete.
......@@ -161,10 +162,3 @@ httpRequest.request2(
}
);
```
## 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)
# IPC & RPC Development Guidelines
## When to Use
## Overview
IPC/RPC enables a proxy and a stub that run on different processes to communicate with each other, regardless of whether they run on the same or different devices.
......
# Network Connection Management
## Introduction
## Overview
The Network Connection Management module provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution.
> **NOTE**
>
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-connection.md).
## Basic Concepts
......
# Ethernet Connection
## Introduction
## Overview
The Ethernet Connection module allows a device to access the Internet through a network cable. After a device is connected to the Ethernet through a network cable, the device can obtain a series of network attributes, such as the dynamically allocated IP address, subnet mask, gateway, and DNS. You can manually configure and obtain the network attributes of the device in static mode.
> **NOTE**
>
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-ethernet.md).
## **Constraints**
......
# MDNS Management
## Introduction
## Overview
Multicast DNS (mDNS) provides functions such as adding, removing, discovering, and resolving local services on a LAN.
- Local service: a service provider on a LAN, for example, a printer or scanner.
......
# Network Sharing
## Introduction
## Overview
The Network Sharing module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume.
> **NOTE**
>
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-sharing.md).
## Basic Concepts
......
# Traffic Management
## Introduction
## Overview
The traffic management module allows you to query real-time or historical data traffic by the specified network interface card (NIC) or user ID (UID).
......@@ -11,6 +11,7 @@ Its functions include:
- Subscribing to traffic change events by NIC or UID
> **NOTE**
>
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [Traffic Management](../reference/apis/js-apis-net-statistics.md).
The following describes the development procedure specific to each application scenario.
......
......@@ -5,6 +5,7 @@
A virtual private network (VPN) is a dedicated network established on a public network. On a VPN, the connection between any two nodes does not have an end-to-end physical link required by the traditional private network. Instead, user data is transmitted over a logical link because a VPN is a logical network deployed over the network platform (such as the Internet) provided by the public network service provider.
> **NOTE**
>
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [Traffic Management](../reference/apis/js-apis-net-vpn.md).
The following describes the development procedure specific to each application scenario.
......
# Socket Connection
## Introduction
## Overview
The Socket Connection module allows an application to transmit data over a socket connection through the TCP, UDP, or TLS protocol.
......
# Subscribing to State Changes of a Remote Object
## Overview
IPC/RPC allows you to subscribe to the state changes of a remote stub object. When the remote stub object dies, a death notification will be sent to your local proxy object. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **DeathRecipient** interface and the **onRemoteDied** API to clear resources. This callback is invoked when the process accommodating the remote stub object dies, or the device accommodating the remote stub object leaves the network. It is worth noting that these APIs should be called in the following order: The proxy object must first subscribe to death notifications of the stub object. If the stub object is in the normal state, the proxy object can cancel the subscription as required. If the process of the stub object exits or the device hosting the stub object goes offline, subsequent operations customized by the proxy object will be automatically triggered.
## When to Use
......
# WebSocket Connection
## When to Use
## Overview
You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the **createWebSocket()** API to create a **WebSocket** object and then use the **connect()** API to connect to the server. If the connection is successful, the client will receive a callback of the **open** event. Then, the client can communicate with the server using the **send()** API. When the server sends a message to the client, the client will receive a callback of the **message** event. If the client no longer needs this connection, it can call the **close()** API to disconnect from the server. Then, the client will receive a callback of the **close** event.
......
# DFX
- [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)
- Performance Tracing
......
# Application Freeze (appfreeze) Log Analysis
## Introduction
## Overview
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.
......
# Application Recovery Development
## When to Use
## Overview
During application running, some unexpected behaviors are inevitable. For example, unprocessed exceptions and errors are thrown, and the call or running constraints of the recovery framework are violated.
......
# Process Crash (cppcrash) Log Analysis
## Introduction
## Overview
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.
......
# Development of Error Manager
## When to Use
## Overview
If coding specification issues or errors exist in the code of an application, the application may encounter unexpected errors, for example, uncaught exceptions or application lifecycle timeouts, while it is running. In such a case, the application may exit unexpectedly. Error logs, however, are usually stored on users' local storage, making it inconvenient to locate faults. With the APIs provided by the **errorManager** module, your application will be able to report related errors and logs to your service platform for fault locating before it exits.
......
# Development of Application Event Logging
## Introduction
## Overview
A traditional log system aggregates log information generated by all applications running on the entire device, making it difficult to identify key information in the log. Therefore, an effective logging mechanism is needed to evaluate mission-critical information, for example, number of visits, number of daily active users, user operation habits, and key factors that affect application usage.
......
# HiLog Development (Native)
## Introduction
## Overview
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.
......
# Development of Distributed Call Chain Tracing
## Introduction
## Overview
The hiTraceChain module provides APIs to implement call chain tracing throughout a service process. This can help you quickly obtain the run log for the call chain of a specified service process and locate faults in inter-device, inter-process, or inter-thread communications.
......
# Development of Performance Tracing (ArkTS)
## Introduction
## Overview
hiTraceMeter provides APIs for system performance tracing. You can call the APIs provided by the hiTraceMeter module in your own service logic to effectively track service processes and check the system performance.
......@@ -21,7 +21,7 @@ hiTraceMeter provides APIs for system performance tracing. You can call the APIs
## Available APIs
The performance tracing APIs are provided by the **hiTraceMeter** module. For details, see [API Reference](../reference/apis/js-apis-hitracemeter.md).
The performance tracing APIs are provided by the **hiTraceMeter** module. For details, see [API Reference]( ../reference/apis/js-apis-hitracemeter.md).
**APIs for performance tracing**
......@@ -35,51 +35,7 @@ The performance tracing APIs are provided by the **hiTraceMeter** module. For de
In this example, distributed call chain tracing begins when the application startup execution page is loaded and stops when the service usage is completed.
1. Create a JS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **js** > **default** > **pages** > **index**, and double-click **index.js**. Add the code to implement performance tracing upon page loading. The sample code is as follows:
```js
import hiTraceMeter from '@ohos.hiTraceMeter'
export default {
data: {
title: ""
},
onInit() {
this.title = this.$t('strings.world');
// Start trace tasks with the same name concurrently.
hiTraceMeter.startTrace("business", 1);
// Keep the service process running.
console.log(`business running`);
hiTraceMeter.startTrace("business", 2); // Start the second trace task with the same name while the first task is still running. The tasks are running concurrently and therefore their taskId must be different.
// Keep the service process running.
console.log(`business running`);
hiTraceMeter.finishTrace("business", 1);
// Keep the service process running.
console.log(`business running`);
hiTraceMeter.finishTrace("business", 2);
// Start trace tasks with the same name in serial mode.
hiTraceMeter.startTrace("business", 1);
// Keep the service process running.
console.log(`business running`);
hiTraceMeter.finishTrace("business", 1); // End the first trace task.
// Keep the service process running.
console.log(`business running`);
hiTraceMeter.startTrace("business", 1); // Start the second trace task with the same name in serial mode.
// Keep the service process running.
console.log(`business running`);
let traceCount = 3;
hiTraceMeter.traceByValue("myTestCount", traceCount);
traceCount = 4;
hiTraceMeter.traceByValue("myTestCount", traceCount);
hiTraceMeter.finishTrace("business", 1);
}
}
```
2. Create an ArkTs application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index**, and double-click **index.js**. Add the code to implement performance tracing upon page loading. For example, if the name of the trace task is **HITRACE\_TAG\_APP**, the sample code is as follows:
1. Create an ArkTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index**, and double-click **index.js**. Add the code to implement performance tracing upon page loading. For example, if the name of the trace task is **HITRACE\_TAG\_APP**, the sample code is as follows:
```ts
import hitrace from '@ohos.hiTraceMeter';
......
# Development of Performance Tracing (Native)
## Introduction
## Overview
hiTraceMeter provides APIs for system performance tracing. You can call the APIs provided by the hiTraceMeter module in your own service logic to effectively track service processes and check the system performance.
> **NOTE**
......
# Connecting the Neural Network Runtime to an AI Inference Framework
# Development Guide for Connecting the Neural Network Runtime to an AI Inference Framework
## When to Use
......@@ -21,7 +21,6 @@ The environment requirements for the Neural Network Runtime are as follows:
The Neural Network Runtime is opened to external systems through OpenHarmony Native APIs. Therefore, you need to use the Native development suite of the OpenHarmony to compile Neural Network Runtime applications.
### Environment Setup
1. Start the Ubuntu server.
......@@ -33,7 +32,6 @@ unzip native-linux-{version number}.zip
```
The directory structure after decompression is as follows. The content in the directory may vary depending on version iteration. Use the Native APIs of the latest version.
```text
native/
─ ─ build // Cross-compilation toolchain
......
......@@ -26,7 +26,7 @@ Prepares for screen hopping. This API uses an asynchronous callback to return th
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | --------------------------- |
| callback | AsyncCallback&lt;void&gt; | Yes|Callback used to return the result. |
| callback | AsyncCallback&lt;void&gt; | Yes|Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. |
**Example**
......@@ -56,7 +56,7 @@ Prepares for screen hopping. This API uses a promise to return the result.
| Parameters | Description |
| ------------------- | ------------------------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Promise&lt;void&gt; | Promise that returns no value.|
......@@ -75,7 +75,6 @@ try {
```
## cooperate.unprepare
unprepare(callback: AsyncCallback&lt;void&gt;): void;
......@@ -86,7 +85,7 @@ Cancels the preparation for screen hopping. This API uses an asynchronous callba
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------------------------ |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example**
......@@ -104,8 +103,6 @@ try {
}
```
## cooperate.unprepare
unprepare(): Promise&lt;void&gt;;
......@@ -118,7 +115,7 @@ Cancels the preparation for screen hopping. This API uses a promise to return th
| Parameters | Description |
| ------------------- | --------------------------------------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Promise&lt;void&gt; | Promise that returns no value.|
```js
try {
......@@ -133,7 +130,6 @@ try {
```
## cooperate.activate
activate(targetNetworkId: string, inputDeviceId: number, callback: AsyncCallback&lt;void&gt;): void;
......@@ -148,7 +144,7 @@ Starts screen hopping. This API uses an asynchronous callback to return the resu
| -------- | ---------------------------- | ---- | ---------------------------- |
| targetNetworkId | string | Yes | Descriptor of the target device for screen hopping. |
| inputDeviceId | number | Yes | Identifier of the input device for screen hopping.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
......@@ -156,7 +152,7 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode
| ID| Error Message|
| -------- | ---------------------------------------- |
| 20900001 | This error code is reported if the screen hopping status is abnormal when the screen hopping API is called. |
| 20900001 | Operation failed.|
**Example**
......@@ -197,7 +193,7 @@ Starts screen hopping. This API uses a promise to return the result.
| Name | Description |
| ---------------------- | ------------------------------- |
| Promise&lt;void&gt; | Promise used to return the result. |
| Promise&lt;void&gt; | Promise that returns no value. |
**Error codes**
......@@ -205,7 +201,7 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode
| ID| Error Message|
| -------- | ---------------------------------------- |
| 20900001 | This error code is reported if the screen hopping status is abnormal when the screen hopping API is called. |
| 20900001 | Operation failed. |
**Example**
......@@ -235,8 +231,8 @@ Stops screen hopping. This API uses an asynchronous callback to return the resul
| Name | Type | Mandatory | Description |
| -------- | ---------------------------- | ---- | ---------------------------- |
| isUnchained | boolean | Yes| Whether to disable the cross-device link.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
| isUnchained | boolean | Yes| Whether to disable the cross-device link.<br> The value **true** means to disable the cross-device link, and the value **false** means the opposite.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
......@@ -268,7 +264,7 @@ Stops screen hopping. This API uses a promise to return the result.
| Name | Type | Mandatory| Description |
| ----------- | ------- | ---- | ------------------ |
| isUnchained | boolean | Yes | Whether to disable the cross-device link.|
| isUnchained | boolean | Yes | Whether to disable the cross-device link.<br> The value **true** means to disable the cross-device link, and the value **false** means the opposite.|
......@@ -276,7 +272,7 @@ Stops screen hopping. This API uses a promise to return the result.
| Name | Description |
| -------- | ---------------------------- |
| Promise&lt;void&gt; | Promise used to return the result. |
| Promise&lt;void&gt; | Promise that returns no value. |
......@@ -307,7 +303,7 @@ Obtains the screen hopping status of the target device. This API uses an asynchr
| Name | Type | Mandatory | Description |
| -------- | --------- | ---- | ---------------------------- |
| networkId | string | Yes | Descriptor of the target device for screen hopping. |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result.|
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result. The value **true** indicates that screen hopping is enabled, and the value **false** indicates the opposite.|
**Example**
......@@ -346,7 +342,7 @@ Obtains the screen hopping status of the target device. This API uses a promise
| Parameters | Description |
| ------------------- | ------------------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** indicates that screen hopping is enabled, and the value **false** indicates the opposite.|
......
......@@ -4,7 +4,7 @@ The **hiAppEvent** module provides the application event logging functions, such
> **NOTE**
>
> - The APIs provided by this module are deprecated since API version 9. You are advised to use [`@ohos.hiviewdfx.hiAppEvent`](js-apis-hiviewdfx-hiappevent.md) instead.
> - The APIs provided by this module are deprecated since API version 9. You are advised to use [`@ohos.hiviewdfx.hiAppEvent`](js-apis-hiviewdfx-hiappevent.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.
......@@ -20,7 +20,7 @@ Before using application event logging, you need to understand the requirements
**Event Name**
An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (\_).
An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter or dollar sign ($) and cannot end with an underscore (_).
**Event Type**
......@@ -30,8 +30,8 @@ An event type is an enumerated value of [EventType](#eventtype).
An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows:
- A parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (\_).
- The parameter value can be of the string, number, boolean, or array type.
- A parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter or dollar sign ($) and cannot end with an underscore (_).
- A parameter value can be of the string, number, boolean, or array type.
- If the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be discarded.
- If the parameter value is a number, the value must be within the range of **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. Otherwise, uncertain values may be generated.
- If the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.
......@@ -156,12 +156,12 @@ Provides the configuration items for application event logging.
| Name | Type | Mandatory| Description |
| ---------- | ------- | ---- | ------------------------------------------------------------ |
| disable | boolean | No | Application event logging switch. The value **true** means to disable the application event logging function, and the value **false** means the opposite.|
| maxStorage | string | No | Maximum size of the event file storage directory. The default value is <strong>10M</strong>. If the specified size is exceeded, the oldest event logging files in the directory will be deleted to free up space.|
| maxStorage | string | No | Maximum size of the event file storage directory. The default value is **10M**. If the specified size is exceeded, the oldest event logging files in the directory will be deleted to free up space.|
## EventType
Enumerates event types.
Enumerates the event types.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
......
......@@ -122,10 +122,10 @@ Defines parameters for an **AppEventInfo** object.
| Name | Type | Mandatory| Description |
| --------- | ----------------------- | ---- | ------------------------------------------------------------ |
| domain | string | Yes | Event domain. Event domain name, which is a string of up to 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).|
| name | string | Yes | Event name. Event name, which is a string of up to 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).|
| domain | string | Yes | Event domain. The value is a string of up to 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).|
| name | string | Yes | Event name. The value is a string of up to 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter or dollar sign ($) and cannot end with an underscore (_).|
| eventType | [EventType](#eventtype) | Yes | Event type. |
| params | object | Yes | Event parameter object, which consists of a parameter name and a parameter value. The specifications are as follows:<br>- The parameter name is a string of up to 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).<br>- The parameter value can be a string, number, boolean, or array. If the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be discarded. If the parameter value is a number, the value must be within the range of **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. Otherwise, uncertain values may be generated. If the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.<br>- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.|
| params | object | Yes | Event parameter object, which consists of a parameter name and a parameter value. The specifications are as follows:<br>- The parameter name is a string of up to 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter or dollar sign ($) and cannot end with an underscore (_).<br>- The parameter value can be a string, number, boolean, or array. If the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be discarded. If the parameter value is a number, the value must be within the range of **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. Otherwise, uncertain values may be generated. If the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.<br>- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.|
## hiAppEvent.configure
......@@ -436,7 +436,7 @@ hiAppEvent.clearData();
## EventType
Enumerates event types.
Enumerates the event types.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
......
......@@ -86,7 +86,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req
| Type | Description |
| :---------- | :----------------------------------------------------------- |
| HttpRequest | An **HttpRequest** object, which contains the **request**, **request2**, **destroy**, **on**, or **off** method.|
| HttpRequest | An **HttpRequest** object, which contains the **request**, **requestInStream**, **destroy**, **on**, or **off** method.|
**Example**
......@@ -364,9 +364,9 @@ Destroys an HTTP request.
httpRequest.destroy();
```
### request2<sup>10+</sup>
### requestInStream<sup>10+</sup>
request2(url: string, callback: AsyncCallback\<number\>): void
requestInStream(url: string, callback: AsyncCallback\<number\>): void
Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response.
......@@ -424,18 +424,18 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Example**
```js
httpRequest.request2("EXAMPLE_URL", (err, data) => {
httpRequest.requestInStream("EXAMPLE_URL", (err, data) => {
if (!err) {
console.info("request2 OK! ResponseCode is " + JSON.stringify(data));
console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data));
} else {
console.info("request2 ERROR : err = " + JSON.stringify(err));
console.info("requestInStream ERROR : err = " + JSON.stringify(err));
}
})
```
### request2<sup>10+</sup>
### requestInStream<sup>10+</sup>
request2(url: string, options: HttpRequestOptions, callback: AsyncCallback\<number\>): void
requestInStream(url: string, options: HttpRequestOptions, callback: AsyncCallback\<number\>): void
Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response.
......@@ -494,7 +494,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Example**
```js
httpRequest.request2("EXAMPLE_URL",
httpRequest.requestInStream("EXAMPLE_URL",
{
method: http.RequestMethod.GET,
header: {
......@@ -504,16 +504,16 @@ httpRequest.request2("EXAMPLE_URL",
connectTimeout: 60000
}, (err, data) => {
if (!err) {
console.info("request2 OK! ResponseCode is " + JSON.stringify(data));
console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data));
} else {
console.info("request2 ERROR : err = " + JSON.stringify(err));
console.info("requestInStream ERROR : err = " + JSON.stringify(err));
}
})
```
### request2<sup>10+</sup>
### requestInStream<sup>10+</sup>
request2(url: string, options? : HttpRequestOptions): Promise\<number\>
requestInStream(url: string, options? : HttpRequestOptions): Promise\<number\>
Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result, which is a streaming response.
......@@ -577,7 +577,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Example**
```js
let promise = httpRequest.request2("EXAMPLE_URL", {
let promise = httpRequest.requestInStream("EXAMPLE_URL", {
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000,
......@@ -586,9 +586,9 @@ let promise = httpRequest.request2("EXAMPLE_URL", {
}
});
promise.then((data) => {
console.info("request2 OK!" + JSON.stringify(data));
console.info("requestInStream OK!" + JSON.stringify(data));
}).catch((err) => {
console.info("request2 ERROR : err = " + JSON.stringify(err));
console.info("requestInStream ERROR : err = " + JSON.stringify(err));
});
```
......@@ -815,9 +815,9 @@ Unregisters the observer for events indicating completion of receiving HTTP stre
httpRequest.off('dataEnd');
```
### on('dataProgress')<sup>10+</sup>
### on('dataReceiveProgress')<sup>10+</sup>
on(type: 'dataProgress', callback: Callback\<{ receiveSize: number, totalSize: number }\>): void
on(type: 'dataReceiveProgress', callback: Callback\<{ receiveSize: number, totalSize: number }\>): void
Registers an observer for events indicating progress of receiving HTTP streaming responses.
......@@ -830,20 +830,20 @@ Registers an observer for events indicating progress of receiving HTTP streaming
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | --------------------------------- |
| type | string | Yes | Event type. The value is **dataProgress**.|
| type | string | Yes | Event type. The value is **dataReceiveProgress**.|
| callback | AsyncCallback\<{ receiveSize: number, totalSize: number }\> | Yes | Callback used to return the result.<br>- **receiveSize**: number of received bytes.<br>- **totalSize**: total number of bytes to be received.|
**Example**
```js
httpRequest.on('dataProgress', (data) => {
console.info('dataProgress:' + JSON.stringify(data));
httpRequest.on('dataReceiveProgress', (data) => {
console.info('dataReceiveProgress:' + JSON.stringify(data));
});
```
### off('dataProgress')<sup>10+</sup>
### off('dataReceiveProgress')<sup>10+</sup>
off(type: 'dataProgress', callback?: Callback\<{ receiveSize: number, totalSize: number }\>): void
off(type: 'dataReceiveProgress', callback?: Callback\<{ receiveSize: number, totalSize: number }\>): void
Unregisters the observer for events indicating progress of receiving HTTP streaming responses.
......@@ -856,13 +856,13 @@ Unregisters the observer for events indicating progress of receiving HTTP stream
| Name | Type | Mandatory| Description |
| -------- | ------------------ | ---- | -------------------------------------- |
| type | string | Yes | Event type. The value is **dataProgress**.|
| type | string | Yes | Event type. The value is **dataReceiveProgress**.|
| callback | Callback\<{ receiveSize: number, totalSize: number }\> | No | Callback used to return the result. |
**Example**
```js
httpRequest.off('dataProgress');
httpRequest.off('dataReceiveProgress');
```
## HttpRequestOptions<sup>6+</sup>
......
......@@ -158,7 +158,7 @@ Obtains the global HTTP proxy configuration of the network. This API uses an asy
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback\<[HttpProxy](#httpproxy)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.|
| callback | AsyncCallback\<[HttpProxy](#httpproxy10)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.|
**Error codes**
......@@ -192,7 +192,7 @@ Obtains the global HTTP proxy configuration of the network. This API uses a prom
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<[HttpProxy](#httpproxy)> | Promise used to return the result.|
| Promise\<[HttpProxy](#httpproxy10)> | Promise used to return the result.|
**Error codes**
......@@ -229,7 +229,7 @@ Sets the global HTTP proxy configuration of the network. This API uses an asynch
| Name | Type | Mandatory| Description |
| --------- | ----------------------- | ---- | ------------------------------------------------------------ |
| httpProxy | [HttpProxy](#httpproxy) | Yes | Global HTTP proxy configuration of the network. |
| httpProxy | [HttpProxy](#httpproxy10) | Yes | Global HTTP proxy configuration of the network. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is set successfully, **error** is **undefined**. Otherwise, **error** is an error object.|
**Error codes**
......@@ -274,7 +274,7 @@ Sets the global HTTP proxy configuration of the network. This API uses a promise
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| httpProxy | [HttpProxy](#httpproxy) | Yes | Global HTTP proxy configuration of the network.|
| httpProxy | [HttpProxy](#httpproxy10) | Yes | Global HTTP proxy configuration of the network.|
**Return value**
......@@ -324,7 +324,7 @@ This API uses an asynchronous callback to return the result.
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback<[HttpProxy](#httpproxy)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.|
| callback | AsyncCallback<[HttpProxy](#httpproxy10)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.|
**Error codes**
......@@ -347,7 +347,7 @@ connection.getDefaultHttpProxy((error, data) => {
getDefaultHttpProxy(): Promise\<HttpProxy>;
Obtains the default proxy configuration of the network.
If the global proxy is set, the global proxy configuration is returned. If [setAppNet](#connectionsetappnet) is used to bind the application to the network specified by [NetHandle](#nethandle), the proxy configuration of this network is returned. In other cases, the HTTP proxy configuration of the default network is returned.
If the global proxy is set, the global HTTP proxy configuration is returned. If [setAppNet](#connectionsetappnet) is used to bind the application to the network specified by [NetHandle](#nethandle), the HTTP proxy configuration of this network is returned. In other cases, the HTTP proxy configuration of the default network is returned.
This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -356,7 +356,7 @@ This API uses a promise to return the result.
| Type | Description |
| -------------------------------- | ----------------------------------------- |
| Promise<[HttpProxy](#httpproxy)> | Promise used to return the result.|
| Promise<[HttpProxy](#httpproxy10)> | Promise used to return the result.|
**Error codes**
......
......@@ -486,7 +486,7 @@ Defines the network configuration for the Ethernet connection.
| gateway | string | Yes| Gateway of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.|
| netMask | string | Yes| Subnet mask of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.|
| dnsServers | string | Yes| DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).|
| httpProxy<sup>10+</sup> | [HttpProxy](js-apis-net-connection.md#httpproxy) | No| HTTP proxy of the Ethernet connection. By default, no proxy is configured.|
| httpProxy<sup>10+</sup> | [HttpProxy](js-apis-net-connection.md#httpproxy10) | No| HTTP proxy of the Ethernet connection. By default, no proxy is configured.|
## IPSetMode<sup>9+</sup>
......
......@@ -850,7 +850,7 @@ Enumerates mouse pointer styles.
| MIDDLE_BTN_SOUTH_EAST | 36 | Scrolling south-east |![MID_Btn_South_East.png](./figures/MID_Btn_South_East.png)|
| MIDDLE_BTN_SOUTH_WEST | 37 | Scrolling south-west |![MID_Btn_South_West.png](./figures/MID_Btn_South_West.png)|
| MIDDLE_BTN_NORTH_SOUTH_WEST_EAST | 38 | Moving as a cone in four directions|![MID_Btn_North_South_West_East.png](./figures/MID_Btn_North_South_West_East.png)|
| HORIZONTAL_TEXT_CURSOR<sup>10+</sup> | 39 | Horizontal text selection|![Horizontal_Text_Cursor.png](./figures/Horizontal_Text_Cursor.png)|
| HORIZONTAL_TEXT_CURSOR<sup>10+</sup> | 39 | Horizontal text cursor|![Horizontal_Text_Cursor.png](./figures/Horizontal_Text_Cursor.png)|
| CURSOR_CROSS<sup>10+</sup> | 40 | Cross cursor|![Cursor_Cross.png](./figures/Cursor_Cross.png)|
| CURSOR_CIRCLE<sup>10+</sup> | 41 | Circular cursor|![Cursor_Circle.png](./figures/Cursor_Circle.png)|
......@@ -1726,3 +1726,357 @@ try {
console.log(`getTouchpadRightClickType failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## pointer.setPointerSize<sup>10+</sup>
setPointerSize(size: number, callback: AsyncCallback&lt;void&gt;): void
Sets the pointer size. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.Pointer
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ------------------------------------- |
| size | number | Yes | Pointer size. The value ranges from **1** to **7**. The default value is **1**. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example**
```js
try {
pointer.setPointerSize(1, (error) => {
if (error) {
console.log(`setPointerSize failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
}
console.log(`setPointerSize success`);
});
} catch (error) {
console.log(`setPointerSize failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## pointer.setPointerSize<sup>10+</sup>
setPointerSize(size: number): Promise&lt;void&gt;
Sets the pointer size. This API uses a promise to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.Pointer
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----------------------------------- |
| size | number | Yes | Pointer size. The value ranges from **1** to **7**. The default value is **1**.|
**Return value**
| Name | Description |
| ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```js
try {
pointer.setPointerSize(3).then(() => {
console.log(`setPointerSize success`);
});
} catch (error) {
console.log(`setPointerSize failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## pointer.setPointerSizeSync<sup>10+</sup>
setPointerSizeSync(size: number): void;
Sets the pointer size. This API returns the result synchronously.
**System capability**: SystemCapability.MultimodalInput.Input.Pointer
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----------------------------------- |
| size | number | Yes | Pointer size. The value ranges from **1** to **7**. The default value is **1**.|
**Example**
```js
try {
pointer.setPointerSizeSync(5);
console.log(`setPointerSizeSync success`);
} catch (error) {
console.log(`setPointerSizeSync failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## pointer.getPointerSize<sup>10+</sup>
getPointerSize(callback: AsyncCallback&lt;number&gt;): void
Obtains the pointer size. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.Pointer
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | -------------- |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the result.|
**Example**
```js
try {
pointer.getPointerSize((error, size) => {
console.log(`getPointerSize success, size: ${JSON.stringify(size)}`);
});
} catch (error) {
console.log(`getPointerSize failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## pointer.getPointerSize<sup>10+</sup>
getPointerSize(): Promise&lt;number&gt;
Obtains the pointer size. This API uses a promise to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.Pointer
**System API**: This is a system API.
**Return value**
| Name | Description |
| --------------------- | ------------------- |
| Promise&lt;number&gt; | Promise used to return the result.|
**Example**
```js
try {
pointer.getPointerSize().then((size) => {
console.log(`getPointerSize success, size: ${JSON.stringify(size)}`);
});
} catch (error) {
console.log(`getPointerSize failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## pointer.getPointerSizeSync<sup>10+</sup>
getPointerSizeSync(): number
Obtains the pointer size. This API returns the result synchronously.
**System capability**: SystemCapability.MultimodalInput.Input.Pointer
**System API**: This is a system API.
**Return value**
| Name | Description |
| --------------------- | ------------------- |
| number | Pointer size. |
**Example**
```js
try {
let pointerSize = pointer.getPointerSizeSync();
console.log(`getPointerSizeSync success, pointerSize: ${JSON.stringify(pointerSize)}`);
} catch (error) {
console.log(`getPointerSizeSync failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## pointer.setPointerColor<sup>10+</sup>
setPointerColor(color: number, callback: AsyncCallback&lt;void&gt;): void
Sets the pointer color. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.Pointer
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ------------------------------------- |
| color | number | Yes | Pointer color. The default value is **black** (0x000000). |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example**
```js
try {
pointer.setPointerColor(0xF6C800, (error) => {
if (error) {
console.log(`setPointerColor failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
}
console.log(`setPointerColor success`);
});
} catch (error) {
console.log(`setPointerColor failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## pointer.setPointerColor<sup>10+</sup>
setPointerColor(color: number): Promise&lt;void&gt;
Sets the pointer color. This API uses a promise to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.Pointer
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----------------------------------- |
| color | number | Yes | Pointer color. The default value is **black** (0x000000).|
**Return value**
| Name | Description |
| ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```js
try {
pointer.setPointerColor(0xF6C800).then(() => {
console.log(`setPointerColor success`);
});
} catch (error) {
console.log(`setPointerColor failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## pointer.setPointerColorSync<sup>10+</sup>
setPointerColorSync(color: number): void;
Sets the pointer color. This API returns the result synchronously.
**System capability**: SystemCapability.MultimodalInput.Input.Pointer
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----------------------------------- |
| color | number | Yes | Pointer color. The default value is **black** (0x000000).|
**Example**
```js
try {
pointer.setPointerColorSync(0xF6C800);
console.log(`setPointerColorSync success`);
} catch (error) {
console.log(`setPointerColorSync failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## pointer.getPointerColor<sup>10+</sup>
getPointerColor(callback: AsyncCallback&lt;number&gt;): void
Obtains the pointer color. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.Pointer
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | -------------- |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the result.|
**Example**
```js
try {
pointer.getPointerColor((error, color) => {
console.log(`getPointerColor success, color: ${JSON.stringify(color)}`);
});
} catch (error) {
console.log(`getPointerColor failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## pointer.getPointerColor<sup>10+</sup>
getPointerColor(): Promise&lt;number&gt;
Obtains the pointer color. This API uses a promise to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.Pointer
**System API**: This is a system API.
**Return value**
| Name | Description |
| --------------------- | ------------------- |
| Promise&lt;number&gt; | Promise used to return the result.|
**Example**
```js
try {
pointer.getPointerColor().then((color) => {
console.log(`getPointerColor success, color: ${JSON.stringify(color)}`);
});
} catch (error) {
console.log(`getPointerColor failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## pointer.getPointerColorSync<sup>10+</sup>
getPointerColorSync(): number
Obtains the pointer color. This API returns the result synchronously.
**System capability**: SystemCapability.MultimodalInput.Input.Pointer
**System API**: This is a system API.
**Return value**
| Name | Description |
| --------------------- | ------------------- |
| number | Pointer color.|
**Example**
```js
try {
let pointerColor = pointer.getPointerColorSync();
console.log(`getPointerColorSync success, pointerColor: ${JSON.stringify(pointerColor)}`);
} catch (error) {
console.log(`getPointerColorSync failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
......@@ -150,7 +150,6 @@ Obtains the **ResourceManager** object of an application based on the specified
});
```
## resourceManager.getSystemResourceManager<sup>10+</sup>
getSystemResourceManager(): ResourceManager
......@@ -177,16 +176,16 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
```js
import resourceManager from '@ohos.resourceManager';
try {
try {
let systemResourceManager = resourceManager.getSystemResourceManager();
systemResourceManager.getStringValue($r('sys.string.ohos_lab_vibrate').id).then(value => {
let str = value;
}).catch(error => {
console.log("systemResourceManager getStringValue promise error is " + error);
});
} catch (error) {
} catch (error) {
console.error(`systemResourceManager getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
}
}
```
......@@ -259,7 +258,7 @@ Defines the device capability.
| Name | Type | Readable | Writable | Description |
| ------------- | ------------------------------- | ---- | ---- | -------- |
| screenDensity | [ScreenDensity](#screendensity) | Yes | No | Screen density of the device.|
| deviceType | [DeviceType](#devicetype) | Yes | No | Type of the device. |
| deviceType | [DeviceType](#devicetype) | Yes | No | Device type. |
## RawFileDescriptor<sup>8+</sup>
......@@ -301,20 +300,25 @@ Defines the capability of accessing application resources.
>
> - 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**.
### getStringValue<sup>9+</sup>
### getStringSync<sup>9+</sup>
getStringValue(resId: number, callback: AsyncCallback&lt;string&gt;): void
getStringSync(resId: number): string
Obtains the string corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
Obtains the string corresponding to the specified resource ID. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | --------------- |
| resId | number | Yes | Resource ID. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| ------ | ----------- |
| string | String corresponding to the specified resource ID.|
**Error codes**
......@@ -322,31 +326,24 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the module resId invalid. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example (stage)**
**Example**
```ts
try {
this.context.resourceManager.getStringValue($r('app.string.test').id, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let str = value;
}
});
this.context.resourceManager.getStringSync($r('app.string.test').id);
} catch (error) {
console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getStringSync<sup>10+</sup>
### getStringValue<sup>9+</sup>
getStringValue(resId: number): Promise&lt;string&gt;
getStringSync(resId: number, ...args: Array<string | number>): string
Obtains the string corresponding to the specified resource ID. This API uses a promise to return the result.
Obtains the string corresponding to the specified resource ID and formats the string based on **args**. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -355,42 +352,39 @@ Obtains the string corresponding to the specified resource ID. This API uses a p
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| args | Array<string \| number> | No | Arguments for formatting strings.<br> Supported arguments:<br> %d, %f, %s, and %%<br> Note: **%%** is used to translate **%**.<br>Example: **%%d** is translated into the **%d** string.|
**Return value**
| Type | Description |
| --------------------- | ----------- |
| Promise&lt;string&gt; | Promise used to return the result.|
| ------ | ---------------------------- |
| string | Formatted string.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| -------- | ----------------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
| 9001007 | If the resource obtained by resId formatting error. |
**Example**
```ts
try {
this.context.resourceManager.getStringValue($r('app.string.test').id).then(value => {
let str = value;
}).catch(error => {
console.log("getStringValue promise error is " + error);
});
this.context.resourceManager.getStringSync($r('app.string.test').id, "format string", 10, 98.78);
} catch (error) {
console.error(`promise getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getStringSync<sup>9+</sup>
### getStringValue<sup>9+</sup>
getStringValue(resource: Resource, callback: AsyncCallback&lt;string&gt;): void
getStringSync(resource: Resource): string
Obtains the string corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
Obtains the string corresponding to the specified resource object. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -399,9 +393,14 @@ Obtains the string corresponding to the specified resource object. This API uses
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | --------------- |
| resource | [Resource](#resource9) | Yes | Resource object. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
**Return value**
| Type | Description |
| ------ | ---------------- |
| string | String corresponding to the specified resource object.|
**Error codes**
......@@ -421,25 +420,17 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
id: $r('app.string.test').id
};
try {
this.context.resourceManager.getStringValue(resource, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let str = value;
}
});
this.context.resourceManager.getStringSync(resource);
} catch (error) {
console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getStringSync<sup>10+</sup>
### getStringValue<sup>9+</sup>
getStringValue(resource: Resource): Promise&lt;string&gt;
getStringSync(resource: Resource, ...args: Array<string | number>): string
Obtains the string corresponding to the specified resource object. This API uses a promise to return the result.
Obtains the string corresponding to the specified resource object and formats the string based on **args**. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -450,12 +441,13 @@ Obtains the string corresponding to the specified resource object. This API uses
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| args | Array<string \| number> | No | Arguments for formatting strings.<br> Supported arguments:<br> %d, %f, %s, and %%<br> Note: **%%** is used to translate **%**.<br>Example: **%%d** is translated into the **%d** string.|
**Return value**
| Type | Description |
| --------------------- | ---------------- |
| Promise&lt;string&gt; | Promise used to return the result.|
| ------ | ---------------------------- |
| string | Formatted string.|
**Error codes**
......@@ -466,6 +458,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
| 9001007 | If the resource obtained by resId formatting error. |
**Example**
```ts
......@@ -475,31 +468,31 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
id: $r('app.string.test').id
};
try {
this.context.resourceManager.getStringValue(resource).then(value => {
let str = value;
}).catch(error => {
console.log("getStringValue promise error is " + error);
});
this.context.resourceManager.getStringSync(resource, "format string", 10, 98.78);
} catch (error) {
console.error(`promise getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getStringByNameSync<sup>9+</sup>
### getStringArrayValue<sup>9+</sup>
getStringArrayValue(resId: number, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void
getStringByNameSync(resName: string): string
Obtains the string array corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
Obtains the string corresponding to the specified resource name. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------- |
| resId | number | Yes | Resource ID. |
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback used to return the result.|
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| ------ | ---------- |
| string | String corresponding to the specified resource name.|
**Error codes**
......@@ -507,45 +500,39 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let strArray = value;
}
});
this.context.resourceManager.getStringByNameSync("test");
} catch (error) {
console.error(`callback getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getStringByNameSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getStringByNameSync<sup>10+</sup>
### getStringArrayValue<sup>9+</sup>
getStringArrayValue(resId: number): Promise&lt;Array&lt;string&gt;&gt;
getStringByNameSync(resName: string, ...args: Array<string | number>): string
Obtains the string array corresponding to the specified resource ID. This API uses a promise to return the result.
Obtains the string corresponding to the specified resource name and formats the string based on **args**. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
| args | Array<string \| number> | No | Arguments for formatting strings.<br> Supported arguments:<br> %d, %f, %s, and %%<br> Note: **%%** is used to translate **%**.<br>Example: **%%d** is translated into the **%d** string.|
**Return value**
| Type | Description |
| ---------------------------------- | ------------- |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the result.|
| ------ | ---------------------------- |
| string | Formatted string.|
**Error codes**
......@@ -553,39 +540,34 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
| 9001008 | If the resource obtained by resName formatting error. |
**Example**
```ts
try {
this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id).then(value => {
let strArray = value;
}).catch(error => {
console.log("getStringArrayValue promise error is " + error);
});
this.context.resourceManager.getStringByNameSync("test", "format string", 10, 98.78);
} catch (error) {
console.error(`promise getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getStringByNameSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getStringArrayValue<sup>9+</sup>
### getStringValue<sup>9+</sup>
getStringArrayValue(resource: Resource, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void
getStringValue(resId: number, callback: AsyncCallback&lt;string&gt;): void
Obtains the string array corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
Obtains the string corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------- |
| resource | [Resource](#resource9) | Yes | Resource object. |
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback used to return the result.|
| -------- | --------------------------- | ---- | --------------- |
| resId | number | Yes | Resource ID. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
**Error codes**
......@@ -593,51 +575,44 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001001 | If the module resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
**Example (stage)**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.strarray.test').id
};
try {
this.context.resourceManager.getStringArrayValue(resource, (error, value) => {
this.context.resourceManager.getStringValue($r('app.string.test').id, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let strArray = value;
let str = value;
}
});
} catch (error) {
console.error(`callback getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getStringArrayValue<sup>9+</sup>
### getStringValue<sup>9+</sup>
getStringArrayValue(resource: Resource): Promise&lt;Array&lt;string&gt;&gt;
getStringValue(resId: number): Promise&lt;string&gt;
Obtains the string array corresponding to the specified resource object. This API uses a promise to return the result.
Obtains the string corresponding to the specified resource ID. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| ---------------------------------- | ------------------ |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the result.|
| --------------------- | ----------- |
| Promise&lt;string&gt; | Promise used to return the result.|
**Error codes**
......@@ -651,36 +626,33 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.strarray.test').id
};
try {
this.context.resourceManager.getStringArrayValue(resource).then(value => {
let strArray = value;
this.context.resourceManager.getStringValue($r('app.string.test').id).then(value => {
let str = value;
}).catch(error => {
console.log("getStringArray promise error is " + error);
console.log("getStringValue promise error is " + error);
});
} catch (error) {
console.error(`promise getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContent<sup>9+</sup>
### getStringValue<sup>9+</sup>
getMediaContent(resId: number, callback: AsyncCallback&lt;Uint8Array&gt;): void
getStringValue(resource: Resource, callback: AsyncCallback&lt;string&gt;): void
Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
Obtains the string corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ------------------ |
| resId | number | Yes | Resource ID. |
| callback | AsyncCallback&lt;Uint8Array&gt; | Yes | Callback used to return the result.|
| -------- | --------------------------- | ---- | --------------- |
| resource | [Resource](#resource9) | Yes | Resource object. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
**Error codes**
......@@ -690,37 +662,49 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.string.test').id
};
try {
this.context.resourceManager.getMediaContent($r('app.media.test').id, (error, value) => {
this.context.resourceManager.getStringValue(resource, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let media = value;
let str = value;
}
});
} catch (error) {
console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContent<sup>10+</sup>
### getStringValue<sup>9+</sup>
getMediaContent(resId: number, density: number, callback: AsyncCallback&lt;Uint8Array&gt;): void
getStringValue(resource: Resource): Promise&lt;string&gt;
Obtains the content of the media file with the screen density corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
Obtains the string corresponding to the specified resource object. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ------------------ |
| resId | number | Yes | Resource ID. |
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
| callback | AsyncCallback&lt;Uint8Array&gt; | Yes | Callback used to return the result.|
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
**Return value**
| Type | Description |
| --------------------- | ---------------- |
| Promise&lt;string&gt; | Promise used to return the result.|
**Error codes**
......@@ -730,41 +714,85 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.string.test').id
};
try {
this.context.resourceManager.getMediaContent($r('app.media.test').id, 120, (error, value) => {
this.context.resourceManager.getStringValue(resource).then(value => {
let str = value;
}).catch(error => {
console.log("getStringValue promise error is " + error);
});
} catch (error) {
console.error(`promise getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getStringByName<sup>9+</sup>
getStringByName(resName: string, callback: AsyncCallback&lt;string&gt;): void
Obtains the string corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | --------------- |
| resName | string | Yes | Resource name. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getStringByName("test", (error, value) => {
if (error != null) {
console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
console.log("error is " + error);
} else {
let media = value;
let str = value;
}
});
} catch (error) {
console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getStringByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContent<sup>9+</sup>
### getStringByName<sup>9+</sup>
getMediaContent(resId: number): Promise&lt;Uint8Array&gt;
getStringByName(resName: string): Promise&lt;string&gt;
Obtains the content of the media file corresponding to the specified resource ID. This API uses a promise to return the result.
Obtains the string corresponding to the specified resource name. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| ------------------------- | -------------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.|
| --------------------- | ---------- |
| Promise&lt;string&gt; | Promise used to return the result.|
**Error codes**
......@@ -772,27 +800,28 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getMediaContent($r('app.media.test').id).then(value => {
let media = value;
this.context.resourceManager.getStringByName("test").then(value => {
let str = value;
}).catch(error => {
console.log("getMediaContent promise error is " + error);
console.log("getStringByName promise error is " + error);
});
} catch (error) {
console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getStringByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContent<sup>10+</sup>
### getStringArrayValueSync<sup>10+</sup>
getMediaContent(resId: number, density: number): Promise&lt;Uint8Array&gt;
getStringArrayValueSync(resId: number): Array&lt;string&gt;
Obtains the content of the media file with the screen density corresponding to the specified resource ID. This API uses a promise to return the result.
Obtains the string array corresponding to the specified resource ID. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -801,13 +830,12 @@ Obtains the content of the media file with the screen density corresponding to t
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
**Return value**
| Type | Description |
| ------------------------- | -------------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.|
| --------------------- | ----------- |
| Array&lt;string&gt; | String array corresponding to the specified resource ID.|
**Error codes**
......@@ -817,25 +845,22 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getMediaContent($r('app.media.test').id, 120).then(value => {
let media = value;
}).catch(error => {
console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
});
this.context.resourceManager.getStringArrayValueSync($r('app.strarray.test').id);
} catch (error) {
console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getStringArrayValueSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContent<sup>9+</sup>
### getStringArrayValueSync<sup>10+</sup>
getMediaContent(resource: Resource, callback: AsyncCallback&lt;Uint8Array&gt;): void
getStringArrayValueSync(resource: Resource): Array&lt;string&gt;
Obtains the content of the media file corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
Obtains the string array corresponding to the specified resource object. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -844,9 +869,14 @@ Obtains the content of the media file corresponding to the specified resource ob
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ------------------ |
| resource | [Resource](#resource9) | Yes | Resource object. |
| callback | AsyncCallback&lt;Uint8Array&gt; | Yes | Callback used to return the result.|
| ----- | ------ | ---- | ----- |
| resource | [Resource](#resource9) | Yes | Resource object.|
**Return value**
| Type | Description |
| --------------------- | ----------- |
| Array&lt;string&gt; | String array corresponding to the specified resource object.|
**Error codes**
......@@ -856,44 +886,36 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
id: $r('app.strarray.test').id
};
try {
this.context.resourceManager.getMediaContent(resource, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let media = value;
}
});
this.context.resourceManager.getStringArrayValueSync(resource);
} catch (error) {
console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getStringArrayValueSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContent<sup>10+</sup>
### getStringArrayValue<sup>9+</sup>
getMediaContent(resource: Resource, density: number, callback: AsyncCallback&lt;Uint8Array&gt;): void
getStringArrayValue(resId: number, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void
Obtains the content of the media file with the screen density corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
Obtains the string array corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ------------------ |
| resource | [Resource](#resource9) | Yes | Resource object. |
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
| callback | AsyncCallback&lt;Uint8Array&gt; | Yes | Callback used to return the result.|
| -------- | ---------------------------------------- | ---- | ----------------- |
| resId | number | Yes | Resource ID. |
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback used to return the result.|
**Error codes**
......@@ -903,48 +925,42 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
};
try {
this.context.resourceManager.getMediaContent(resource, 120, (error, value) => {
this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id, (error, value) => {
if (error != null) {
console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
console.log("error is " + error);
} else {
let media = value;
let strArray = value;
}
});
} catch (error) {
console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContent<sup>9+</sup>
### getStringArrayValue<sup>9+</sup>
getMediaContent(resource: Resource): Promise&lt;Uint8Array&gt;
getStringArrayValue(resId: number): Promise&lt;Array&lt;string&gt;&gt;
Obtains the content of the media file corresponding to the specified resource object. This API uses a promise to return the result.
Obtains the string array corresponding to the specified resource ID. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| ------------------------- | ------------------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.|
| ---------------------------------- | ------------- |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the result.|
**Error codes**
......@@ -954,30 +970,26 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
};
try {
this.context.resourceManager.getMediaContent(resource).then(value => {
let media = value;
this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id).then(value => {
let strArray = value;
}).catch(error => {
console.log("getMediaContent promise error is " + error);
console.log("getStringArrayValue promise error is " + error);
});
} catch (error) {
console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContent<sup>10+</sup>
### getStringArrayValue<sup>9+</sup>
getMediaContent(resource: Resource, density: number): Promise&lt;Uint8Array&gt;
getStringArrayValue(resource: Resource, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void
Obtains the content of the media file with the screen density corresponding to the specified resource object. This API uses a promise to return the result.
Obtains the string array corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -986,15 +998,9 @@ Obtains the content of the media file with the screen density corresponding to t
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
**Return value**
| Type | Description |
| ------------------------- | ------------------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.|
| -------- | ---------------------------------------- | ---- | ----------------- |
| resource | [Resource](#resource9) | Yes | Resource object. |
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback used to return the result.|
**Error codes**
......@@ -1004,39 +1010,49 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
id: $r('app.strarray.test').id
};
try {
this.context.resourceManager.getMediaContent(resource, 120).then(value => {
let media = value;
}).catch(error => {
console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
this.context.resourceManager.getStringArrayValue(resource, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let strArray = value;
}
});
} catch (error) {
console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContentBase64<sup>9+</sup>
### getStringArrayValue<sup>9+</sup>
getMediaContentBase64(resId: number, callback: AsyncCallback&lt;string&gt;): void
getStringArrayValue(resource: Resource): Promise&lt;Array&lt;string&gt;&gt;
Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
Obtains the string array corresponding to the specified resource object. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------ |
| resId | number | Yes | Resource ID. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
**Return value**
| Type | Description |
| ---------------------------------- | ------------------ |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the result.|
**Error codes**
......@@ -1046,37 +1062,40 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.strarray.test').id
};
try {
this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let media = value;
}
this.context.resourceManager.getStringArrayValue(resource).then(value => {
let strArray = value;
}).catch(error => {
console.log("getStringArray promise error is " + error);
});
} catch (error) {
console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContentBase64<sup>10+</sup>
### getStringArrayByName<sup>9+</sup>
getMediaContentBase64(resId: number, density: number, callback: AsyncCallback&lt;string&gt;): void
getStringArrayByName(resName: string, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void
Obtains the Base64 code of an image with the screen density corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
Obtains the string array corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------ |
| resId | number | Yes | Resource ID. |
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
| -------- | ---------------------------------------- | ---- | ----------------- |
| resName | string | Yes | Resource name. |
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback used to return the result.|
**Error codes**
......@@ -1084,43 +1103,44 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120, (error, value) => {
this.context.resourceManager.getStringArrayByName("test", (error, value) => {
if (error != null) {
console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
console.log("error is " + error);
} else {
let media = value;
let strArray = value;
}
});
} catch (error) {
console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getStringArrayByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContentBase64<sup>9+</sup>
### getStringArrayByName<sup>9+</sup>
getMediaContentBase64(resId: number): Promise&lt;string&gt;
getStringArrayByName(resName: string): Promise&lt;Array&lt;string&gt;&gt;
Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses a promise to return the result.
Obtains the string array corresponding to the specified resource name. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| --------------------- | -------------------- |
| Promise&lt;string&gt; | Promise used to return the result.|
| ---------------------------------- | ------------ |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the result.|
**Error codes**
......@@ -1128,27 +1148,28 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getMediaContentBase64($r('app.media.test').id).then(value => {
let media = value;
this.context.resourceManager.getStringArrayByName("test").then(value => {
let strArray = value;
}).catch(error => {
console.log("getMediaContentBase64 promise error is " + error);
console.log("getStringArrayByName promise error is " + error);
});
} catch (error) {
console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getStringArrayByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContentBase64<sup>10+</sup>
### getPluralStringValueSync<sup>10+</sup>
getMediaContentBase64(resId: number, density: number): Promise&lt;string&gt;
getPluralStringValueSync(resId: number, num: number): string
Obtains the Base64 code of an image with the screen density corresponding to the specified resource ID. This API uses a promise to return the result.
Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -1157,13 +1178,13 @@ Obtains the Base64 code of an image with the screen density corresponding to the
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
| num | number | Yes | Number. |
**Return value**
| Type | Description |
| --------------------- | -------------------- |
| Promise&lt;string&gt; | Promise used to return the result.|
| -------- | ----------- |
| string | Singular-plural string corresponding to the specified resource ID.|
**Error codes**
......@@ -1173,25 +1194,22 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120).then(value => {
let media = value;
}).catch(error => {
console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
});
this.context.resourceManager.getPluralStringValueSync($r('app.plural.test').id, 1);
} catch (error) {
console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getPluralStringValueSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContentBase64<sup>9+</sup>
### getPluralStringValueSync<sup>10+</sup>
getMediaContentBase64(resource: Resource, callback: AsyncCallback&lt;string&gt;): void
getPluralStringValueSync(resource: Resource, num: number): string
Obtains the Base64 code of the image corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -1200,9 +1218,15 @@ Obtains the Base64 code of the image corresponding to the specified resource obj
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------ |
| resource | [Resource](#resource9) | Yes | Resource object. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
| ----- | ------ | ---- | ----- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| num | number | Yes | Number. |
**Return value**
| Type | Description |
| --------------------- | ----------- |
| string | Singular-plural string corresponding to the specified resource object.|
**Error codes**
......@@ -1212,43 +1236,36 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
id: $r('app.plural.test').id
};
try {
this.context.resourceManager.getMediaContentBase64(resource, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let media = value;
}
});
this.context.resourceManager.getPluralStringValueSync(resource, 1);
} catch (error) {
console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getPluralStringValueSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContentBase64<sup>10+</sup>
### getPluralStringValue<sup>9+</sup>
getMediaContentBase64(resource: Resource, density: number, callback: AsyncCallback&lt;string&gt;): void
getPluralStringValue(resId: number, num: number, callback: AsyncCallback&lt;string&gt;): void
Obtains the Base64 code of an image with the screen density corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------ |
| resource | [Resource](#resource9) | Yes | Resource object. |
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
| -------- | --------------------------- | ---- | ------------------------------- |
| resId | number | Yes | Resource ID. |
| num | number | Yes | Number. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
**Error codes**
......@@ -1259,42 +1276,37 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
};
try {
this.context.resourceManager.getMediaContentBase64(resource, 120, (error, value) => {
this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1, (error, value) => {
if (error != null) {
console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
console.log("error is " + error);
} else {
let media = value;
let str = value;
}
});
} catch (error) {
console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContentBase64<sup>9+</sup>
### getPluralStringValue<sup>9+</sup>
getMediaContentBase64(resource: Resource): Promise&lt;string&gt;
getPluralStringValue(resId: number, num: number): Promise&lt;string&gt;
Obtains the Base64 code of the image corresponding to the specified resource object. This API uses a promise to return the result.
Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| num | number | Yes | Number. |
**Return value**
......@@ -1310,30 +1322,74 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1).then(value => {
let str = value;
}).catch(error => {
console.log("getPluralStringValue promise error is " + error);
});
} catch (error) {
console.error(`promise getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getPluralStringValue<sup>9+</sup>
getPluralStringValue(resource: Resource, num: number, callback: AsyncCallback&lt;string&gt;): void
Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------------------ |
| resource | [Resource](#resource9) | Yes | Resource object. |
| num | number | Yes | Number. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
id: $r('app.plural.test').id
};
try {
this.context.resourceManager.getMediaContentBase64(resource).then(value => {
let media = value;
}).catch(error => {
console.log("getMediaContentBase64 promise error is " + error);
this.context.resourceManager.getPluralStringValue(resource, 1, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let str = value;
}
});
} catch (error) {
console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContentBase64<sup>10+</sup>
### getPluralStringValue<sup>9+</sup>
getMediaContentBase64(resource: Resource, density: number): Promise&lt;string&gt;
getPluralStringValue(resource: Resource, num: number): Promise&lt;string&gt;
Obtains the Base64 code of an image with the screen density corresponding to the specified resource object. This API uses a promise to return the result.
Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -1344,12 +1400,12 @@ Obtains the Base64 code of an image with the screen density corresponding to the
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
| num | number | Yes | Number. |
**Return value**
| Type | Description |
| --------------------- | ------------------------- |
| --------------------- | ------------------------------ |
| Promise&lt;string&gt; | Promise used to return the result.|
**Error codes**
......@@ -1360,159 +1416,222 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
id: $r('app.plural.test').id
};
try {
this.context.resourceManager.getMediaContentBase64(resource, 120).then(value => {
let media = value;
this.context.resourceManager.getPluralStringValue(resource, 1).then(value => {
let str = value;
}).catch(error => {
console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
console.log("getPluralStringValue promise error is " + error);
});
} catch (error) {
console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getConfiguration
### getPluralStringByName<sup>9+</sup>
getConfiguration(callback: AsyncCallback&lt;Configuration&gt;): void
getPluralStringByName(resName: string, num: number, callback: AsyncCallback&lt;string&gt;): void
Obtains the device configuration. This API uses an asynchronous callback to return the result.
Obtains the plural string corresponding to the specified resource name based on the specified number. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------------------------- |
| callback | AsyncCallback&lt;[Configuration](#configuration)&gt; | Yes | Callback used to return the result.|
| -------- | --------------------------- | ---- | ----------------------------- |
| resName | string | Yes | Resource name. |
| num | number | Yes | Number. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getConfiguration((error, value) => {
this.context.resourceManager.getPluralStringByName("test", 1, (error, value) => {
if (error != null) {
console.error("getConfiguration callback error is " + error);
console.log("error is " + error);
} else {
let direction = value.direction;
let locale = value.locale;
let str = value;
}
});
} catch (error) {
console.error("getConfiguration callback error is " + error);
console.error(`callback getPluralStringByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getPluralStringByName<sup>9+</sup>
### getConfiguration
getConfiguration(): Promise&lt;Configuration&gt;
getPluralStringByName(resName: string, num: number): Promise&lt;string&gt;
Obtains the device configuration. This API uses a promise to return the result.
Obtains the plural string corresponding to the specified resource name based on the specified number. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
| num | number | Yes | Number. |
**Return value**
| Type | Description |
| ---------------------------------------- | ---------------- |
| Promise&lt;[Configuration](#configuration)&gt; | Promise used to return the result.|
| --------------------- | ---------------------- |
| Promise&lt;string&gt; | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getConfiguration().then(value => {
let direction = value.direction;
let locale = value.locale;
this.context.resourceManager.getPluralStringByName("test", 1).then(value => {
let str = value;
}).catch(error => {
console.error("getConfiguration promise error is " + error);
console.log("getPluralStringByName promise error is " + error);
});
} catch (error) {
console.error("getConfiguration promise error is " + error);
console.error(`promise getPluralStringByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContentSync<sup>10+</sup>
### getDeviceCapability
getDeviceCapability(callback: AsyncCallback&lt;DeviceCapability&gt;): void
getMediaContentSync(resId: number, density?: number): Uint8Array
Obtains the device capability. This API uses an asynchronous callback to return the result.
Obtains the content of the media file (with the default or specified screen density) corresponding to the specified resource ID. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------- |
| callback | AsyncCallback&lt;[DeviceCapability](#devicecapability)&gt; | Yes | Callback used to return the result.|
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.|
**Return value**
| Type | Description |
| -------- | ----------- |
| Uint8Array | Content of the media file corresponding to the specified resource ID.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
try {
this.context.resourceManager.getDeviceCapability((error, value) => {
if (error != null) {
console.error("getDeviceCapability callback error is " + error);
} else {
let screenDensity = value.screenDensity;
let deviceType = value.deviceType;
this.context.resourceManager.getMediaContentSync($r('app.media.test').id); // Default screen density
} catch (error) {
console.error(`getMediaContentSync failed, error code: ${error.code}, message: ${error.message}.`);
}
});
try {
this.context.resourceManager.getMediaContentSync($r('app.media.test').id, 120); // Specified screen density
} catch (error) {
console.error("getDeviceCapability callback error is " + error);
console.error(`getMediaContentSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContentSync<sup>10+</sup>
### getDeviceCapability
getDeviceCapability(): Promise&lt;DeviceCapability&gt;
getMediaContentSync(resource: Resource, density?: number): Uint8Array
Obtains the device capability. This API uses a promise to return the result.
Obtains the content of the media file (with the default or specified screen density) corresponding to the specified resource object. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.|
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------- |
| Promise&lt;[DeviceCapability](#devicecapability)&gt; | Promise used to return the result.|
| --------------------- | ----------- |
| Uint8Array | Content of the media file corresponding to the specified resource object|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
};
try {
this.context.resourceManager.getDeviceCapability().then(value => {
let screenDensity = value.screenDensity;
let deviceType = value.deviceType;
}).catch(error => {
console.error("getDeviceCapability promise error is " + error);
});
this.context.resourceManager.getMediaContentSync(resource); // Default screen density
} catch (error) {
console.error("getDeviceCapability promise error is " + error);
console.error(`getMediaContentSync failed, error code: ${error.code}, message: ${error.message}.`);
}
try {
this.context.resourceManager.getMediaContentSync(resource, 120); // Specified screen density
} catch (error) {
console.error(`getMediaContentSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getPluralStringValue<sup>9+</sup>
### getMediaContent<sup>9+</sup>
getPluralStringValue(resId: number, num: number, callback: AsyncCallback&lt;string&gt;): void
getMediaContent(resId: number, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses an asynchronous callback to return the result.
Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------------- |
| -------- | ------------------------------- | ---- | ------------------ |
| resId | number | Yes | Resource ID. |
| num | number | Yes | Number. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
| callback | AsyncCallback&lt;Uint8Array&gt; | Yes | Callback used to return the result.|
**Error codes**
......@@ -1522,44 +1641,37 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1, (error, value) => {
this.context.resourceManager.getMediaContent($r('app.media.test').id, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let str = value;
let media = value;
}
});
} catch (error) {
console.error(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContent<sup>10+</sup>
### getPluralStringValue<sup>9+</sup>
getPluralStringValue(resId: number, num: number): Promise&lt;string&gt;
getMediaContent(resId: number, density: number, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses a promise to return the result.
Obtains the content of the media file (with the specified screen density) corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| num | number | Yes | Number. |
**Return value**
| Type | Description |
| --------------------- | ------------------------- |
| Promise&lt;string&gt; | Promise used to return the result.|
| -------- | ------------------------------- | ---- | ------------------ |
| resId | number | Yes | Resource ID. |
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
| callback | AsyncCallback&lt;Uint8Array&gt; | Yes | Callback used to return the result.|
**Error codes**
......@@ -1569,38 +1681,41 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1).then(value => {
let str = value;
}).catch(error => {
console.log("getPluralStringValue promise error is " + error);
this.context.resourceManager.getMediaContent($r('app.media.test').id, 120, (error, value) => {
if (error != null) {
console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
} else {
let media = value;
}
});
} catch (error) {
console.error(`promise getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getPluralStringValue<sup>9+</sup>
### getMediaContent<sup>9+</sup>
getPluralStringValue(resource: Resource, num: number, callback: AsyncCallback&lt;string&gt;): void
getMediaContent(resId: number): Promise&lt;Uint8Array&gt;
Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API uses an asynchronous callback to return the result.
Obtains the content of the media file corresponding to the specified resource ID. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------------------ |
| resource | [Resource](#resource9) | Yes | Resource object. |
| num | number | Yes | Number. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| ------------------------- | -------------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.|
**Error codes**
......@@ -1610,50 +1725,40 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.plural.test').id
};
try {
this.context.resourceManager.getPluralStringValue(resource, 1, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let str = value;
}
this.context.resourceManager.getMediaContent($r('app.media.test').id).then(value => {
let media = value;
}).catch(error => {
console.log("getMediaContent promise error is " + error);
});
} catch (error) {
console.error(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getPluralStringValue<sup>9+</sup>
### getMediaContent<sup>10+</sup>
getPluralStringValue(resource: Resource, num: number): Promise&lt;string&gt;
getMediaContent(resId: number, density: number): Promise&lt;Uint8Array&gt;
Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API uses a promise to return the result.
Obtains the content of the media file (with the specified screen density) corresponding to the specified resource ID. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| num | number | Yes | Number. |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
**Return value**
| Type | Description |
| --------------------- | ------------------------------ |
| Promise&lt;string&gt; | Promise used to return the result.|
| ------------------------- | -------------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.|
**Error codes**
......@@ -1663,40 +1768,35 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.plural.test').id
};
try {
this.context.resourceManager.getPluralStringValue(resource, 1).then(value => {
let str = value;
this.context.resourceManager.getMediaContent($r('app.media.test').id, 120).then(value => {
let media = value;
}).catch(error => {
console.log("getPluralStringValue promise error is " + error);
console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
console.error(`promise getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContent<sup>9+</sup>
### getRawFileContent<sup>9+</sup>
getRawFileContent(path: string, callback: AsyncCallback&lt;Uint8Array&gt;): void
getMediaContent(resource: Resource, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the content of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result.
Obtains the content of the media file corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ----------------------- |
| path | string | Yes | Path of the raw file. |
| -------- | ------------------------------- | ---- | ------------------ |
| resource | [Resource](#resource9) | Yes | Resource object. |
| callback | AsyncCallback&lt;Uint8Array&gt; | Yes | Callback used to return the result.|
**Error codes**
......@@ -1705,79 +1805,97 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001005 | If the resource not found by path. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
};
try {
this.context.resourceManager.getRawFileContent("test.xml", (error, value) => {
this.context.resourceManager.getMediaContent(resource, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let rawFile = value;
let media = value;
}
});
} catch (error) {
console.error(`callback getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getRawFileContent<sup>9+</sup>
### getMediaContent<sup>10+</sup>
getRawFileContent(path: string): Promise&lt;Uint8Array&gt;
getMediaContent(resource: Resource, density: number, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the content of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result.
Obtains the content of the media file (with the specified screen density) corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----------- |
| path | string | Yes | Path of the raw file.|
| -------- | ------------------------------- | ---- | ------------------ |
| resource | [Resource](#resource9) | Yes | Resource object. |
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
| callback | AsyncCallback&lt;Uint8Array&gt; | Yes | Callback used to return the result.|
**Return value**
| Type | Description |
| ------------------------- | ----------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.|
**Error codes**
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001005 | If the resource not found by path. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
};
try {
this.context.resourceManager.getRawFileContent("test.xml").then(value => {
let rawFile = value;
}).catch(error => {
console.log("getRawFileContent promise error is " + error);
this.context.resourceManager.getMediaContent(resource, 120, (error, value) => {
if (error != null) {
console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
} else {
let media = value;
}
});
} catch (error) {
console.error(`promise getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaContent<sup>9+</sup>
### getRawFd<sup>9+</sup>
getRawFd(path: string, callback: AsyncCallback&lt;RawFileDescriptor&gt;): void
getMediaContent(resource: Resource): Promise&lt;Uint8Array&gt;
Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result.
Obtains the content of the media file corresponding to the specified resource object. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | -------------------------------- |
| path | string | Yes | Path of the raw file. |
| callback | AsyncCallback&lt;[RawFileDescriptor](#rawfiledescriptor8)&gt; | Yes | Callback used to return the result.|
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
**Return value**
| Type | Description |
| ------------------------- | ------------------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.|
**Error codes**
......@@ -1785,44 +1903,49 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001005 | If the resource not found by path. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
};
try {
this.context.resourceManager.getRawFd("test.xml", (error, value) => {
if (error != null) {
console.log(`callback getRawFd failed error code: ${error.code}, message: ${error.message}.`);
} else {
let fd = value.fd;
let offset = value.offset;
let length = value.length;
}
this.context.resourceManager.getMediaContent(resource).then(value => {
let media = value;
}).catch(error => {
console.log("getMediaContent promise error is " + error);
});
} catch (error) {
console.error(`callback getRawFd failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getRawFd<sup>9+</sup>
### getMediaContent<sup>10+</sup>
getRawFd(path: string): Promise&lt;RawFileDescriptor&gt;
getMediaContent(resource: Resource, density: number): Promise&lt;Uint8Array&gt;
Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result.
Obtains the content of the media file (with the specified screen density) corresponding to the specified resource object. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----------- |
| path | string | Yes | Path of the raw file.|
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------- |
| Promise&lt;[RawFileDescriptor](#rawfiledescriptor8)&gt; | Promise used to return the result.|
| ------------------------- | ------------------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.|
**Error codes**
......@@ -1830,37 +1953,41 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001005 | If the resource not found by path. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
};
try {
this.context.resourceManager.getRawFd("test.xml").then(value => {
let fd = value.fd;
let offset = value.offset;
let length = value.length;
this.context.resourceManager.getMediaContent(resource, 120).then(value => {
let media = value;
}).catch(error => {
console.log(`promise getRawFd error error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
console.error(`promise getRawFd failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getRawFileList<sup>10+</sup>
### getMediaByName<sup>9+</sup>
getRawFileList(path: string, callback: AsyncCallback&lt;Array\<string\>&gt;): void;
getMediaByName(resName: string, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the list of files in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result.
Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ----------------------- |
| path | string | Yes | Path of the **rawfile** folder. |
| callback | AsyncCallback&lt;Array\<string\>&gt; | Yes| Callback used to return the result.|
| -------- | ------------------------------- | ---- | ------------------ |
| resName | string | Yes | Resource name. |
| callback | AsyncCallback&lt;Uint8Array&gt; | Yes | Callback used to return the result.|
**Error codes**
......@@ -1868,42 +1995,39 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001005 | If the resource not found by path. |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
**Example**
```ts
try { // Passing "" means to obtain the list of files in the root directory of the raw file.
this.context.resourceManager.getRawFileList("", (error, value) => {
try {
this.context.resourceManager.getMediaByName("test", (error, value) => {
if (error != null) {
console.error(`callback getRawFileList failed, error code: ${error.code}, message: ${error.message}.`);
console.log("error is " + error);
} else {
let rawFile = value;
let media = value;
}
});
} catch (error) {
console.error(`callback getRawFileList failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getRawFileList<sup>10+</sup>
### getMediaByName<sup>10+</sup>
getRawFileList(path: string): Promise&lt;Array\<string\>&gt;
getMediaByName(resName: string, density: number, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the list of files in the **resources/rawfile** directory. This API uses a promise to return the result.
Obtains the content of the media file (with the specified screen density) corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----------- |
| path | string | Yes | Path of the **rawfile** folder.|
**Return value**
| Type | Description |
| ------------------------- | ----------- |
| Promise&lt;Array\<string\>&gt; | List of files in the **rawfile** folder.|
| -------- | ------------------------------- | ---- | ------------------ |
| resName | string | Yes | Resource name. |
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
| callback | AsyncCallback&lt;Uint8Array&gt; | Yes | Callback used to return the result.|
**Error codes**
......@@ -1911,35 +2035,43 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001005 | If the resource not found by path. |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
**Example**
```ts
try { // Passing "" means to obtain the list of files in the root directory of the raw file.
this.context.resourceManager.getRawFileList("").then(value => {
let rawFile = value;
}).catch(error => {
console.error(`promise getRawFileList failed, error code: ${error.code}, message: ${error.message}.`);
try {
this.context.resourceManager.getMediaByName("test", 120, (error, value) => {
if (error != null) {
console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
} else {
let media = value;
}
});
} catch (error) {
console.error(`promise getRawFileList failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### closeRawFd<sup>9+</sup>
### getMediaByName<sup>9+</sup>
closeRawFd(path: string, callback: AsyncCallback&lt;void&gt;): void
getMediaByName(resName: string): Promise&lt;Uint8Array&gt;
Closes the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result.
Obtains the content of the media file corresponding to the specified resource name. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ----------- |
| path | string | Yes | Path of the raw file.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| ------------------------- | ------------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.|
**Error codes**
......@@ -1947,41 +2079,42 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001005 | The resource not found by path. |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
**Example**
```ts
try {
this.context.resourceManager.closeRawFd("test.xml", (error, value) => {
if (error != null) {
console.log("error is " + error);
}
this.context.resourceManager.getMediaByName("test").then(value => {
let media = value;
}).catch(error => {
console.log("getMediaByName promise error is " + error);
});
} catch (error) {
console.error(`callback closeRawFd failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`)
}
```
### closeRawFd<sup>9+</sup>
### getMediaByName<sup>10+</sup>
closeRawFd(path: string): Promise&lt;void&gt;
getMediaByName(resName: string, density: number): Promise&lt;Uint8Array&gt;
Closes the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result.
Obtains the content of the media file (with the specified screen density) corresponding to the specified resource name. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----------- |
| path | string | Yes | Path of the raw file.|
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
**Return value**
| Type | Description |
| ------------------- | ---- |
| Promise&lt;void&gt; | Promise that returns no value.|
| ------------------------- | ------------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.|
**Error codes**
......@@ -1989,97 +2122,133 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001005 | If the resource not found by path. |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
**Example**
```ts
try {
this.context.resourceManager.closeRawFd("test.xml").then(value => {
let result = value;
this.context.resourceManager.getMediaByName("test", 120).then(value => {
let media = value;
}).catch(error => {
console.log("closeRawFd promise error is " + error);
console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
console.error(`promise closeRawFd failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### release<sup>7+</sup>
### getMediaContentBase64Sync<sup>10+</sup>
release()
getMediaContentBase64Sync(resId: number, density?: number): string
Releases a created **resourceManager** object.
Obtains the Base64 code of the image (with the default or specified screen density) corresponding to the specified resource ID.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.|
**Return value**
| Type | Description |
| -------- | ----------- |
| string | Base64 code of the image corresponding to the specified resource ID.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
try {
this.context.resourceManager.release();
this.context.resourceManager.getMediaContentBase64Sync($r('app.media.test').id); // Default screen density
} catch (error) {
console.error("release error is " + error);
console.error(`getMediaContentBase64Sync failed, error code: ${error.code}, message: ${error.message}.`);
}
try {
this.context.resourceManager.getMediaContentBase64Sync($r('app.media.test').id, 120); // Specified screen density
} catch (error) {
console.error(`getMediaContentBase64Sync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getStringByName<sup>9+</sup>
### getMediaContentBase64Sync<sup>10+</sup>
getStringByName(resName: string, callback: AsyncCallback&lt;string&gt;): void
getMediaContentBase64Sync(resource: Resource, density?: number): string
Obtains the string corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
Obtains the Base64 code of the image (with the default or specified screen density) corresponding to the specified resource object.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | --------------- |
| resName | string | Yes | Resource name. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
| ----- | ------ | ---- | ----- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.|
**Error codes**
**Return value**
| Type | Description |
| --------------------- | ----------- |
| string | Base64 code of the media file corresponding to the specified resource object.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
};
try {
this.context.resourceManager.getStringByName("test", (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let string = value;
this.context.resourceManager.getMediaContentBase64Sync(resource); // Default screen density
} catch (error) {
console.error(`getMediaContentBase64Sync failed, error code: ${error.code}, message: ${error.message}.`);
}
});
try {
this.context.resourceManager.getMediaContentBase64Sync(resource, 120); // Specified screen density
} catch (error) {
console.error(`callback getStringByName failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getMediaContentBase64Sync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getStringByName<sup>9+</sup>
### getMediaContentBase64<sup>9+</sup>
getStringByName(resName: string): Promise&lt;string&gt;
getMediaContentBase64(resId: number, callback: AsyncCallback&lt;string&gt;): void
Obtains the string corresponding to the specified resource name. This API uses a promise to return the result.
Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| --------------------- | ---------- |
| Promise&lt;string&gt; | Promise used to return the result.|
| -------- | --------------------------- | ---- | ------------------------ |
| resId | number | Yes | Resource ID. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
**Error codes**
......@@ -2087,37 +2256,39 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
try {
this.context.resourceManager.getStringByName("test").then(value => {
let string = value;
}).catch(error => {
console.log("getStringByName promise error is " + error);
this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let media = value;
}
});
} catch (error) {
console.error(`promise getStringByName failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getStringArrayByName<sup>9+</sup>
### getMediaContentBase64<sup>10+</sup>
getStringArrayByName(resName: string, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void
getMediaContentBase64(resId: number, density: number, callback: AsyncCallback&lt;string&gt;): void
Obtains the string array corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
Obtains the Base64 code of an image with the screen density corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------- |
| resName | string | Yes | Resource name. |
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback used to return the result.|
| -------- | --------------------------- | ---- | ------------------------ |
| resId | number | Yes | Resource ID. |
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
**Error codes**
......@@ -2125,44 +2296,43 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
try {
this.context.resourceManager.getStringArrayByName("test", (error, value) => {
this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120, (error, value) => {
if (error != null) {
console.log("error is " + error);
console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
} else {
let strArray = value;
let media = value;
}
});
} catch (error) {
console.error(`callback getStringArrayByName failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getStringArrayByName<sup>9+</sup>
### getMediaContentBase64<sup>9+</sup>
getStringArrayByName(resName: string): Promise&lt;Array&lt;string&gt;&gt;
getMediaContentBase64(resId: number): Promise&lt;string&gt;
Obtains the string array corresponding to the specified resource name. This API uses a promise to return the result.
Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| ---------------------------------- | ------------ |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the result.|
| --------------------- | -------------------- |
| Promise&lt;string&gt; | Promise used to return the result.|
**Error codes**
......@@ -2170,37 +2340,42 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
try {
this.context.resourceManager.getStringArrayByName("test").then(value => {
let strArray = value;
this.context.resourceManager.getMediaContentBase64($r('app.media.test').id).then(value => {
let media = value;
}).catch(error => {
console.log("getStringArrayByName promise error is " + error);
console.log("getMediaContentBase64 promise error is " + error);
});
} catch (error) {
console.error(`promise getStringArrayByName failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaByName<sup>9+</sup>
### getMediaContentBase64<sup>10+</sup>
getMediaByName(resName: string, callback: AsyncCallback&lt;Uint8Array&gt;): void
getMediaContentBase64(resId: number, density: number): Promise&lt;string&gt;
Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
Obtains the Base64 code of an image with the screen density corresponding to the specified resource ID. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ------------------ |
| resName | string | Yes | Resource name. |
| callback | AsyncCallback&lt;Uint8Array&gt; | Yes | Callback used to return the result.|
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
**Return value**
| Type | Description |
| --------------------- | -------------------- |
| Promise&lt;string&gt; | Promise used to return the result.|
**Error codes**
......@@ -2208,39 +2383,38 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
try {
this.context.resourceManager.getMediaByName("test", (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120).then(value => {
let media = value;
}
}).catch(error => {
console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaByName<sup>10+</sup>
### getMediaContentBase64<sup>9+</sup>
getMediaByName(resName: string, density: number, callback: AsyncCallback&lt;Uint8Array&gt;): void
getMediaContentBase64(resource: Resource, callback: AsyncCallback&lt;string&gt;): void
Obtains the content of the media file with the screen density corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
Obtains the Base64 code of the image corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ------------------ |
| resName | string | Yes | Resource name. |
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
| callback | AsyncCallback&lt;Uint8Array&gt; | Yes | Callback used to return the result.|
| -------- | --------------------------- | ---- | ------------------------ |
| resource | [Resource](#resource9) | Yes | Resource object. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
**Error codes**
......@@ -2248,43 +2422,46 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
};
try {
this.context.resourceManager.getMediaByName("test", 120, (error, value) => {
this.context.resourceManager.getMediaContentBase64(resource, (error, value) => {
if (error != null) {
console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
console.log("error is " + error);
} else {
let media = value;
}
});
} catch (error) {
console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaByName<sup>9+</sup>
### getMediaContentBase64<sup>10+</sup>
getMediaByName(resName: string): Promise&lt;Uint8Array&gt;
getMediaContentBase64(resource: Resource, density: number, callback: AsyncCallback&lt;string&gt;): void
Obtains the content of the media file corresponding to the specified resource name. This API uses a promise to return the result.
Obtains the Base64 code of an image with the screen density corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| ------------------------- | ------------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.|
| -------- | --------------------------- | ---- | ------------------------ |
| resource | [Resource](#resource9) | Yes | Resource object. |
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
**Error codes**
......@@ -2292,42 +2469,50 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
};
try {
this.context.resourceManager.getMediaByName("test").then(value => {
this.context.resourceManager.getMediaContentBase64(resource, 120, (error, value) => {
if (error != null) {
console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
} else {
let media = value;
}).catch(error => {
console.log("getMediaByName promise error is " + error);
}
});
} catch (error) {
console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaByName<sup>10+</sup>
### getMediaContentBase64<sup>9+</sup>
getMediaByName(resName: string, density: number): Promise&lt;Uint8Array&gt;
getMediaContentBase64(resource: Resource): Promise&lt;string&gt;
Obtains the content of the media file with the screen density corresponding to the specified resource name. This API uses a promise to return the result.
Obtains the Base64 code of the image corresponding to the specified resource object. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
**Return value**
| Type | Description |
| ------------------------- | ------------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.|
| --------------------- | ------------------------- |
| Promise&lt;string&gt; | Promise used to return the result.|
**Error codes**
......@@ -2335,38 +2520,93 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
};
try {
this.context.resourceManager.getMediaByName("test", 120).then(value => {
this.context.resourceManager.getMediaContentBase64(resource).then(value => {
let media = value;
}).catch(error => {
console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
console.log("getMediaContentBase64 promise error is " + error);
});
} catch (error) {
console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaBase64ByName<sup>9+</sup>
### getMediaContentBase64<sup>10+</sup>
getMediaBase64ByName(resName: string, callback: AsyncCallback&lt;string&gt;): void
getMediaContentBase64(resource: Resource, density: number): Promise&lt;string&gt;
Obtains the Base64 code of the image corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
Obtains the Base64 code of an image with the screen density corresponding to the specified resource object. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------ |
| resName | string | Yes | Resource name. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
**Error codes**
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
**Return value**
| Type | Description |
| --------------------- | ------------------------- |
| Promise&lt;string&gt; | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.test').id
};
try {
this.context.resourceManager.getMediaContentBase64(resource, 120).then(value => {
let media = value;
}).catch(error => {
console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getMediaBase64ByName<sup>9+</sup>
getMediaBase64ByName(resName: string, callback: AsyncCallback&lt;string&gt;): void
Obtains the Base64 code of the image corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------ |
| resName | string | Yes | Resource name. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
......@@ -2515,21 +2755,26 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
}
```
### getPluralStringByName<sup>9+</sup>
### getDrawableDescriptor<sup>10+</sup>
getPluralStringByName(resName: string, num: number, callback: AsyncCallback&lt;string&gt;): void
getDrawableDescriptor(resId: number, density?: number): DrawableDescriptor;
Obtains the plural string corresponding to the specified resource name based on the specified number. This API uses an asynchronous callback to return the result.
Obtains the **DrawableDescriptor** object corresponding to the specified resource ID. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ----------------------------- |
| resName | string | Yes | Resource name. |
| num | number | Yes | Number. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result.|
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.|
**Return value**
| Type | Description |
| ------ | ---------- |
| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.|
**Error codes**
......@@ -2537,46 +2782,45 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
try {
this.context.resourceManager.getPluralStringByName("test", 1, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let str = value;
this.context.resourceManager.getDrawableDescriptor($r('app.media.icon').id);
} catch (error) {
console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`);
}
});
try {
this.context.resourceManager.getDrawableDescriptor($r('app.media.icon').id, 120);
} catch (error) {
console.error(`callback getPluralStringByName failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getPluralStringByName<sup>9+</sup>
### getDrawableDescriptor<sup>10+</sup>
getPluralStringByName(resName: string, num: number): Promise&lt;string&gt;
getDrawableDescriptor(resource: Resource, density?: number): DrawableDescriptor;
Obtains the plural string corresponding to the specified resource name based on the specified number. This API uses a promise to return the result.
Obtains the **DrawableDescriptor** object corresponding to the specified resource object. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
| num | number | Yes | Number. |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.|
**Return value**
| Type | Description |
| --------------------- | ---------------------- |
| Promise&lt;string&gt; | Promise used to return the result.|
| ------- | ----------------- |
| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.|
**Error codes**
......@@ -2584,42 +2828,48 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.icon').id
};
try {
this.context.resourceManager.getPluralStringByName("test", 1).then(value => {
let str = value;
}).catch(error => {
console.log("getPluralStringByName promise error is " + error);
});
this.context.resourceManager.getDrawableDescriptor(resource);
} catch (error) {
console.error(`promise getPluralStringByName failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`);
}
try {
this.context.resourceManager.getDrawableDescriptor(resource, 120);
} catch (error) {
console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getStringSync<sup>9+</sup>
### getDrawableDescriptorByName<sup>10+</sup>
getStringSync(resId: number): string
getDrawableDescriptorByName(resName: string, density?: number): DrawableDescriptor;
Obtains the string corresponding to the specified resource ID. This API returns the result synchronously.
Obtains the **DrawableDescriptor** object corresponding to the specified resource name. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.|
**Return value**
| Type | Description |
| ------ | ----------- |
| string | String corresponding to the specified resource ID.|
| ------ | --------- |
| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.|
**Error codes**
......@@ -2627,24 +2877,28 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
**Example**
```ts
try {
this.context.resourceManager.getStringSync($r('app.string.test').id);
this.context.resourceManager.getDrawableDescriptorByName('icon');
} catch (error) {
console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getDrawableDescriptorByName failed, error code: ${error.code}, message: ${error.message}.`);
}
try {
this.context.resourceManager.getDrawableDescriptorByName('icon', 120);
} catch (error) {
console.error(`getDrawableDescriptorByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getStringSync<sup>10+</sup>
### getBoolean<sup>9+</sup>
getStringSync(resId: number, ...args: Array<string | number>): string
getBoolean(resId: number): boolean
Obtains the string corresponding to the specified resource ID and formats the string based on **args**. This API returns the result synchronously.
Obtains the Boolean result corresponding to the specified resource ID. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -2653,39 +2907,36 @@ Obtains the string corresponding to the specified resource ID and formats the st
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| args | Array<string \| number> | No | Arguments for formatting strings.<br> Supported arguments:<br> -%d, %f, %s, and %%<br> Note: **%%** is used to translate **%**.<br>Example: **%%d** is translated into the **%d** string.|
**Return value**
| Type | Description |
| ------ | ---------------------------- |
| string | Formatted string.|
| ------- | ------------ |
| boolean | Boolean result corresponding to the specified resource ID.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ----------------------------------------------- |
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
| 9001007 | If the resource obtained by resId formatting error. |
**Example**
```ts
try {
this.context.resourceManager.getStringSync($r('app.string.test').id, "format string", 10, 98.78);
this.context.resourceManager.getBoolean($r('app.boolean.boolean_test').id);
} catch (error) {
console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getBoolean failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getBoolean<sup>9+</sup>
### getStringSync<sup>9+</sup>
getStringSync(resource: Resource): string
getBoolean(resource: Resource): boolean
Obtains the string corresponding to the specified resource object. This API returns the result synchronously.
Obtains the Boolean result corresponding to the specified resource object. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -2700,8 +2951,8 @@ Obtains the string corresponding to the specified resource object. This API retu
**Return value**
| Type | Description |
| ------ | ---------------- |
| string | String corresponding to the specified resource object.|
| ------- | ----------------- |
| boolean | Boolean result corresponding to the specified resource object.|
**Error codes**
......@@ -2718,37 +2969,34 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.string.test').id
id: $r('app.boolean.boolean_test').id
};
try {
this.context.resourceManager.getStringSync(resource);
this.context.resourceManager.getBoolean(resource);
} catch (error) {
console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getBoolean failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getStringSync<sup>10+</sup>
### getBooleanByName<sup>9+</sup>
getStringSync(resource: Resource, ...args: Array<string | number>): string
getBooleanByName(resName: string): boolean
Obtains the string corresponding to the specified resource object and formats the string based on **args**. This API returns the result synchronously.
Obtains the Boolean result corresponding to the specified resource name. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| args | Array<string \| number> | No | Arguments for formatting strings.<br> Supported arguments:<br> -%d, %f, %s, and %%<br> Note: **%%** is used to translate **%**.<br>Example: **%%d** is translated into the **%d** string.|
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| ------ | ---------------------------- |
| string | Formatted string.|
| ------- | ----------- |
| boolean | Boolean result corresponding to the specified resource name.|
**Error codes**
......@@ -2756,44 +3004,38 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
| 9001007 | If the resource obtained by resId formatting error. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.string.test').id
};
try {
this.context.resourceManager.getStringSync(resource, "format string", 10, 98.78);
this.context.resourceManager.getBooleanByName("boolean_test");
} catch (error) {
console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getBooleanByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getStringByNameSync<sup>9+</sup>
### getNumber<sup>9+</sup>
getStringByNameSync(resName: string): string
getNumber(resId: number): number
Obtains the string corresponding to the specified resource name. This API returns the result synchronously.
Obtains the integer or float value corresponding to the specified resource ID. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| ------ | ---------- |
| string | String corresponding to the specified resource name.|
| number | Integer or float value corresponding to the specified resource ID. Wherein, the integer value is the original value, and the float value is the actual pixel value. For details, see the sample code.|
**Error codes**
......@@ -2801,39 +3043,46 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getStringByNameSync("test");
this.context.resourceManager.getNumber($r('app.integer.integer_test').id); // integer refers to the original value.
} catch (error) {
console.error(`getStringByNameSync failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getNumber failed, error code: ${error.code}, message: ${error.message}.`);
}
try {
this.context.resourceManager.getNumber($r('app.float.float_test').id); // float refers to the actual pixel value.
} catch (error) {
console.error(`getNumber failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getStringByNameSync<sup>10+</sup>
### getNumber<sup>9+</sup>
getStringByNameSync(resName: string, ...args: Array<string | number>): string
getNumber(resource: Resource): number
Obtains the string corresponding to the specified resource name and formats the string based on **args**. This API returns the result synchronously.
Obtains the integer or float value corresponding to the specified resource object. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
| args | Array<string \| number> | No | Arguments for formatting strings.<br> Supported arguments:<br> -%d, %f, %s, and %%<br> Note: **%%** is used to translate **%**.<br>Example: **%%d** is translated into the **%d** string.|
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
**Return value**
| Type | Description |
| ------ | ---------------------------- |
| string | Formatted string.|
| ------ | --------------- |
| number | Integer or float value corresponding to the specified resource object. Wherein, the integer value is the original value, and the float value is the actual pixel value. For details, see the sample code.|
**Error codes**
......@@ -2841,39 +3090,43 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
| 9001008 | If the resource obtained by resName formatting error. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.integer.integer_test').id
};
try {
this.context.resourceManager.getStringByNameSync("test", "format string", 10, 98.78);
this.context.resourceManager.getNumber(resource);// integer refers to the original value; float refers to the actual pixel value.
} catch (error) {
console.error(`getStringByNameSync failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getNumber failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getBoolean<sup>9+</sup>
### getNumberByName<sup>9+</sup>
getBoolean(resId: number): boolean
getNumberByName(resName: string): number
Obtains the Boolean result corresponding to the specified resource ID. This API returns the result synchronously.
Obtains the integer or float value corresponding to the specified resource name. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| ------- | ------------ |
| boolean | Boolean result corresponding to the specified resource ID.|
| ------ | --------- |
| number | Integer or float value corresponding to the specified resource name.|
**Error codes**
......@@ -2881,39 +3134,44 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getBoolean($r('app.boolean.boolean_test').id);
this.context.resourceManager.getNumberByName("integer_test");
} catch (error) {
console.error(`getBoolean failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getNumberByName failed, error code: ${error.code}, message: ${error.message}.`);
}
try {
this.context.resourceManager.getNumberByName("float_test");
} catch (error) {
console.error(`getNumberByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getBoolean<sup>9+</sup>
getBoolean(resource: Resource): boolean
### getColorSync<sup>10+</sup>
Obtains the Boolean result corresponding to the specified resource object. This API returns the result synchronously.
getColorSync(resId: number) : number;
**System capability**: SystemCapability.Global.ResourceManager
Obtains the color value corresponding to the specified resource ID. This API returns the result synchronously.
**Model restriction**: This API can be used only in the stage model.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| ------- | ----------------- |
| boolean | Boolean result corresponding to the specified resource object.|
| ------ | ----------- |
| number | Color value corresponding to the resource ID (decimal).|
**Error codes**
......@@ -2927,37 +3185,34 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.boolean.boolean_test').id
};
try {
this.context.resourceManager.getBoolean(resource);
this.context.resourceManager.getColorSync($r('app.color.test').id);
} catch (error) {
console.error(`getBoolean failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getColorSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getBooleanByName<sup>9+</sup>
### getColorSync<sup>10+</sup>
getBooleanByName(resName: string): boolean
getColorSync(resource: Resource): number
Obtains the Boolean result corresponding to the specified resource name. This API returns the result synchronously.
Obtains the color value corresponding to the specified resource object. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
**Return value**
| Type | Description |
| ------- | ----------- |
| boolean | Boolean result corresponding to the specified resource name.|
| ------ | ---------------- |
| number | Color value corresponding to the resource object (decimal).|
**Error codes**
......@@ -2965,38 +3220,43 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.color.test').id
};
try {
this.context.resourceManager.getBooleanByName("boolean_test");
this.context.resourceManager.getColorSync(resource);
} catch (error) {
console.error(`getBooleanByName failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getColorSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getNumber<sup>9+</sup>
### getColorByNameSync<sup>10+</sup>
getNumber(resId: number): number
getColorByNameSync(resName: string) : number;
Obtains the integer or float value corresponding to the specified resource ID. This API returns the result synchronously.
Obtains the color value corresponding to the specified resource name. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| ------ | ---------- |
| number | Integer or float value corresponding to the specified resource ID. Wherein, the integer value is the original value, and the float value is the actual pixel value. For details, see the sample code.|
| number | Color value corresponding to the resource name (decimal).|
**Error codes**
......@@ -3004,46 +3264,33 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getNumber($r('app.integer.integer_test').id); // integer refers to the original value.
} catch (error) {
console.error(`getNumber failed, error code: ${error.code}, message: ${error.message}.`);
}
try {
this.context.resourceManager.getNumber($r('app.float.float_test').id); // float refers to the actual pixel value.
this.context.resourceManager.getColorByNameSync("test");
} catch (error) {
console.error(`getNumber failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getColorByNameSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getNumber<sup>9+</sup>
### getColor<sup>10+</sup>
getNumber(resource: Resource): number
getColor(resId: number, callback: AsyncCallback&lt;number&gt;): void;
Obtains the integer or float value corresponding to the specified resource object. This API returns the result synchronously.
Obtains the color value corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
**Return value**
| Type | Description |
| ------ | --------------- |
| number | Integer or float value corresponding to the specified resource object. Wherein, the integer value is the original value, and the float value is the actual pixel value. For details, see the sample code.|
| -------- | --------------------------- | ---- | --------------- |
| resId | number | Yes | Resource ID. |
| callback | AsyncCallback&lt;number&gt; | Yes | Asynchronous callback used to return the result.|
**Error codes**
......@@ -3051,43 +3298,44 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001001 | If the module resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
**Example (stage)**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.integer.integer_test').id
};
try {
this.context.resourceManager.getNumber(resource);// integer refers to the original value; float refers to the actual pixel value.
this.context.resourceManager.getColor($r('app.color.test').id, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let str = value;
}
});
} catch (error) {
console.error(`getNumber failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getColor failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getNumberByName<sup>9+</sup>
### getColor<sup>10+</sup>
getNumberByName(resName: string): number
getColor(resId: number): Promise&lt;number&gt;
Obtains the integer or float value corresponding to the specified resource name. This API returns the result synchronously.
Obtains the color value corresponding to the specified resource ID. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| ------ | --------- |
| number | Integer or float value corresponding to the specified resource name.|
| --------------------- | ----------- |
| Promise&lt;number&gt; | Promise used to return the result.|
**Error codes**
......@@ -3095,45 +3343,39 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getNumberByName("integer_test");
} catch (error) {
console.error(`getNumberByName failed, error code: ${error.code}, message: ${error.message}.`);
}
try {
this.context.resourceManager.getNumberByName("float_test");
this.context.resourceManager.getColor($r('app.color.test').id).then(value => {
let str = value;
}).catch(error => {
console.log("getColor promise error is " + error);
});
} catch (error) {
console.error(`getNumberByName failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getColor failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getDrawableDescriptor<sup>10+</sup>
### getColor<sup>10+</sup>
getDrawableDescriptor(resId: number, density?: number): DrawableDescriptor;
getColor(resource: Resource, callback: AsyncCallback&lt;number&gt;): void;
Obtains the **DrawableDescriptor** object corresponding to the specified resource ID. This API returns the result synchronously.
Obtains the color value corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| [density](#screendensity) | number | No | Screen density. The default value is **0**.|
**Return value**
| Type | Description |
| ------ | ---------- |
| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.|
| -------- | --------------------------- | ---- | --------------- |
| resource | [Resource](#resource9) | Yes | Resource object. |
| callback | AsyncCallback&lt;number&gt; | Yes | Asynchronous callback used to return the result.|
**Error codes**
......@@ -3143,26 +3385,33 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.color.test').id
};
try {
this.context.resourceManager.getDrawableDescriptor($r('app.media.icon').id);
} catch (error) {
console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`);
this.context.resourceManager.getColor(resource, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let str = value;
}
try {
this.context.resourceManager.getDrawableDescriptor($r('app.media.icon').id, 120);
});
} catch (error) {
console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getColor failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getDrawableDescriptor<sup>10+</sup>
### getColor<sup>10+</sup>
getDrawableDescriptor(resource: Resource, density?: number): DrawableDescriptor;
getColor(resource: Resource): Promise&lt;number&gt;;
Obtains the **DrawableDescriptor** object corresponding to the specified resource object. This API returns the result synchronously.
Obtains the color value corresponding to the specified resource object. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -3173,13 +3422,12 @@ Obtains the **DrawableDescriptor** object corresponding to the specified resourc
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| [density](#screendensity) | number | No | Screen density. The default value is **0**.|
**Return value**
| Type | Description |
| ------- | ----------------- |
| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.|
| --------------------- | ---------------- |
| Promise&lt;number&gt; | Promise used to return the result.|
**Error codes**
......@@ -3189,46 +3437,40 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.icon').id
id: $r('app.color.test').id
};
try {
this.context.resourceManager.getDrawableDescriptor(resource);
this.context.resourceManager.getColor(resource).then(value => {
let str = value;
}).catch(error => {
console.log("getColor promise error is " + error);
});
} catch (error) {
console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`);
}
try {
this.context.resourceManager.getDrawableDescriptor(resource, 120);
} catch (error) {
console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getColor failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getDrawableDescriptorByName<sup>10+</sup>
### getColorByName<sup>10+</sup>
getDrawableDescriptorByName(resName: string, density?: number): DrawableDescriptor;
getColorByName(resName: string, callback: AsyncCallback&lt;number&gt;): void
Obtains the **DrawableDescriptor** object corresponding to the specified resource name. This API returns the result synchronously.
Obtains the color value corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
| [density](#screendensity) | number | No | Screen density. The default value is **0**.|
**Return value**
| Type | Description |
| ------ | --------- |
| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.|
| -------- | --------------------------- | ---- | --------------- |
| resName | string | Yes | Resource name. |
| callback | AsyncCallback&lt;number&gt; | Yes | Asynchronous callback used to return the result.|
**Error codes**
......@@ -3238,35 +3480,42 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
this.context.resourceManager.getDrawableDescriptorByName('icon');
} catch (error) {
console.error(`getDrawableDescriptorByName failed, error code: ${error.code}, message: ${error.message}.`);
this.context.resourceManager.getColorByName("test", (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let string = value;
}
try {
this.context.resourceManager.getDrawableDescriptorByName('icon', 120);
});
} catch (error) {
console.error(`getDrawableDescriptorByName failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getColorByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getColor<sup>10+</sup>
### getColorByName<sup>10+</sup>
getColor(resId: number, callback: AsyncCallback&lt;number&gt;): void;
getColorByName(resName: string): Promise&lt;number&gt;
Obtains the color value corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
Obtains the color value corresponding to the specified resource name. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | --------------- |
| resId | number | Yes | Resource ID. |
| callback | AsyncCallback&lt;number&gt; | Yes | Asynchronous callback used to return the result.|
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| --------------------- | ---------- |
| Promise&lt;number&gt; | Promise used to return the result.|
**Error codes**
......@@ -3274,44 +3523,42 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the module resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
**Example (stage)**
**Example**
```ts
try {
this.context.resourceManager.getColor($r('app.color.test').id, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let str = value;
}
this.context.resourceManager.getColorByName("test").then(value => {
let string = value;
}).catch(error => {
console.log("getColorByName promise error is " + error);
});
} catch (error) {
console.error(`callback getColor failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getColorByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getColor<sup>10+</sup>
### getRawFileContentSync<sup>10+</sup>
getColor(resId: number): Promise&lt;number&gt;
getRawFileContentSync(path: string): Uint8Array
Obtains the color value corresponding to the specified resource ID. This API uses a promise to return the result.
Obtains the content of the raw file in the **resources/rawfile** directory. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| -------- | ------------------------------- | ---- | ----------------------- |
| path | string | Yes | Path of the raw file. |
**Return value**
| Type | Description |
| --------------------- | ----------- |
| Promise&lt;number&gt; | Color value corresponding to the resource ID (decimal).|
| --------------------- | ---------- |
| Uint8Array | Content of the raw file.|
**Error codes**
......@@ -3319,39 +3566,31 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
| 9001005 | If the resource not found by path. |
**Example**
```ts
try {
this.context.resourceManager.getColor($r('app.color.test').id).then(value => {
let str = value;
}).catch(error => {
console.log("getColor promise error is " + error);
});
this.context.resourceManager.getRawFileContentSync("test.txt");
} catch (error) {
console.error(`promise getColor failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getRawFileContentSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getColor<sup>10+</sup>
### getRawFileContent<sup>9+</sup>
getColor(resource: Resource, callback: AsyncCallback&lt;number&gt;): void;
getRawFileContent(path: string, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the color value corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
Obtains the content of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | --------------- |
| resource | [Resource](#resource9) | Yes | Resource object. |
| callback | AsyncCallback&lt;number&gt; | Yes | Asynchronous callback used to return the result.|
| -------- | ------------------------------- | ---- | ----------------------- |
| path | string | Yes | Path of the raw file. |
| callback | AsyncCallback&lt;Uint8Array&gt; | Yes | Callback used to return the result.|
**Error codes**
......@@ -3359,51 +3598,42 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
| 9001005 | If the resource not found by path. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.color.test').id
};
try {
this.context.resourceManager.getColor(resource, (error, value) => {
this.context.resourceManager.getRawFileContent("test.xml", (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let str = value;
let rawFile = value;
}
});
} catch (error) {
console.error(`callback getColor failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getColor<sup>10+</sup>
### getRawFileContent<sup>9+</sup>
getColor(resource: Resource): Promise&lt;number&gt;;
getRawFileContent(path: string): Promise&lt;Uint8Array&gt;
Obtains the color value corresponding to the specified resource object. This API uses a promise to return the result.
Obtains the content of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| ---- | ------ | ---- | ----------- |
| path | string | Yes | Path of the raw file.|
**Return value**
| Type | Description |
| --------------------- | ---------------- |
| Promise&lt;number&gt; | Color value corresponding to the resource object (decimal).|
| ------------------------- | ----------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.|
**Error codes**
......@@ -3411,42 +3641,40 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
| 9001005 | If the resource not found by path. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.color.test').id
};
try {
this.context.resourceManager.getColor(resource).then(value => {
let str = value;
this.context.resourceManager.getRawFileContent("test.xml").then(value => {
let rawFile = value;
}).catch(error => {
console.log("getColor promise error is " + error);
console.log("getRawFileContent promise error is " + error);
});
} catch (error) {
console.error(`promise getColor failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getColorByName<sup>10+</sup>
### getRawFileListSync<sup>10+</sup>
getColorByName(resName: string, callback: AsyncCallback&lt;number&gt;): void
getRawFileListSync(path: string): Array\<string\>
Obtains the color value corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
Obtains the list of files in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | --------------- |
| resName | string | Yes | Resource name. |
| callback | AsyncCallback&lt;number&gt; | Yes | Asynchronous callback used to return the result.|
| -------- | ------------------------------- | ---- | ----------------------- |
| path | string | Yes | Path of the **rawfile** folder. |
**Return value**
| Type | Description |
| ------------------------- | ----------- |
| Array\<string\> | List of files in the **resources/rawfile** directory.|
**Error codes**
......@@ -3454,44 +3682,31 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
| 9001005 | If the resource not found by path. |
**Example**
```ts
try {
this.context.resourceManager.getColorByName("test", (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let string = value;
}
});
try { // Passing "" means to obtain the list of files in the root directory of the raw file.
this.context.resourceManager.getRawFileListSync("")
} catch (error) {
console.error(`callback getColorByName failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getRawFileListSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getColorByName<sup>10+</sup>
### getRawFileList<sup>10+</sup>
getColorByName(resName: string): Promise&lt;number&gt;
getRawFileList(path: string, callback: AsyncCallback&lt;Array\<string\>&gt;): void;
Obtains the color value corresponding to the specified resource name. This API uses a promise to return the result.
Obtains the list of files in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| --------------------- | ---------- |
| Promise&lt;number&gt; | Color value corresponding to the resource name (decimal).|
| -------- | ------------------------------- | ---- | ----------------------- |
| path | string | Yes | Path of the **rawfile** folder. |
| callback | AsyncCallback&lt;Array\<string\>&gt; | Yes| Callback used to return the result.|
**Error codes**
......@@ -3499,42 +3714,42 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
| 9001005 | If the resource not found by path. |
**Example**
```ts
try {
this.context.resourceManager.getColorByName("test").then(value => {
let string = value;
}).catch(error => {
console.log("getColorByName promise error is " + error);
try { // Passing "" means to obtain the list of files in the root directory of the raw file.
this.context.resourceManager.getRawFileList("", (error, value) => {
if (error != null) {
console.error(`callback getRawFileList failed, error code: ${error.code}, message: ${error.message}.`);
} else {
let rawFile = value;
}
});
} catch (error) {
console.error(`promise getColorByName failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`callback getRawFileList failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getColorSync<sup>10+</sup>
### getRawFileList<sup>10+</sup>
getColorSync(resId: number) : number;
getRawFileList(path: string): Promise&lt;Array\<string\>&gt;
Obtains the color value corresponding to the specified resource ID. This API returns the result synchronously.
Obtains the list of files in the **resources/rawfile** directory. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| ---- | ------ | ---- | ----------- |
| path | string | Yes | Path of the **rawfile** folder.|
**Return value**
| Type | Description |
| ------ | ----------- |
| number | Color value corresponding to the resource ID (decimal).|
| ------------------------- | ----------- |
| Promise&lt;Array\<string\>&gt; | Promise used to return the result.|
**Error codes**
......@@ -3542,40 +3757,40 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
| 9001005 | If the resource not found by path. |
**Example**
```ts
try {
this.context.resourceManager.getColorSync($r('app.color.test').id);
try { // Passing "" means to obtain the list of files in the root directory of the raw file.
this.context.resourceManager.getRawFileList("").then(value => {
let rawFile = value;
}).catch(error => {
console.error(`promise getRawFileList failed, error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
console.error(`getColorSync failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getRawFileList failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getColorSync<sup>10+</sup>
### getRawFdSync<sup>10+</sup>
getColorSync(resource: Resource): number
getRawFdSync(path: string): RawFileDescriptor
Obtains the color value corresponding to the specified resource object. This API returns the result synchronously.
Obtains the descriptor of the raw file in the **resources/rawfile** directory.
**System capability**: SystemCapability.Global.ResourceManager
**Model restriction**: This API can be used only in the stage model.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| -------- | ---------------------------------------- | ---- | -------------------------------- |
| path | string | Yes | Path of the raw file. |
**Return value**
| Type | Description |
| ------ | ---------------- |
| number | Color value corresponding to the resource object (decimal).|
| ------------------------- | ----------- |
| [RawFileDescriptor](#rawfiledescriptor8) | Descriptor of the raw file.|
**Error codes**
......@@ -3583,43 +3798,76 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
| 9001005 | If the resource not found by path. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.color.test').id
};
try {
this.context.resourceManager.getColorSync(resource);
this.context.resourceManager.getRawFdSync("test.txt");
} catch (error) {
console.error(`getColorSync failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`getRawFdSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getColorByNameSync<sup>10+</sup>
### getRawFd<sup>9+</sup>
getColorByNameSync(resName: string) : number;
getRawFd(path: string, callback: AsyncCallback&lt;RawFileDescriptor&gt;): void
Obtains the color value corresponding to the specified resource name. This API returns the result synchronously.
Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
| -------- | ---------------------------------------- | ---- | -------------------------------- |
| path | string | Yes | Path of the raw file. |
| callback | AsyncCallback&lt;[RawFileDescriptor](#rawfiledescriptor8)&gt; | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001005 | If the resource not found by path. |
**Example**
```ts
try {
this.context.resourceManager.getRawFd("test.xml", (error, value) => {
if (error != null) {
console.log(`callback getRawFd failed error code: ${error.code}, message: ${error.message}.`);
} else {
let fd = value.fd;
let offset = value.offset;
let length = value.length;
}
});
} catch (error) {
console.error(`callback getRawFd failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getRawFd<sup>9+</sup>
getRawFd(path: string): Promise&lt;RawFileDescriptor&gt;
Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----------- |
| path | string | Yes | Path of the raw file.|
**Return value**
| Type | Description |
| ------ | ---------- |
| number | Color value corresponding to the resource name (decimal).|
| ---------------------------------------- | ------------------- |
| Promise&lt;[RawFileDescriptor](#rawfiledescriptor8)&gt; | Promise used to return the result.|
**Error codes**
......@@ -3627,16 +3875,261 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
| 9001005 | If the resource not found by path. |
**Example**
```ts
try {
this.context.resourceManager.getColorByNameSync("test");
this.context.resourceManager.getRawFd("test.xml").then(value => {
let fd = value.fd;
let offset = value.offset;
let length = value.length;
}).catch(error => {
console.log(`promise getRawFd error error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
console.error(`getColorByNameSync failed, error code: ${error.code}, message: ${error.message}.`);
console.error(`promise getRawFd failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### closeRawFdSync<sup>10+</sup>
closeRawFdSync(path: string): void
Closes the descriptor of the raw file in the **resources/rawfile** directory.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ----------- |
| path | string | Yes | Path of the raw file.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001005 | The resource not found by path. |
**Example**
```ts
try {
this.context.resourceManager.closeRawFdSync("test.txt");
} catch (error) {
console.error(`closeRawFd failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### closeRawFd<sup>9+</sup>
closeRawFd(path: string, callback: AsyncCallback&lt;void&gt;): void
Closes the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ----------- |
| path | string | Yes | Path of the raw file.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001005 | The resource not found by path. |
**Example**
```ts
try {
this.context.resourceManager.closeRawFd("test.xml", (error, value) => {
if (error != null) {
console.log("error is " + error);
}
});
} catch (error) {
console.error(`callback closeRawFd failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### closeRawFd<sup>9+</sup>
closeRawFd(path: string): Promise&lt;void&gt;
Closes the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----------- |
| path | string | Yes | Path of the raw file.|
**Return value**
| Type | Description |
| ------------------- | ---- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001005 | If the resource not found by path. |
**Example**
```ts
try {
this.context.resourceManager.closeRawFd("test.xml").then(value => {
let result = value;
}).catch(error => {
console.log("closeRawFd promise error is " + error);
});
} catch (error) {
console.error(`promise closeRawFd failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getConfiguration
getConfiguration(callback: AsyncCallback&lt;Configuration&gt;): void
Obtains the device configuration. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------------------------- |
| callback | AsyncCallback&lt;[Configuration](#configuration)&gt; | Yes | Callback used to return the result.|
**Example**
```ts
try {
this.context.resourceManager.getConfiguration((error, value) => {
if (error != null) {
console.error("getConfiguration callback error is " + error);
} else {
let direction = value.direction;
let locale = value.locale;
}
});
} catch (error) {
console.error("getConfiguration callback error is " + error);
}
```
### getConfiguration
getConfiguration(): Promise&lt;Configuration&gt;
Obtains the device configuration. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Return value**
| Type | Description |
| ---------------------------------------- | ---------------- |
| Promise&lt;[Configuration](#configuration)&gt; | Promise used to return the result.|
**Example**
```ts
try {
this.context.resourceManager.getConfiguration().then(value => {
let direction = value.direction;
let locale = value.locale;
}).catch(error => {
console.error("getConfiguration promise error is " + error);
});
} catch (error) {
console.error("getConfiguration promise error is " + error);
}
```
### getDeviceCapability
getDeviceCapability(callback: AsyncCallback&lt;DeviceCapability&gt;): void
Obtains the device capability. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------- |
| callback | AsyncCallback&lt;[DeviceCapability](#devicecapability)&gt; | Yes | Callback used to return the result.|
**Example**
```ts
try {
this.context.resourceManager.getDeviceCapability((error, value) => {
if (error != null) {
console.error("getDeviceCapability callback error is " + error);
} else {
let screenDensity = value.screenDensity;
let deviceType = value.deviceType;
}
});
} catch (error) {
console.error("getDeviceCapability callback error is " + error);
}
```
### getDeviceCapability
getDeviceCapability(): Promise&lt;DeviceCapability&gt;
Obtains the device capability. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------- |
| Promise&lt;[DeviceCapability](#devicecapability)&gt; | Promise used to return the result.|
**Example**
```ts
try {
this.context.resourceManager.getDeviceCapability().then(value => {
let screenDensity = value.screenDensity;
let deviceType = value.deviceType;
}).catch(error => {
console.error("getDeviceCapability promise error is " + error);
});
} catch (error) {
console.error("getDeviceCapability promise error is " + error);
}
```
### release<sup>7+</sup>
release()
Releases a created **resourceManager** object.
**System capability**: SystemCapability.Global.ResourceManager
**Example**
```ts
try {
this.context.resourceManager.release();
} catch (error) {
console.error("release error is " + error);
}
```
......
......@@ -2732,7 +2732,7 @@ Obtains the MSISDN of the SIM card in the specified slot. This API uses an async
**System API**: This is a system API.
**Required permission**: ohos.permission.GET_TELEPHONY_STATE
**Required permission**: ohos.permission.GET_PHONE_NUMBERS
**System capability**: SystemCapability.Telephony.CoreService
......@@ -2775,7 +2775,7 @@ Obtains the MSISDN of the SIM card in the specified slot. This API uses a promis
**System API**: This is a system API.
**Required permission**: ohos.permission.GET_TELEPHONY_STATE
**Required permission**: ohos.permission.GET_PHONE_NUMBERS
**System capability**: SystemCapability.Telephony.CoreService
......
......@@ -1691,7 +1691,7 @@ listen(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. The server listens to and accepts TCP socket connections established over the socket. Multiple threads are used to process client data concurrently. This API uses an asynchronous callback to return the result.
> **NOTE**
> **NOTE**<br>
> The server uses this API to perform the **bind**, **listen**, and **accept** operations. If the **bind** operation fails, the system randomly allocates a port number.
**Required permissions**: ohos.permission.INTERNET
......@@ -1736,7 +1736,7 @@ listen(address: NetAddress): Promise\<void\>
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. The server listens to and accepts TCP socket connections established over the socket. Multiple threads are used to process client data concurrently. This API uses a promise to return the result.
> **NOTE**
> **NOTE**<br>
> The server uses this API to perform the **bind**, **listen**, and **accept** operations. If the **bind** operation fails, the system randomly allocates a port number.
**Required permissions**: ohos.permission.INTERNET
......
......@@ -63,8 +63,8 @@ This error code is reported if the **write** API is called to perform applicatio
The specified event name does not comply with the following rules:
- The event name contains only digits, lowercase letters, and underscores (\_).
- The event name starts with a lowercase letter and does not end with an underscore (\_).
- An event name contains only digits, letters, and underscores (_).
- An event name starts with a letter or dollar sign ($) and does not end with an underscore (_).
- The event name is not empty and contains a maximum of 48 characters.
**Solution**
......@@ -119,11 +119,11 @@ This error code is reported if the **write** API is called to perform applicatio
**Possible Causes**
The specified event parameter name does not comply with the following rules:
The specified event name does not comply with the following rules:
- The event parameter name contains only digits, lowercase letters, and underscores (\_).
- The event parameter name starts with a lowercase letter and does not end with an underscore (\_).
- The event parameter name is not empty and contains a maximum of 16 characters.
- An event name contains only digits, letters, and underscores (_).
- An event name starts with a letter or dollar sign ($) and does not end with an underscore (_).
- An event parameter name is not empty and contains a maximum of 16 characters.
**Solution**
......@@ -163,7 +163,7 @@ The specified watcher name does not comply with the following rules:
- The watcher name can contain only digits, lowercase letters, and underscores (\_).
- The watcher name starts with a lowercase letter and does not end with an underscore (\_).
- The watcher name is not empty and contains a maximum of 32 characters.
- A watcher name is not empty and contains a maximum of 32 characters.
**Solution**
......
......@@ -4,156 +4,319 @@
## Overview
### Introduction
### Function Introduction
HiSysEvent supports listening for events across processes. You can register a listener to listen for concerned events on a real-time basis. For example, you can enable the battery module to listen for power consumption events for power usage analysis.
HiSysEvent supports listening for events across processes. You can register a listener to listen for concerned events on a real-time basis. For example, you can enable the battery module to subscribe to power consumption events for power usage analysis.
### Constraints
Before subscribing to system events, you need to configure HiSysEvent logging. For details, see [HiSysEvent Logging Configuration](../subsystems/subsys-dfx-hisysevent-logging-config.md).
Before listening for system events, you need to configure HiSysEvent logging. For details, see [HiSysEvent Logging Configuration](../subsystems/subsys-dfx-hisysevent-logging-config.md).
## Development Guidelines
## How to Develop
### Available APIs
**Table 1** Description of HiSysEventListener APIs
#### C++ APIs
| API| Description|
| -------- | -------- |
| int32_t HiSysEventManager::AddListener(std::shared_ptr&lt;HiSysEventListener&gt; listener, std::vector&lt;ListenerRule&gt;&amp; rules) | Registers a listener for system events. You can listen for certain events by specifying rules.<br>Input arguments:<br>- **listener**: callback object for system events.<br>- **rules**: rules for event listening.<br>Return value:<br>- **0**: Registration is successful.<br>- A negative value: Registration has failed.|
| int32_t HiSysEventManager::RemoveListener(std::shared_ptr&lt;HiSysEventListener&gt; listener) | Removes the listener for system events.<br>Input arguments:<br>- **listener**: callback object for system events.<br>Return value:<br>- **0**: Canceling registration is successful.<br>- A negative value: Canceling registration has failed. |
HiSysEvent is implemented using the APIs provided by the **HiSysEventManager** class. For details, see the [API Header Files](/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent_manager/include/).
**Table 2** Description of ListenerRule
> **NOTE**
>
> For details about the **RuleType** argument in the constructor of **ListenerRule**, see Table 4 in [HiSysEvent Query](subsys-dfx-hisysevent-query.md).
**Table 1** Description of C++ HiSysEventManager APIs
| API| Description|
| Name| Description|
| -------- | -------- |
| ListenerRule(const std::string&amp; tag, RuleType ruleType = RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event tag.<br>Input arguments:<br>- **tag**: event tag for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, lowercase letters, and digits.<br>- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.|
| ListenerRule(const std::string&amp; domain, const std::string&amp; eventName, RuleType ruleType = RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event domain and event name.<br>Input arguments:<br>- **domain**: event domain for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, digits, and underscores.<br>- **eventName**: event name for the **ListenerRule** object. The value is a string of 1 to 32 characters, including uppercase letters, digits, and underscores.<br>- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.|
| ListenerRule(const std::string&amp; domain, const std::string&amp; eventName, const std::string&amp; tag, RuleType ruleType = RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event domain, event name, and event tag.<br>Input arguments:<br>- **tag**: event tag for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, lowercase letters, and digits.<br>- **domain**: event domain for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, digits, and underscores.<br>- **eventName**: event name for the **ListenerRule** object. The value is a string of 1 to 32 characters, including uppercase letters, digits, and underscores.<br>- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.|
| int32_t&nbsp;HiSysEventManager::AddListener(std::shared_ptr&lt;HiSysEventListener&gt;&nbsp;listener,<br>&nbsp;std::vector&lt;ListenerRule&gt;&amp;&nbsp;rules) | Adds a listener to listen for system events based on the specified rules.<br>Input arguments:<br>- **listener**: listener for system events.<br>- **rules**: event listening rules.<br>Return value:<br>- **0**: The listener is added successfully.<br>- A negative value: The listener fails to be added.|
| int32_t&nbsp;HiSysEventManager::RemoveListener(std::shared_ptr&lt;HiSysEventListener&gt;&nbsp;listener) | Removes the listener for system events.<br>Input arguments:<br>- **listener**: listener for system events.<br>Return value:<br>- **0**: The listener is removed successfully.<br>- A negative value: The listener fails to be removed. |
**Table 3** Description of RuleType
**Table 2** Description of ListenerRule
| Value| Description|
| Name| Description|
| -------- | -------- |
| WHOLE_WORD | Whole word matching|
| PREFIX | Prefix matching|
| REGULAR | Regular expression matching|
| ListenerRule(const&nbsp;std::string&amp;&nbsp;tag,<br>&nbsp;RuleType&nbsp;ruleType&nbsp;=&nbsp;RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event tag.<br>Input arguments:<br>- **tag**: event tag for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, lowercase letters, and digits.<br>- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.|
| ListenerRule(const&nbsp;std::string&amp;&nbsp;domain,<br>&nbsp;const&nbsp;std::string&amp;&nbsp;eventName,<br>&nbsp;RuleType&nbsp;ruleType&nbsp;=&nbsp;RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event domain and event name.<br>Input arguments:<br>- **domain**: event domain for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, digits, and underscores.<br>- **eventName**: event name for the **ListenerRule** object. The value is a string of 1 to 32 characters, including uppercase letters, digits, and underscores.<br>- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.|
| ListenerRule(const&nbsp;std::string&amp;&nbsp;domain,<br>&nbsp;const&nbsp;std::string&amp;&nbsp;eventName,<br>&nbsp;const&nbsp;std::string&amp;&nbsp;tag,<br>&nbsp;RuleType&nbsp;ruleType&nbsp;=&nbsp;RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event domain, event name, and event tag.<br>Input arguments:<br>- **tag**: event tag for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, lowercase letters, and digits.<br>- **domain**: event domain for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, digits, and underscores.<br>- **eventName**: event name for the **ListenerRule** object. The value is a string of 1 to 32 characters, including uppercase letters, digits, and underscores.<br>- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.|
**Table 4** Description of HiSysEventListener
**Table 3** Description of HiSysEventListener
| API| Description|
| Name| Description|
| -------- | -------- |
| void HiSysEventListener::OnEvent(std::shared_ptr&lt;HiSysEventRecord&gt; sysEvent) | Callback object for system events.<br>Input arguments:<br>- **sysEvent**: real-time system events.<br>Return value:<br>None.|
| void HiSysEventListener::OnServiceDied() | Callback object for service exceptions.<br>Input arguments:<br>None.<br>Return value:<br>None.|
| void&nbsp;HiSysEventListener::OnEvent(std::shared_ptr&lt;HiSysEventRecord&gt;&nbsp;sysEvent) | Callback object for system events.<br>Input arguments:<br>- **sysEvent**: real-time system event.<br>Return value:<br>None.|
| void&nbsp;HiSysEventListener::OnServiceDied() | Callback object for service exceptions.<br>Input arguments:<br>None.<br>Return value:<br>None.|
**Table 5** Description of HiSysEventRecord
| API| Description|
**Table 4** Description of HiSysEventRecord
| Name| Description|
| -------- | -------- |
|std::string HiSysEventRecord::AsJson()|Obtains the content of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Content of the system event.|
|std::string HiSysEventRecord::GetDomain()|Obtains the domain name of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Domain name of the system event.|
|std::string HiSysEventRecord::GetEventName()|Obtains the name of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Name of the system event.|
|HiSysEvent::EventType HiSysEventRecord::GetEventType()|Obtains the type of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Type of the system event.|
|std::string HiSysEventRecord::GetLevel()|Obtains the level of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Level of the system event.|
|std::string HiSysEventRecord::GetTag()|Obtains the tag of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Tag of the system event.|
|std::string HiSysEventRecord::GetTimeZone()|Obtains the time zone of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Time zone, in the format of **+0800**.|
|int HiSysEventRecord::GetTraceFlag()|Obtains the distributed call chain tracing flag of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Distributed call chain tracing flag.|
|int64_t HiSysEventRecord::GetPid()|Obtains the ID of the process that flushes a system event to the disk.<br>Input arguments:<br>None.<br>Return value:<br>Process ID.|
|int64_t HiSysEventRecord::GetTid()|Obtains the thread ID of the process that flushes a system event to the disk.<br>Input arguments:<br>None.<br>Return value:<br>Thread ID.|
|int64_t HiSysEventRecord::GetUid()|Obtains the user ID of the process that flushes a system event to the disk.<br>Input arguments:<br>None.<br>Return value:<br>User ID.|
|uint64_t HiSysEventRecord::GetPspanId()|Obtains the parent span ID of the distributed call chain tracing task.<br>Input arguments:<br>None.<br>Return value:<br>Parent span ID of the distributed call chain tracing task.|
|uint64_t HiSysEventRecord::GetSpandId()|Obtains the span ID of the distributed call chain tracing task.<br>Input arguments:<br>None.<br>Return value:<br>Span ID of the distributed call chain tracing task.|
|uint64_t HiSysEventRecord::GetTime()|Obtains the timestamp of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Timestamp of the system event.|
|uint64_t HiSysEventRecord::GetTraceId()|Obtains the ID of the distributed call chain tracing task.<br>Input arguments:<br>None.<br>Return value:<br>ID of the distributed call chain tracing task.|
|void HiSysEventRecord::GetParamNames(std::vector&lt;std::string&gt;&amp; params)|Obtains all key names of a system event.<br>Input arguments:<br>- **params**: key name array reference.<br>Return value:<br>None.|
|int HiSysEventRecord::GetParamValue(const std::string&amp; param, int64_t&amp; value)|Parses the value of the **param** key in a system event into an int64\_t value.<br>Input arguments:<br>- **param**: key name.<br>- **value**: int64\_t reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int HiSysEventRecord::GetParamValue(const std::string&amp; param, uint64_t&amp; value)|Parses the value of the **param** key in a system event into a uint64\_t value.<br>Input arguments:<br>- **param**: key name.<br>- **value**: uint64\_t reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int HiSysEventRecord::GetParamValue(const std::string&amp; param, double&amp; value)|Parses the value of the **param** key in a system event into a double value.<br>Input arguments:<br>- **param**: key name.<br>- **value**: double reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int HiSysEventRecord::GetParamValue(const std::string&amp; param, std::string&amp; value)|Parses the value of the **param** key in a system event into a string value.<br>Input arguments:<br>- **param**: key name.<br>- **value**: std::string reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int HiSysEventRecord::GetParamValue(const std::string&amp; param, std::vector&lt;int64_t&gt;&amp; value)|Parses the value of the **param** key in a system event into an int64\_t array.<br>Input arguments:<br>- **param**: key name.<br>- **value**: int64\_t array reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int HiSysEventRecord::GetParamValue(const std::string&amp; param, std::vector&lt;uint64_t&gt;&amp; value)|Parses the value of the **param** key in a system event into a uint64\_t array.<br>Input arguments:<br>- **param**: key name.<br>- **value**: uint64\_t array reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int HiSysEventRecord::GetParamValue(const std::string&amp; param, std::vector&lt;double&gt;&amp; value)|Parses the value of the **param** key in a system event into a double array.<br>Input arguments:<br>- **param**: key name.<br>- **value**: double array reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int HiSysEventRecord::GetParamValue(const std::string&amp; param, std::vector&lt;std::string&gt;&amp; value)|Parses the value of the **param** key in a system event into a string array.<br>Input arguments:<br>- **param**: key name.<br>- **value**: std::string array reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|std::string&nbsp;HiSysEventRecord::AsJson()|Obtains the content of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Content of the system event.|
|std::string&nbsp;HiSysEventRecord::GetDomain()|Obtains the domain name of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Domain name of the system event.|
|std::string&nbsp;HiSysEventRecord::GetEventName()|Obtains the name of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Name of the system event.|
|HiSysEvent::EventType&nbsp;HiSysEventRecord::GetEventType()|Obtains the type of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Type of the system event.|
|std::string&nbsp;HiSysEventRecord::GetLevel()|Obtains the level of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Level of the system event.|
|std::string&nbsp;HiSysEventRecord::GetTag()|Obtains the tag of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Tag of the system event.|
|std::string&nbsp;HiSysEventRecord::GetTimeZone()|Obtains the time zone of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Time zone, in the format of **+0800**.|
|int&nbsp;HiSysEventRecord::GetTraceFlag()|Obtains the distributed call chain tracing flag of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Distributed call chain tracing flag.|
|int64_t&nbsp;HiSysEventRecord::GetPid()|Obtains the ID of the process that flushes a system event to the disk.<br>Input arguments:<br>None.<br>Return value:<br>Process ID.|
|int64_t&nbsp;HiSysEventRecord::GetTid()|Obtains the thread ID of the process that flushes a system event to the disk.<br>Input arguments:<br>None.<br>Return value:<br>Thread ID.|
|int64_t&nbsp;HiSysEventRecord::GetUid()|Obtains the user ID of the process that flushes a system event to the disk.<br>Input arguments:<br>None.<br>Return value:<br>User ID.|
|uint64_t&nbsp;HiSysEventRecord::GetPspanId()|Obtains the parent span ID of the distributed call chain tracing task.<br>Input arguments:<br>None.<br>Return value:<br>Parent span ID of the distributed call chain tracing task.|
|uint64_t&nbsp;HiSysEventRecord::GetSpandId()|Obtains the span ID of the distributed call chain tracing task.<br>Input arguments:<br>None.<br>Return value:<br>Span ID of the distributed call chain tracing task.|
|uint64_t&nbsp;HiSysEventRecord::GetTime()|Obtains the timestamp of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Timestamp.|
|uint64_t&nbsp;HiSysEventRecord::GetTraceId()|Obtains the ID of the distributed call chain tracing task.<br>Input arguments:<br>None.<br>Return value:<br>ID of the distributed call chain tracing task.|
|void&nbsp;HiSysEventRecord::GetParamNames(std::vector&lt;std::string&gt;&amp;&nbsp;params)|Obtains all key names of a system event.<br>Input arguments:<br>- **params**: key name array reference.<br>Return value:<br>None.|
|int&nbsp;HiSysEventRecord::GetParamValue(const std::string&amp;&nbsp;param,&nbsp;int64_t&amp;&nbsp;value)|Parses the value of the **param** key in a system event into an int64\_t value.<br>Input arguments:<br>- **param**: key name.<br>- **value**: int64\_t reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int&nbsp;HiSysEventRecord::GetParamValue(const std::string&amp;&nbsp;param,&nbsp;uint64_t&amp;&nbsp;value)|Parses the value of the **param** key in a system event into a uint64\_t value.<br>Input arguments:<br>- **param**: key name.<br>- **value**: uint64\_t reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int&nbsp;HiSysEventRecord::GetParamValue(const std::string&amp;&nbsp;param,&nbsp;double&amp;&nbsp;value)|Parses the value of the **param** key in a system event into a double value.<br>Input arguments:<br>- **param**: key name.<br>- **value**: double reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int&nbsp;HiSysEventRecord::GetParamValue(const std::string&amp;&nbsp;param,&nbsp;std::string&amp; value)|Parses the value of the **param** key in a system event into a string value.<br>Input arguments:<br>- **param**: key name.<br>- **value**: std::string reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int&nbsp;HiSysEventRecord::GetParamValue(const std::string&amp;&nbsp;param,&nbsp;std::vector&lt;int64_t&gt;&amp;&nbsp;value)|Parses the value of the **param** key in a system event into an int64\_t array.<br>Input arguments:<br>- **param**: key name.<br>- **value**: int64\_t array reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int&nbsp;HiSysEventRecord::GetParamValue(const std::string&amp;&nbsp;param,&nbsp;std::vector&lt;uint64_t&gt;&amp;&nbsp;value)|Parses the value of the **param** key in a system event into a uint64\_t array.<br>Input arguments:<br>- **param**: key name.<br>- **value**: uint64\_t array reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int&nbsp;HiSysEventRecord::GetParamValue(const std::string&amp;&nbsp;param,&nbsp;std::vector&lt;double&gt;&amp;&nbsp;value)|Parses the value of the **param** key in a system event into a double array.<br>Input arguments:<br>- **param**: key name.<br>- **value**: double array reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int&nbsp;HiSysEventRecord::GetParamValue(const std::string&amp;&nbsp;param,&nbsp;std::vector&lt;std::string&gt;&amp;&nbsp;value)|Parses the value of the **param** key in a system event into a string array.<br>Input arguments:<br>- **param**: key name.<br>- **value**: std::string array reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
#### C APIs
HiSysEvent listening is implemented using the API provided in the following table. For details, see the [API Header Files](/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent_manager/include/).
> **NOTE**
>
> For details about the **HiSysEventRecord** argument in the **OnEvent** callback of **HiSysEventWatcher**, see Table 11 and Table 12 in [HiSysEvent Query](subsys-dfx-hisysevent-query.md).
**Table 5** Description of C HiSysEventManager APIs
| Name | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| int OH_HiSysEvent_Add_Watcher(HiSysEventWatcher* watcher,<br>HiSysEventWatchRule rules[],<br>size_t ruleSize); | Adds a listener to listen for system events based on the specified rules.<br>Input arguments:<br>- **watcher**: watcher for system events.<br>- **rules**: array of event listening rules.<br>- **ruleSize**: length of the array of event listening rules.<br>Return value:<br>- **0**: The listener is added successfully.<br>- A negative value: The listener fails to be added.|
| int OH_HiSysEvent_Remove_Watcher(HiSysEventWatcher* watcher); | Remove the watcher for system events.<br>Input arguments:<br>- **watcher**: watcher for system events.<br>Return value:<br>- **0**: The watcher is removed successfully.<br>- A negative value: The watcher fails to be removed. |
**Table 6** Description of the HiSysEventWatcher structure
| Field | Type | Description |
| ------------- | -------------------------------------------------- | ------------------------------------------------------------ |
| OnEvent | void (*)(HiSysEventRecord record); | Callback object for system events.<br>Input arguments:<br>- **record**: real-time system event.<br>Return value:<br>None.|
| OnServiceDied | void (*)(); | Callback object for service exceptions.<br>Input arguments:<br>None.<br>Return value:<br>None. |
**Table 7** Description of the HiSysEventWatchRule structure
| Field | Type | Description |
| ------------- | --------- | ---------------------------------- |
| domain | char[] | Event domain. |
| name | char[] | Event name. |
| tag | char[] | Event tag. |
| ruleType | int | Event matching rule. For details about the values, see Table 4 in [HiSysEvent Query](subsys-dfx-hisysevent-query.md). |
| eventType | int | Event type. For details about the values, see Table 3 in [HiSysEvent Query](subsys-dfx-hisysevent-query.md). The value **0** indicates all event types. |
### How to Develop
#### C++ HiSysEvent Listening
1. Import the corresponding header file.
```c++
#include "hisysevent_manager.h"
```
2. Implement the callback API for the service domain.
## How to Develop
```c++
class TestListener : public OHOS::HiviewDFX::HiSysEventListener {
public:
void OnEvent(std::shared_ptr<HiSysEventRecord> record)
{
if (record == nullptr) {
return;
}
std::cout << record->AsJson() << std::endl;
}
void OnServiceDied()
{
std::cout << std::string("service disconnect, exit") << std::endl;
exit(0);
}
};
```
3. Call the listening API while passing in parameters such as **listener** and **rules**. When the service ends, disable event listening.
### **C++**
```c++
auto testListener = std::make_shared<TestListener>();
// Add a ListenerRule object based on the event tag, with RuleType left unspecified (in this case, ruleType is defaulted to WHOLE_WORD).
ListenerRule tagRule("dfx");
// Add a ListenerRule object based on the event tag, with RuleType set as REGULAR.
ListenerRule regRule("dfx.*", RuleType::REGULAR);
// Add a ListenerRule object based on the event domain and event name, with RuleType set as PREFIX.
ListenerRule domainNameRule("HIVIEWDFX", "APP_USAGE", RuleType::PREFIX);
std::vector<ListenerRule> sysRules;
sysRules.push_back(tagRule);
sysRules.push_back(regRule);
sysRules.push_back(domainNameRule);
// Start event listening.
auto ret = HiSysEventManager::AddEventListener(testListener, sysRules);
// Remove the listener when the service ends.
if (ret == 0) {
HiSysEventManager::RemoveListener(testListener);
}
```
The following provides an example of how to use C++ APIs of **HiSysEvent**.
#### C HiSysEvent Listening
1. Develop the source code.
Import the **DemoListener.h** header file, which contains the **DemoListener** class for implementing the custom event callback.
1. Import the corresponding header file.
```c++
#include "hisysevent_manager_c.h"
```
#ifndef DEMO_LISTENER_H
#define DEMO_LISTENER_H
#include "hisysevent_listener.h"
#include <string>
2. Implement the callback API for the service domain.
class DemoListener : public OHOS::HiviewDFX::HiSysEventListener {
public:
explicit DemoListener() : HiSysEventListener() {}
virtual ~DemoListener() {}
```c++
void OnEventTest(HiSysEventRecord record)
{
printf("OnEventTest: event=%s", record.jsonStr);
}
public:
void OnEvent(std::shared_ptr<HiSysEventRecord> sysEvent);
void OnServiceDied();
};
void OnServiceDiedTest()
{
printf("OnServiceDied");
}
```
#endif // DEMO_LISTENER_H
3. Call the listening API while passing in parameters such as **watcher** and **rules**. When the service ends, disable event listening.
```c++
HiSysEventWatcher watcher;
watcher.OnEvent = OnEventTest;
watcher.OnServiceDied = OnServiceDiedTest;
// Add a HiSysEventWatchRule object based on the event tag, with RuleType left unspecified (in this case, ruleType is defaulted to WHOLE_WORD).
constexpr char DFX_TAG[] = "dfx";
HiSysEventWatchRule tagRule;
(void)strcpy_s(tagRule.tag, strlen(DFX_TAG) + 1, DFX_TAG);
tagRule.ruleType = 1;
tagRule.eventType = 0;
// Add a HiSysEventWatchRule object based on the event tag, with RuleType set as REGULAR.
constexpr char DFX_PATTERN_TAG[] = "dfx.*";
HiSysEventWatchRule regRule;
(void)strcpy_s(regRule.tag, strlen(DFX_PATTERN_TAG) + 1, DFX_PATTERN_TAG);
regRule.ruleType = 3;
regRule.eventType = 0;
// Add a HiSysEventWatchRule object based on the event domain and event name, with RuleType set as PREFIX.
constexpr char DOMAIN[] = "HIVIEWDFX";
constexpr char NAME[] = "APP_USAGE";
HiSysEventWatchRule domainNameRule;
(void)strcpy_s(domainNameRule.domain, strlen(DOMAIN) + 1, DOMAIN);
(void)strcpy_s(domainNameRule.name, strlen(NAME) + 1, NAME);
domainNameRule.ruleType = 2;
domainNameRule.eventType = 0;
// Start event listening.
HiSysEventWatchRule rules[] = {tagRule, regRule, domainNameRule};
int ret = OH_HiSysEvent_Add_Watcher(&watcher, rules, sizeof(rules) / sizeof(HiSysEventWatchRule));
// Remove the watcher when the service ends.
if (ret == 0) {
ret = OH_HiSysEvent_Remove_Watcher(&watcher);
}
```
Create the **DemoListener.cpp** file, and add the implementation logic of the custom event callback API in the **DemoListener** class.
### Development Examples
#### C++ HiSysEvent Listening
Suppose you want to enable listening for all events whose domain is **HIVIEWDFX** and name is **PLUGIN_LOAD**. The sample code is as follows:
1. Add the **libhisysevent** and **libhisyseventmanager** dependencies of the **hisysevent** component to the **BUILD.gn** file of the service module.
```c++
external_deps = [
"hisysevent:libhisysevent",
"hisysevent:libhisyseventmanager",
]
```
#include "demo_listener.h"
2. Call the listening API in the **TestEventListening()** function. When the service ends, disable event listening.
```c++
#include <iostream>
void DemoListener::OnEvent(std::shared_ptr<HiSysEventRecord> sysEvent)
#include "hisysevent_manager.h"
using namespace OHOS::HiviewDFX;
class TestListener : public HiSysEventQueryCallback {
public:
void OnEvent(std::shared_ptr<HiSysEventRecord> record)
{
if (sysEvent == nullptr) {
if (record == nullptr) {
return;
}
std::cout << sysEvent.AsJson() << std::endl;
std::cout << record->AsJson() << std::endl;
}
void DemoListener::OnServiceDied()
void OnServiceDied()
{
std::cout << std::string("service disconnect, exit") << std::endl;
exit(0);
}
```
Call the **AddEventListener** API of the **HiSysEventManager** class to add a listener for system events.
};
```
auto demoListener = std::make_shared<DemoListener>();
// Add a ListenerRule object based on the event tag, with RuleType left unspecified (in this case, ruleType is defaulted to WHOLE_WORD).
ListenerRule tagRule("dfx");
// Add a ListenerRule object based on the event tag, with RuleType set as REGULAR.
ListenerRule regRule("dfx.*", RuleType::REGULAR);
// Add a ListenerRule object based on the event domain and event name, with RuleType set as PREFIX.
ListenerRule domainNameRule("HIVIEWDFX", "APP_USAGE", RuleType::PREFIX);
void TestEventListening()
{
auto testListener = std::make_shared<TestListener>();
ListenerRule domainNameRule("HIVIEWDFX", "PLUGIN_LOAD", RuleType::WHOLE_WORD);
std::vector<ListenerRule> sysRules;
sysRules.push_back(tagRule);
sysRules.push_back(regRule);
sysRules.push_back(domainNameRule);
HiSysEventManager::AddEventListener(demoListener, sysRules);
auto ret = HiSysEventManager::AddEventListener(testListener, sysRules);
if (ret == 0) {
HiSysEventManager::RemoveListener(testListener);
}
}
```
2. Configure the **BUILD.gn** file.
In the **BUILD.gn** file, add the **libhisysevent** and **libhisyseventmanager** libraries that depend on the **hisysevent** component.
#### C HiSysEvent Listening
Suppose you want to enable listening for all events whose domain is **HIVIEWDFX** and name is **PLUGIN_LOAD**. The sample code is as follows:
1. Add the **libhisysevent** and **libhisyseventmanager** dependencies of the **hisysevent** component to the **BUILD.gn** file of the service module.
```c++
external_deps = [ "hisysevent:libhisyseventmanager" ]
// for strcpy_s
deps = [ "//third_party/bounds_checking_function:libsec_shared" ]
```
external_deps = [
"hisysevent:libhisysevent",
"hisysevent:libhisyseventmanager",
]
2. Call the listening API in the **TestEventListening()** function. When the service ends, disable event listening.
```c++
#include <securec.h>
#include "hisysevent_manager_c.h"
void OnEventTest(HiSysEventRecord record)
{
printf("OnEventTest: event=%s", record.jsonStr);
}
void OnServiceDiedTest()
{
printf("OnServiceDied");
}
void TestEventListening()
{
HiSysEventWatcher watcher;
watcher.OnEvent = OnEventTest;
watcher.OnServiceDied = OnServiceDiedTest;
constexpr char DOMAIN[] = "HIVIEWDFX";
constexpr char NAME[] = "PLUGIN_LOAD";
HiSysEventWatchRule domainNameRule;
(void)strcpy_s(domainNameRule.domain, strlen(DOMAIN) + 1, DOMAIN);
(void)strcpy_s(domainNameRule.name, strlen(NAME) + 1, NAME);
domainNameRule.ruleType = 1;
domainNameRule.eventType = 0;
HiSysEventWatchRule rules[] = {domainNameRule};
int ret = OH_HiSysEvent_Add_Watcher(&watcher, rules, sizeof(rules) / sizeof(HiSysEventWatchRule));
if (ret == 0) {
ret = OH_HiSysEvent_Remove_Watcher(&watcher);
}
}
```
......@@ -33,10 +33,11 @@ Constraints on the event domain, event name, and parameter
| Field| Description|
| -------- | -------- |
| type | Event type. This field is mandatory.<br>Value:<br>- FAULT: fault<br>- STATISTIC: statistics<br>- SECURITY: security<br>- BEHAVIOR: user behavior|
| type | Event type. This field is mandatory.<br>Value:<br>- **FAULT**: fault<br>- STATISTIC: statistics<br>- **SECURITY**: security<br>- **BEHAVIOR**: behavior|
| level | Event level. This field is mandatory.<br>Value:<br>- CRITICAL: critical<br>- MINOR: minor|
| tag | Event tag. This field is mandatory.<br>Rule:<br>- You can define a maximum of five tags, separated with a space.<br>- A single tag can contain a maximum of 16 characters, including a to z, A to Z, and 0 to 9.|
| desc | Event name. This field is mandatory.<br>Rule:<br>The description contains 3 to 128 characters, including a to z, A to Z, 0 to 9, and underscores (_).|
| desc | Event name. This field is mandatory.<br>Rule:<br>- A string of 3 to 128 characters.|
| preserve | Whether events need to be logged in the event file. This field is optional. The default value is **true**.<br>Value:<br>- **true**: Events need to be logged in the event file.<br>- **false**: Events do not need to be logged in the event file.|
**Table 2** Description of custom parameters
......@@ -44,7 +45,7 @@ Constraints on the event domain, event name, and parameter
| -------- | -------- |
| type | Parameter type. This field is mandatory.<br>Value:<br>- BOOL<br>- INT8<br>- UINT8<br>- INT16<br>- UINT16<br>- INT32<br>- UINT32<br>- INT64<br>- UINT64<br>- FLOAT<br>- DOUBLE<br>- STRING |
| arrsize | Length of the parameter of the array type. This field is optional.<br>Value:<br>1-100|
| desc | Parameter description. This field is mandatory.<br>Rule:<br>The description contains 3 to 128 characters, including a to z, A to Z, 0 to 9, and underscores (_).|
| desc | Parameter description. This field is mandatory.<br>Rule:<br>- A string of 3 to 128 characters.|
## How to Develop
......
......@@ -10,99 +10,119 @@ HiSysEvent allows you to query system events by specifying search criteria. For
### Available APIs
#### C++ Event Query API
#### C++ APIs
HiSysEvent query is implemented using the API provided by the **HiSysEventManager** class. For details, see the [API Header Files](/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent_manager/include/).
> **NOTE**
>
> For details about **HiSysEventRecord** in the **OnQuery()** API of **HiSysEventQueryCallback**, see Table 5 in [HiSysEvent Listening](subsys-dfx-hisysevent-listening.md).
> For details about **HiSysEventRecord** in the **OnQuery()** API of **HiSysEventQueryCallback**, see Table 4 in [HiSysEvent Listening](subsys-dfx-hisysevent-listening.md).
**Table 1** Description of the HiSysEvent query API
**Table 1** Description of the C++ HiSysEvent query API
| API| Description|
| Name| Description|
| -------- | -------- |
| int32_t Query(struct&nbsp;QueryArg&amp;&nbsp;arg,<br>std::vector&lt;QueryRule&gt;&amp;&nbsp;rules,<br>std::shared_ptr&lt;HiSysEventQueryCallback&gt;&nbsp;callback) | Queries system events by search criteria such as the time segment, event domain, and event name.<br>Input arguments:<br>- **arg**: event query parameter.<br>- **rules**: rules for event filtering.<br>- **callback**: callback object for event query.<br>Return value:<br>- **0**: Query is successful.<br>- A negative value: Query has failed.|
| int32_t Query(struct&nbsp;QueryArg&amp;&nbsp;arg,<br>std::vector&lt;QueryRule&gt;&amp;&nbsp;rules,<br>std::shared_ptr&lt;HiSysEventQueryCallback&gt;&nbsp;callback) | Queries system events by search criteria such as the time segment, event domain, and event name.<br>Input arguments:<br>- **arg**: event query parameter.<br>- **rules**: event filtering rules.<br>- **callback**: callback object for event query.<br>Return value:<br>- **0**: Query is successful.<br>- A negative value: Query has failed.|
**Table 2** Description of QueryArg objects
| Attribute| Type| Description|
| Field| Type| Description|
| -------- | -------- | -------- |
| beginTime | long long | Start time for query. The value is a Unix timestamp, in milliseconds.|
| endTime | long long | End time for query. The value is a Unix timestamp, in milliseconds.|
| maxEvents | int | Maximum number of returned events.|
**Table 3** Description of QueryRule objects
**Table 3** Description of EventType enums
| API| Description|
| Event Type| Value| Description|
| ------------ | ---- | ------------------ |
| FAULT | 1 | Fault type. |
| STATISTIC | 2 | Statistical type. |
| SECURITY | 3 | Security type. |
| BEHAVIOR | 4 | User behavior type.|
**Table 4** RuleType enum values
| Rule Type| Value| Description|
| ------------ | ---- | ------------------ |
| WHOLE_WORD | 1 | Whole word matching. |
| PREFIX | 2 | Prefix matching. |
| REGULAR | 3 | Regular expression matching. |
**Table 5** Description of QueryRule objects
| Name| Description|
| -------- | -------- |
| QueryRule(const&nbsp;std::string&amp;&nbsp;domain,<br>const&nbsp;std::vector&lt;std::string&gt;&amp;&nbsp;eventList) | Constructor used to create a **QueryRule** object.<br>Input arguments:<br>- **domain**: domain to which the event of the **QueryRule** object belongs, in the string format. By default, an empty string indicates that the domain is successfully matched.<br>**eventList**: event name list, in the **std::vector&lt;std::string&gt;** format. By default, an empty string indicates that the event names on the list are successfully matched.|
| QueryRule(const&nbsp;std::string&amp;&nbsp;domain,<br>const&nbsp;std::vector&lt;std::string&gt;&amp;&nbsp;eventList,<br>RuleType&nbsp;ruleType,<br>uint32_t&nbsp;eventType,<br>const&nbsp;std::string&&nbsp;cond) | Constructor used to create a **QueryRule** object.<br>Input arguments:<br>- **domain**: domain to which the event of the **QueryRule** object belongs, in the string format. By default, an empty string indicates that the domain is successfully matched.<br>**eventList**: event name list, in the **std::vector&lt;std::string&gt;** format. By default, an empty string indicates that the event names on the list are successfully matched.<br>- **ruleType**: rule type. For details, see Table 4.<br>- **eventType**: system event type. The value is of the uint32_t type. For details about the system event types, see Table 3. When **eventType** is set to **0**, all types of events are queried.<br>- **cond**: query criteria. The value is of the string type.|
**Table 4** Description of HiSysEventQueryCallback objects
The **condition** parameter must be in the specified JSON string format. For example:
| API| Description|
```json
{
"version":"V1",
"condition":{
"and":[
{"param":"type_","op":">","value":0},
{"param":"uid_","op":"=","value":1201}
]
}
}
```
- The **version** field is mandatory, indicating the supported version of the input condition. Currently, only **V1** is supported.
- The **condition** field is mandatory, indicating the input condition.
- The **and** field is optional, indicating the AND relationship between conditions.
- The **param** field is mandatory, indicating the parameter name for condition matching. The value must be a string.
- The **op** field is mandatory, indicating the parameter comparison operator for condition matching. The value must be a string. Supported comparison operators include the following: =, >, <, >=, and <=.
- The **value** field is mandatory, indicating the parameter value for condition matching. The value must be a string or an integer.
**Table 6** Description of HiSysEventQueryCallback objects
| Name| Description|
| -------- | -------- |
| void&nbsp;HiSysEventQueryCallback::OnQuery(std::shared_ptr&lt;std::vector&lt;HiSysEventRecord&gt;&gt;&nbsp;sysEvents) | Callback object for event query.<br>Input arguments:<br>- **sysEvents**: event list.|
| void&nbsp;HiSysEventQueryCallback::OnComplete(int32_t&nbsp;reason,&nbsp;int32_t&nbsp;total) | Callback object for completion of event query.<br>Input arguments:<br>- **reason**: reason for completion of event query. The value **0** indicates that the query is normal, and any other value indicates that the query has failed.<br>- **total**: total number of events returned in this query.|
#### C Event Query API
#### C APIs
HiSysEvent query is implemented using the API provided in the following table. For details, see the [API Header Files](/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent_manager/include/).
**Table 5** Description of the HiSysEvent query API
**Table 7** Description of the C HiSysEvent query API
| API | Description |
| Name | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| int OH_HiSysEvent_Query(const HiSysEventQueryArg& arg, HiSysEventQueryRule rules[], size_t ruleSize, HiSysEventQueryCallback& callback); | Queries system events by search criteria such as the time segment, event domain, event name, and event parameter.<br>Input arguments:<br>- **arg**: event query parameter.<br>- **rules**: rules for event filtering.<br>- **ruleSize**: number of event filtering rules.<br>- **callback**: callback object for event query.<br>Return value:<br>- **0**: Query is successful.<br>- A negative value: Query has failed.|
| int OH_HiSysEvent_Query(const HiSysEventQueryArg& arg, HiSysEventQueryRule rules[], size_t ruleSize, HiSysEventQueryCallback& callback); | Queries system events by search criteria such as the time segment, event domain, event name, and event parameter.<br>Input arguments:<br>- **arg**: event query parameter.<br>- **rules**: event filtering rules.<br>- **ruleSize**: number of event filtering rules.<br>- **callback**: callback object for event query.<br>Return value:<br>- **0**: Query is successful.<br>- A negative value: Query has failed.|
**Table 6** Description of the HiSysEventQueryArg structure
**Table 8** Description of the HiSysEventQueryArg structure
| Attribute | Type| Description |
| Field | Type| Description |
| --------- | -------- | ---------------------------------------------------- |
| beginTime | int64_t | Start time for query. The value is a Unix timestamp, in milliseconds.|
| endTime | int64_t | End time for query. The value is a Unix timestamp, in milliseconds.|
| maxEvents | int32_t | Maximum number of returned events. |
**Table 7** Description of the HiSysEventQueryRule structure
**Table 9** Description of the HiSysEventQueryRule structure
| Attribute | Type | Description |
| Field | Type | Description |
| ------------- | --------- | ---------------------------------- |
| domain | char[] | Event domain. |
| eventList | char\[][] | Event name list. |
| eventListSize | size_t | Size of the event name list. |
| condition | char* | Custom event parameter conditions for the query.|
The **condition** parameter must be in the specified JSON string format. For example:
```json
{
"version":"V1",
"condition":{
"and":[
{"param":"type_","op":">","value":0},
{"param":"uid_","op":"=","value":1201}
]
}
}
```
- The **version** field is mandatory, indicating the supported version of the input condition. Currently, only **V1** is supported.
- The **condition** field is mandatory, indicating the input condition.
- The **and** field is optional, indicating the AND relationship between conditions.
- The **param** field is mandatory, indicating the parameter name for condition matching. The value must be a string.
- The **op** field is mandatory, indicating the parameter comparison operator for condition matching. The value must be a string. Supported comparison operators include the following: =, >, <, >=, and <=.
- The **value** field is mandatory, indicating the parameter value for condition matching. The value must be a string or an integer.
**Table 10** Description of the HiSysEventQueryCallback structure
**Table 8** Description of the HiSysEventQueryCallback structure
| Attribute | Type | Description |
| Field | Type | Description |
| ---------- | -------------------------------------------------- | ------------------------------------------------------------ |
| OnQuery | void (*)(HiSysEventRecord records[], size_t size); | Callback object for event query.<br>Input arguments:<br>- **records**: event list.<br>- **size**: size of the event list.|
| OnComplete | void (*)(int32_t reason, int32_t total); | Callback object for completion of event query.<br>Input arguments:<br>- **reason**: reason for completion of event query. The value **0** indicates that the query is normal, and any other value indicates that the query has failed.<br>- **total**: total number of events returned in this query.|
**Table 9** Description of the HiSysEventRecord event structure
**Table 11** Description of the HiSysEventRecord event structure
| Attribute | Type | Description |
| Field | Type | Description |
| --------- | ------------------- | -------------------------- |
| domain | char[] | Event domain. |
| eventName | char\[] | Event name. |
......@@ -120,13 +140,13 @@ The **condition** parameter must be in the specified JSON string format. For exa
| tag | char* | Event tag. |
| jsonStr | char* | Event content. |
**Table 10** Description of HiSysEventRecord APIs
**Table 12** Description of HiSysEventRecord APIs
| API | |
| Name | |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| void OH_HiSysEvent_GetParamNames(const HiSysEventRecord& record, char*** params, size_t& len); | Obtains all parameter names of an event.<br>Input arguments:<br>- **record**: event structure.<br>- **params**: parameter name array.<br>- **len**: size of the parameter name array.|
| int OH_HiSysEvent_GetParamInt64Value(const HiSysEventRecord& record, const char* name, int64_t& value); | Parses the parameter value in the event to an int64_t value and assigns the value to **value**.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: parameter value of the int64_t type.|
| int OH_HiSysEvent_GetParamUint64Value(const HiSysEventRecord& record, const char* name, uint64_t& value); | Parses the parameter value in the event to an uint64_t value and assigns the value to **value**.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: parameter value of the uint64_t type.|
| int OH_HiSysEvent_GetParamUint64Value(const HiSysEventRecord& record, const char* name, uint64_t& value); | Parses the parameter value in the event to a uint64_t value and assigns the value to **value**.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: parameter value of the uint64_t type.|
| int OH_HiSysEvent_GetParamDoubleValue(const HiSysEventRecord& record, const char* name, double& value); | Parses the parameter value in the event to a double value and assigns the value to **value**.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: parameter value of the double type.|
| int OH_HiSysEvent_GetParamStringValue(const HiSysEventRecord& record, const char* name, char** value); | Parses the parameter value in the event to a char array value and assigns the value to **value**. You need to release the memory manually after usage.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: char\* reference.|
| int OH_HiSysEvent_GetParamInt64Values(const HiSysEventRecord& record, const char* name, int64_t** value, size_t& len); | Parses the parameter value in the event to a int64_t array value and assigns the value to **value**. You need to release the memory manually after usage.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: int64_t\* reference.<br>- **len**: array size.|
......@@ -143,15 +163,15 @@ The return values of the HiSysEventRecord APIs are described as follows:
### How to Develop
#### C++ HiSysEvent Query API
#### C++ HiSysEvent Query
1. Import the corresponding header file:
1. Import the corresponding header file.
```c++
#include "hisysevent_manager.h"
```
2. Implement the callback API.
2. Implement the callback API for the service domain.
```c++
class TestQueryCallback : public HiSysEventQueryCallback {
......@@ -174,35 +194,35 @@ The return values of the HiSysEventRecord APIs are described as follows:
};
```
3. Call the query API while passing in the query parameter, rule, and callback object.
3. Call the query API while passing in **QueryArg**, **QueryRule**, and **QueryCallback**.
```c++
// Create a query parameter object.
// Create a QueryArg object.
long long startTime = 0;
long long endTime = 1668245644000; //2022-11-12 09:34:04
int queryCount = 10;
QueryArg arg(startTime, endTime, queryCount);
// Create a query rule object.
// Create a QueryRule object.
QueryRule rule("HIVIEWDFX", { "PLUGIN_LOAD" });
std::vector<QueryRule> queryRules = { rule };
// Create a query callback object.
// Create a QueryCallback object.
auto queryCallback = std::make_shared<TestQueryCallback>();
// Call the query API.
HiSysEventManager::Query(arg, queryRules, queryCallback);
```
#### C HiSysEvent Query API
#### C HiSysEvent Query
1. Import the corresponding header file:
1. Import the corresponding header file.
```c++
#include "hisysevent_manager_c.h"
```
2. Implement the callback API.
2. Implement the callback API for the service domain.
```c++
void OnQueryTest(HiSysEventRecord records[], size_t size)
......@@ -218,16 +238,16 @@ The return values of the HiSysEventRecord APIs are described as follows:
}
```
3. Call the query API while passing in the query parameter, rule, and callback object.
3. Call the query API while passing in **HiSysEventQueryArg**, **HiSysEventQueryRule**, and **HiSysEventQueryCallback**.
```c++
// Create a query parameter object.
// Create a HiSysEventQueryArg object.
HiSysEventQueryArg arg;
arg.beginTime = 0;
arg.endTime = 1668245644000; //2022-11-12 09:34:04
arg.maxEvents = 10;
// Create a query rule object.
// Create a HiSysEventQueryRule object.
constexpr char TEST_DOMAIN[] = "HIVIEWDFX";
constexpr char TEST_NAME[] = "PLUGIN_LOAD";
HiSysEventQueryRule rule;
......@@ -237,7 +257,7 @@ The return values of the HiSysEventRecord APIs are described as follows:
rule.condition = nullptr;
HiSysEventQueryRule rules[] = { rule };
// Create a query callback object.
// Create a HiSysEventQueryCallback object.
HiSysEventQueryCallback callback;
callback.OnQuery = OnQueryTest;
callback.OnComplete = OnCompleteTest;
......@@ -246,13 +266,13 @@ The return values of the HiSysEventRecord APIs are described as follows:
OH_HiSysEvent_Query(arg, rules, sizeof(rules) / sizeof(HiSysEventQueryRule), callback);
```
### Development Example
### Development Examples
#### C++ HiSysEvent Query
Assume that you need to query all **PLUGIN_LOAD** events that are generated for the **HIVIEWDFX** domain until the current time on a service module. The development procedure is as follows:
Suppose you want to query all events generated up to the current time with domain being **HIVIEWDFX** and name being **PLUGIN_LOAD**. The sample code is as follows:
1. Add the **libhisysevent** and **libhisyseventmanager** dependencies of the **hisysevent** component to **BUILD.gn** of the service module.
1. Add the **libhisysevent** and **libhisyseventmanager** dependencies of the **hisysevent** component to the **BUILD.gn** file of the service module.
```c++
external_deps = [
......@@ -298,36 +318,29 @@ Assume that you need to query all **PLUGIN_LOAD** events that are generated for
void TestQuery()
{
// Create a query parameter object.
long long startTime = 0;
long long endTime = GetMilliseconds();
int maxEvents = 100;
QueryArg arg(startTime, endTime, maxEvents);
// Create a query rule object.
QueryRule rule("HIVIEWDFX", { "PLUGIN_LOAD" });
std::vector<QueryRule> queryRules = { rule };
// Create a query callback object.
auto queryCallback = std::make_shared<TestQueryCallback>();
// Call the query API.
int ret = HiSysEventManager::Query(arg, queryRules, queryCallback);
}
```
#### C HiSysEvent Query
Assume that you need to query all **PLUGIN_LOAD** events that are generated for the **HIVIEWDFX** domain until the current time on a service module. The development procedure is as follows:
Suppose you want to query all events generated up to the current time with domain being **HIVIEWDFX** and name being **PLUGIN_LOAD**. The sample code is as follows:
1. Add the **libhisyseventmanager** dependency of the **hisysevent** component to the **BUILD.gn** file of the service module.
```c++
```c++
external_deps = [ "hisysevent:libhisyseventmanager" ]
// for strcpy_s
deps = [ "//third_party/bounds_checking_function:libsec_shared" ]
```
```
2. Call the query API in the **TestQuery()** function of the service module.
......@@ -355,13 +368,10 @@ Assume that you need to query all **PLUGIN_LOAD** events that are generated for
void TestQuery()
{
// Create a query parameter object.
HiSysEventQueryArg arg;
arg.beginTime = 0;
arg.endTime = GetMilliseconds();
arg.maxEvents = 100;
// Create a query rule object.
constexpr char TEST_DOMAIN[] = "HIVIEWDFX";
constexpr char TEST_NAME[] = "PLUGIN_LOAD";
HiSysEventQueryRule rule;
......@@ -370,13 +380,9 @@ Assume that you need to query all **PLUGIN_LOAD** events that are generated for
rule.eventListSize = 1;
rule.condition = nullptr;
HiSysEventQueryRule rules[] = { rule };
// Create a query callback object.
HiSysEventQueryCallback callback;
callback.OnQuery = OnQueryTest;
callback.OnComplete = OnCompleteTest;
// Call the query API.
int ret = OH_HiSysEvent_Query(arg, rules, sizeof(rules) / sizeof(HiSysEventQueryRule), callback);
}
```
# Network Management Subsystem Changelog
## request2 API Name Change
Changed the name of the HTTP streaming request from **request2** to **requestInStream**. The original name **request2** does not clearly express the intent of the API and may cause ambiguity, which does not comply with the OpenHarmony API specifications.
-
## dataProgress Event Name Change
Changed the name of the streaming data receiving event from **dataProgress** to **dataReceiveProgress**. The original name **dataProgress** does not clearly express the meaning of the event, which does not comply with the OpenHarmony API specifications.
-
**Change Impact**
For applications developed based on earlier versions, the corresponding API and event names must be updated. Otherwise, API calls may fail, affecting the service logic.
**Key API/Component Changes**
Involved APIs:
- request2;
- on(type: "dataProgress", callback: Callback<{ receiveSize: number, totalSize: number }>): void;
- off(type: "dataProgress", callback: Callback<{ receiveSize: number, totalSize: number }>): void;
Before change:
- request2(url: string, callback: AsyncCallback<number>): void;
- request2(url: string, options: HttpRequestOptions, callback: AsyncCallback<number>): void;
- request2(url: string, options?: HttpRequestOptions): Promise<number>;
- on(type: "dataProgress", callback: Callback<{ receiveSize: number, totalSize: number }>): void;
- off(type: 'dataProgress', callback?: Callback<{ receiveSize: number, totalSize: number }>): void;
After change:
- requestInStream(url: string, callback: AsyncCallback<number>): void;
- requestInStream(url: string, options: HttpRequestOptions, callback: AsyncCallback<number>): void;
- requestInStream(url: string, options?: HttpRequestOptions): Promise<number>;
- on(type: "dataReceiveProgress", callback: Callback<{ receiveSize: number, totalSize: number }>): void;
- off(type: 'dataReceiveProgress', callback?: Callback<{ receiveSize: number, totalSize: number }>): void;
**Adaptation Guide**
Replace the API name **request2** and event name **dataProgress** in the original service code with **requestInStream** and **dataReceiveProgress**, respectively.
# DFX Subsystem Changelog
## cl.hiviewdfx.1 Event Verification Specification Change for the write Method of the HiAppEvent Module
Extended the event verification specifications for the **write** method of the HiAppEvent module to support predefined events of HUAWEI Analytics. Specific changes are as follows:
- The event name can start with a dollar sign ($) and can contain uppercase letters, lowercase letters, digits, and underscores (_). Before the change, the event name can contain lowercase letters, digits, and underscores (_).
- The event parameter name can start with a dollar sign ($) and can contain uppercase letters, lowercase letters, digits, and underscores (_). Before the change, the event parameter name can contain lowercase letters, digits, and underscores (_).
**Change Impact**
More event definition formats are supported for event logging.
**Key API/Component Changes**
Involved APIs:
- hiAppEvent.write;
**Adaptation Guide**
The event verification specifications are downward compatible. No additional adaptation is required.
# Telephony Subsystem Changelog
## cl.telephony.1 VoNRState Enum Value Change of setVoNState
Changed the **VoNRState** enum values of the **setVoNState** API. The values value of **VONR_STATE_ON** is changed from **0** to **1** and that of **VONR_STATE_OFF** is defined as **0** to keep consistency with boolean values.
**Change Impact**
The new **VoNRState** enum values need to be used when **setVoNState** is called. The API function remains unchanged.
**Key API/Component Changes**
Before change:
```js
function setVoNRState(slotId: number, state: VoNRState, callback: AsyncCallback<void>): void;
/**
* @systemapi Hide this for inner system use.
* @since 10
*/
export enum VoNRState {
/** Indicates the VoNR switch is on */
VONR_STATE_ON = 0,
}
```
After change:
```js
function setVoNRState(slotId: number, state: VoNRState, callback: AsyncCallback<void>): void;
/**
* Indicates the VoNR state.
*
* @enum { number }
* @syscap SystemCapability.Telephony.CallManager
* @systemapi Hide this for inner system use.
* @since 10
*/
export enum VoNRState {
/**
* Indicates the VoNR switch is off.
*
* @syscap SystemCapability.Telephony.CallManager
* @systemapi Hide this for inner system use.
* @since 10
*/
VONR_STATE_OFF = 0,
/**
* Indicates the VoNR switch is on.
*
* @syscap SystemCapability.Telephony.CallManager
* @systemapi Hide this for inner system use.
* @since 10
*/
VONR_STATE_ON = 1,
}
```
**Adaptation Guide**
When calling **setVoNState**, use the new **VoNRState** enum values. The sample code is as follows:
```js
call.setVoNRState( 0, VONR_STATE_ON, (err) => {
if (err) {
console.log(`callback: err->${JSON.stringify(err)}`);
}
});
call.setVoNRState( 0, VONR_STATE_OFF, (err) => {
console.log(`callback: err->${JSON.stringify(err)}`);
});
```
## cl.telephony.2 Callback Value Change of setVoNState
Changed the callback value of **setVoNState** from a boolean value to **void**.
**Change Impact**
The callback value needs to be set to **void** when **setVoNState** is called.
**Key API/Component Changes**
Before change:
```js
function setVoNRState(slotId: number, state: VoNRState, callback: AsyncCallback<boolean>): void;
function setVoNRState(slotId: number, state: VoNRState): Promise<boolean>;
```
After change:
```js
function setVoNRState(slotId: number, state: VoNRState, callback: AsyncCallback<void>): void;
function setVoNRState(slotId: number, state: VoNRState): Promise<void>;
```
**Adaptation Guide**
Set the callback value to **void** when calling **setVoNState**. The sample code is as follows:
```js
call.setVoNRState( 0, VONR_STATE_ON, (err) => {
if (err) {
console.log(`callback: err->${JSON.stringify(err)}`);
}
});
call.setVoNRState( 0, VONR_STATE_OFF, (err) => {
console.log(`callback: err->${JSON.stringify(err)}`);
});
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册