diff --git a/CODEOWNERS b/CODEOWNERS index 23303c92c5a24ed1894449ea30b52c7de2685226..fffaf64564e559bbf9ca4ffd5d5a65e228b26e00 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -241,7 +241,7 @@ zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @feng-aiwen @ge zh-cn/application-dev/reference/apis/js-apis-data-rdb.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-udmf.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-cloudData.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 -zh-cn/application-dev/reference/apis/js-apis-data-relationStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 +zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-resultset.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-storage.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-ValuesBucket.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 diff --git a/en/application-dev/application-models/arkts-ui-widget-configuration.md b/en/application-dev/application-models/arkts-ui-widget-configuration.md index ea9832f92d32dfe0c2a4160f3ac6f8e904d323fa..d86c3b6991460a25c0ea6a177a8aec8c4607364c 100644 --- a/en/application-dev/application-models/arkts-ui-widget-configuration.md +++ b/en/application-dev/application-models/arkts-ui-widget-configuration.md @@ -54,7 +54,7 @@ Widget-related configuration includes **FormExtensionAbility** configuration and | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification.| String| Yes (initial value: left empty)| | metadata | Metadata of the widget. This field contains the array of the **customizeData** field.| Object| Yes (initial value: left empty)| | dataProxyEnabled | Whether the widget supports the [update-through-proxy](./arkts-ui-widget-update-by-proxy.md) feature.
- **true**: The widget supports the update-through-proxy feature.
- **false**: The widget does not support the update-through-proxy feature.
If this tag is set to **true**, the settings for the scheduled update time will still take effect, but the settings for the update interval and next update time will not.| Boolean| Yes (initial value: **false**)| - | isDynamic | Whether the widget is a dynamic widget. This tag only applies to ArkTS widgets.
- **true**: The widget is a dynamic widget.
- **false**: The widget is a static widget. In this case, the widget is displayed as a static image after being added.| Boolean| Yes (initial value: **true**)| + | isDynamic | Whether the widget is a dynamic widget. This tag applies only to ArkTS widgets.
- **true**: The widget is a dynamic widget.
- **false**: The widget is a static widget. In this case, the widget is displayed as a static image after being added.| Boolean| Yes (initial value: **true**)| **Table 2** Internal structure of the window object diff --git a/en/application-dev/application-models/component-startup-rules.md b/en/application-dev/application-models/component-startup-rules.md index bddf63dbc69ea243733e6f60f67f92a854833bf7..2db47d35f24df7d3eb155bb4ab2540f4a1af7ce0 100644 --- a/en/application-dev/application-models/component-startup-rules.md +++ b/en/application-dev/application-models/component-startup-rules.md @@ -26,7 +26,7 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol - If the **exported** field of the target component is **false**, verify the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details, see [Component exported Configuration](../quick-start/module-configuration-file.md#abilities). -- **Before starting a component of a background application, verify the BACKGROUND permission.** +- **Before starting a UIAbility component of a background application, verify the BACKGROUND permission.** - An application is considered as a foreground application only when the application process gains focus or its UIAbility component is running in the foreground. - Verify the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. @@ -45,7 +45,9 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol The rules for starting components on the same device vary in the following scenarios: -- Starting or connecting to the UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components +- Starting the UIAbility component + +- Starting the ServiceExtensionAbility and DataShareExtensionAbility components - Using **startAbilityByCall()** to start the UIAbility component @@ -56,9 +58,10 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol The rules for starting components on a different device vary in the following scenarios: -- Starting or connecting to the UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components +- Starting the UIAbility component + +- Starting the ServiceExtensionAbility and DataShareExtensionAbility components - Using **startAbilityByCall()** to start the UIAbility component ![component-startup-rules](figures/component-startup-inter-stage.png) - diff --git a/en/application-dev/application-models/figures/component-startup-inner-stage.png b/en/application-dev/application-models/figures/component-startup-inner-stage.png index 00514276f4ac3eb8ead650e5858cebb0a344d2c6..9761b9879e513f0e1ad942b5fe18997f1331c9e5 100644 Binary files a/en/application-dev/application-models/figures/component-startup-inner-stage.png and b/en/application-dev/application-models/figures/component-startup-inner-stage.png differ diff --git a/en/application-dev/application-models/figures/component-startup-inter-stage.png b/en/application-dev/application-models/figures/component-startup-inter-stage.png index a6f79e6803edc160e5570729456569f46cc80967..517407f6b557648db78a0de89431d8b18f8e2b59 100644 Binary files a/en/application-dev/application-models/figures/component-startup-inter-stage.png and b/en/application-dev/application-models/figures/component-startup-inter-stage.png differ diff --git a/en/application-dev/application-models/start-pageability-from-stage.md b/en/application-dev/application-models/start-pageability-from-stage.md index bd6a11187fdfbc81c63bcc6601f8a8e82b0dbe4c..123e15c45614f83ece1c11db87827535b2ac4937 100644 --- a/en/application-dev/application-models/start-pageability-from-stage.md +++ b/en/application-dev/application-models/start-pageability-from-stage.md @@ -8,6 +8,10 @@ This topic describes how the two application components of the stage model start A UIAbility starts a PageAbility in the same way as it starts another UIAbility. +> **NOTE** +> +> In the FA model, **abilityName** consists of **bundleName** and **AbilityName**. For details, see the code snippet below. + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -25,7 +29,7 @@ export default class EntryAbility extends UIAbility { }); let want = { bundleName: "com.ohos.fa", - abilityName: "EntryAbility", + abilityName: "com.ohos.fa.EntryAbility", }; this.context.startAbility(want).then(() => { console.info('Start Ability successfully.'); diff --git a/en/application-dev/application-models/start-uiability-from-fa.md b/en/application-dev/application-models/start-uiability-from-fa.md index 42d8e034cd6519643423bb289217d1aa140a18d4..8520cf94be0d0d21999af3175848a37edac85c52 100644 --- a/en/application-dev/application-models/start-uiability-from-fa.md +++ b/en/application-dev/application-models/start-uiability-from-fa.md @@ -14,7 +14,7 @@ import featureAbility from '@ohos.ability.featureAbility'; let parameter = { "want": { bundleName: "com.ohos.stage", - abilityName: "com.ohos.stage.EntryAbility" + abilityName: "EntryAbility" } }; featureAbility.startAbility(parameter).then((code) => { diff --git a/en/application-dev/application-models/want-overview.md b/en/application-dev/application-models/want-overview.md index cf5cac43999a5efbe59659252b6b3db325cacd8a..9260c71666f3c47181756ba205c265391d989b05 100644 --- a/en/application-dev/application-models/want-overview.md +++ b/en/application-dev/application-models/want-overview.md @@ -12,7 +12,7 @@ ## Types of Want -- **Explicit Want**: If **abilityName** and **bundleName** are specified in the **want** parameter when starting an an application component, explicit Want is used. +- **Explicit Want**: If **abilityName** and **bundleName** are specified in the **want** parameter when starting an application component, explicit Want is used. Explicit Want is usually used to start a known target application component in the same application. The target application component is started by specifying **bundleName** of the application where the target application component is located and **abilityName** in the **Want** object. When there is an explicit object to process the request, explicit Want is a simple and effective way to start the target application component. @@ -24,7 +24,7 @@ } ``` -- **Implicit Want**: If **abilityName** is not specified in the **want** parameter when starting the an application component, implicit Want is used. +- **Implicit Want**: If **abilityName** is not specified in the **want** parameter when starting an application component, implicit Want is used. Implicit Want can be used when the object used to process the request is unclear and the current application wants to use a capability (defined by the [skills tag](../quick-start/module-configuration-file.md#skills)) provided by another application. The system matches all applications that declare to support the capability. For example, for a link open request, the system matches all applications that support the request and provides the available ones for users to select. @@ -47,6 +47,7 @@ > - An application component that meets the conditions is matched. That application component is started. > - Multiple application components that meet the conditions are matched. A dialog box is displayed for users to select one of them. > - > - If the **want** parameter passed does not contain **abilityName** or **bundleName**, the ServiceExtensionAbility components of all applications cannot be started through implicit Want. + > - In the scenario for starting the ServiceExtensionAbility component: + > - If the **want** parameter passed in contains **abilityName**, the ServiceExtensionAbility component cannot be started through implicit Want. > - > - If the **want** parameter passed contains **bundleName**, the **startServiceExtensionAbility()** method can be used to implicitly start ServiceExtensionAbility. By default, ServiceExtensionAbility with the highest priority is returned. If all the matching ServiceExtensionAbility components have the same priority, the first ServiceExtensionAbility is returned. + > - If the **want** parameter passed in contains **bundleName**, the **startServiceExtensionAbility()** method can be used to implicitly start the ServiceExtensionAbility component. By default, the ServiceExtensionAbility component with the highest priority is returned. If all the matching ServiceExtensionAbility components have the same priority, the first ServiceExtensionAbility component is returned. diff --git a/en/application-dev/connectivity/http-request.md b/en/application-dev/connectivity/http-request.md index 1bb784cf96fb1d74dcbafed54498435f505814b6..a0fa4102864ba2403e7a6826f3ca3b872b5a80dd 100644 --- a/en/application-dev/connectivity/http-request.md +++ b/en/application-dev/connectivity/http-request.md @@ -1,6 +1,6 @@ # 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()10+ | Initiates an HTTP network request based on the URL and returns a streaming response.| +| requestInStream()10+ | 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'\)10+ | Unregisters the observer for events indicating receiving of HTTP streaming responses. | | on\('dataEnd'\)10+ | Registers an observer for events indicating completion of receiving HTTP streaming responses. | | off\('dataEnd'\)10+ | Unregisters the observer for events indicating completion of receiving HTTP streaming responses.| -| on\('dataProgress'\)10+ | Registers an observer for events indicating progress of receiving HTTP streaming responses. | -| off\('dataProgress'\)10+ | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.| +| on\('dataReceiveProgress'\)10+ | Registers an observer for events indicating progress of receiving HTTP streaming responses. | +| off\('dataReceiveProgress'\)10+ | 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) diff --git a/en/application-dev/connectivity/ipc-rpc-development-guideline.md b/en/application-dev/connectivity/ipc-rpc-development-guideline.md index b9bbb0608dfb83ba6d2198b063e68c4b324bbd88..14016ef5da297361bd4a17a3d278357060590784 100644 --- a/en/application-dev/connectivity/ipc-rpc-development-guideline.md +++ b/en/application-dev/connectivity/ipc-rpc-development-guideline.md @@ -1,6 +1,6 @@ # 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. diff --git a/en/application-dev/connectivity/net-connection-manager.md b/en/application-dev/connectivity/net-connection-manager.md index fba108e73cd8e5e3dd81a43880cf25a54aee6ee5..f3b945ab0970786000ab8b04adfe90592a11e0d1 100644 --- a/en/application-dev/connectivity/net-connection-manager.md +++ b/en/application-dev/connectivity/net-connection-manager.md @@ -1,10 +1,11 @@ # 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 diff --git a/en/application-dev/connectivity/net-ethernet.md b/en/application-dev/connectivity/net-ethernet.md index 18f20a7fd7e1a4c9516386c543c9521522df5f66..76ae1ee28078520b9d70796f71fd2b9236f47959 100644 --- a/en/application-dev/connectivity/net-ethernet.md +++ b/en/application-dev/connectivity/net-ethernet.md @@ -1,10 +1,11 @@ # 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** diff --git a/en/application-dev/connectivity/net-mdns.md b/en/application-dev/connectivity/net-mdns.md index de7982a5c03908a70e4005bdc5fbea3584c435f5..75da959da8c4b1fc55aa0afca1cf0dcd945b86bb 100644 --- a/en/application-dev/connectivity/net-mdns.md +++ b/en/application-dev/connectivity/net-mdns.md @@ -1,6 +1,6 @@ # 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. diff --git a/en/application-dev/connectivity/net-sharing.md b/en/application-dev/connectivity/net-sharing.md index 4072217d9ced5d99b2052b5db8ccb8333fcb7023..f2b2e6ac21362691ede111db8b16316fa9fd32cb 100644 --- a/en/application-dev/connectivity/net-sharing.md +++ b/en/application-dev/connectivity/net-sharing.md @@ -1,10 +1,11 @@ # 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 diff --git a/en/application-dev/connectivity/net-statistics.md b/en/application-dev/connectivity/net-statistics.md index 47ec62ff156448b3214885176c30b2f76d77b76c..6df8800dd479b48c32619514b8e6b90d5c776330 100644 --- a/en/application-dev/connectivity/net-statistics.md +++ b/en/application-dev/connectivity/net-statistics.md @@ -1,6 +1,6 @@ # 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. diff --git a/en/application-dev/connectivity/net-vpn.md b/en/application-dev/connectivity/net-vpn.md index adf38f9676f29937532579e0bbdb4a94467095f3..a93b00b932bdec33de7cb45764474c163ed456ce 100644 --- a/en/application-dev/connectivity/net-vpn.md +++ b/en/application-dev/connectivity/net-vpn.md @@ -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. diff --git a/en/application-dev/connectivity/socket-connection.md b/en/application-dev/connectivity/socket-connection.md index 9dda8b4e4c0ac6931ea75ad706fef76c9fb3c0a3..fe8ab1f141e3525de46985ba113eee364adac723 100644 --- a/en/application-dev/connectivity/socket-connection.md +++ b/en/application-dev/connectivity/socket-connection.md @@ -1,6 +1,6 @@ # 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. diff --git a/en/application-dev/connectivity/subscribe-remote-state.md b/en/application-dev/connectivity/subscribe-remote-state.md index 5b21750ba8b56fefcb10a5fff653d7512765c279..d23385e44752cb0945217eddc74117202ca38c5f 100755 --- a/en/application-dev/connectivity/subscribe-remote-state.md +++ b/en/application-dev/connectivity/subscribe-remote-state.md @@ -1,5 +1,7 @@ # 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 diff --git a/en/application-dev/connectivity/websocket-connection.md b/en/application-dev/connectivity/websocket-connection.md index 4c373011c45be18183e4c622c3e7e35b97198a24..1b162256db5cad28aa50ca6989625f9191fb2257 100644 --- a/en/application-dev/connectivity/websocket-connection.md +++ b/en/application-dev/connectivity/websocket-connection.md @@ -1,6 +1,6 @@ # 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. diff --git a/en/application-dev/dfx/Readme-EN.md b/en/application-dev/dfx/Readme-EN.md index 5a1b6326bae1ecb94ef7fe8d9e4cfe2cdf2c6c56..c40f752d8f85e8894eb725965f50a7614dddef36 100644 --- a/en/application-dev/dfx/Readme-EN.md +++ b/en/application-dev/dfx/Readme-EN.md @@ -1,7 +1,6 @@ # 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 diff --git a/en/application-dev/dfx/appfreeze-guidelines.md b/en/application-dev/dfx/appfreeze-guidelines.md index 05b52c4d8070386ec350701cefb2c6b63ef67d55..4984c95e215fe832f59abc3306bf777c6c313818 100644 --- a/en/application-dev/dfx/appfreeze-guidelines.md +++ b/en/application-dev/dfx/appfreeze-guidelines.md @@ -1,6 +1,6 @@ # 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. diff --git a/en/application-dev/dfx/apprecovery-guidelines.md b/en/application-dev/dfx/apprecovery-guidelines.md index 284de5ca6d5f6027f2cce975a29b3259b2778021..9548404b3b359ad3f6fbe6778e0ddaeb374cc2ec 100644 --- a/en/application-dev/dfx/apprecovery-guidelines.md +++ b/en/application-dev/dfx/apprecovery-guidelines.md @@ -1,6 +1,6 @@ # 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. @@ -99,9 +99,12 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant' - Define and register the [ErrorObserver](../reference/apis/js-apis-inner-application-errorObserver.md) callback. For details about its usage, see [errorManager](../reference/apis/js-apis-app-ability-errorManager.md). ```ts - var registerId = -1; - var callback = { - onUnhandledException(errMsg) { + export let abilityWant : Want // file1 + + import * as G form "../file1" + let registerId = -1; + let callback: Callback = { + onUnhandledException(errMsg: string): void { console.log(errMsg); appRecovery.saveAppState(); appRecovery.restartApp(); @@ -112,7 +115,7 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant' // Main window is created, set main page for this ability console.log("[Demo] MainAbility onWindowStageCreate") - globalThis.registerObserver = (() => { + G.registerObserver = (() => { registerId = errorManager.on('error', callback); }) @@ -138,13 +141,16 @@ After the callback triggers **appRecovery.saveAppState()**, **onSaveState(state, After the callback triggers **appRecovery.restartApp()**, the application is restarted. After the restart, **onCreate(want, launchParam)** of **MainAbility** is called, and the saved data is in **parameters** of **want**. ```ts +export let abilityWant : Want // file1 + +import * as GlobalWant form "../file1" storage: LocalStorage onCreate(want, launchParam) { console.log("[Demo] MainAbility onCreate") - globalThis.abilityWant = want; + GlobalWant.abilityWant = want; if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) { this.storage = new LocalStorage(); - let recoveryData = want.parameters["myData"]; + let recoveryData: string = want.parameters["myData"]; this.storage.setOrCreate("myData", recoveryData); this.context.restoreWindowStage(this.storage); } @@ -154,12 +160,15 @@ onCreate(want, launchParam) { - Unregister the **ErrorObserver** callback. ```ts +export let abilityWant : Want // file1 + +import * as G form "../file1" onWindowStageDestroy() { // Main window is destroyed, release UI related resources console.log("[Demo] MainAbility onWindowStageDestroy") - globalThis.unRegisterObserver = (() => { - errorManager.off('error', registerId, (err) => { + G.unRegisterObserver = (() => { + errorManager.off(type: 'error', registerId: number, (err:Error) => { console.error("[Demo] err:", err); }); }) @@ -171,20 +180,22 @@ onWindowStageDestroy() { This is triggered by the recovery framework. You do not need to register an **ErrorObserver** callback. You only need to implement **onSaveState** for application state saving and **onCreate** for data restore. ```ts +export let abilityWant : Want // file1 + +import * as GlobalWant form "../file1" export default class MainAbility extends Ability { - storage: LocalStorage - onCreate(want, launchParam) { + onCreate(want: Want, launchParam:AbilityConstant.LaunchParam):void { console.log("[Demo] MainAbility onCreate") - globalThis.abilityWant = want; + GlobalWant.abilityWant = want; if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) { this.storage = new LocalStorage(); - let recoveryData = want.parameters["myData"]; - this.storage.setOrCreate("myData", recoveryData); + let recoveryData: string = want.parameters["myData"]; + this.storage.setOrCreate("myData", recoveryData); this.context.restoreWindowStage(this.storage); } } - onSaveState(state, wantParams) { + onSaveState(state: AbilityConstant.StateType, wantParams: { [key: string]: Object }) : AbilityConstant.OnSaveResult{ // Ability has called to save app data console.log("[Demo] MainAbility onSaveState") wantParams["myData"] = "my1234567"; diff --git a/en/application-dev/dfx/cppcrash-guidelines.md b/en/application-dev/dfx/cppcrash-guidelines.md index c3ca07a4dc3a069272d89986329c2cbe103a45cb..15136518788324e23ac46c8c8b5bba327c03ea7a 100644 --- a/en/application-dev/dfx/cppcrash-guidelines.md +++ b/en/application-dev/dfx/cppcrash-guidelines.md @@ -1,6 +1,6 @@ # 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. diff --git a/en/application-dev/dfx/errormanager-guidelines.md b/en/application-dev/dfx/errormanager-guidelines.md index 4679cfcfc78893590fe73eab770e49fc68a1a828..14d7735d731d0fb2eb3fc41f61de58f5de7f4e02 100644 --- a/en/application-dev/dfx/errormanager-guidelines.md +++ b/en/application-dev/dfx/errormanager-guidelines.md @@ -1,6 +1,6 @@ # 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. diff --git a/en/application-dev/dfx/hiappevent-guidelines.md b/en/application-dev/dfx/hiappevent-guidelines.md index d21d4e3fa9e0fa0b795c82e7157cd6215eab5e0c..6b0f4dd1cb8ec36288514e3f8767770f4e30105b 100644 --- a/en/application-dev/dfx/hiappevent-guidelines.md +++ b/en/application-dev/dfx/hiappevent-guidelines.md @@ -1,6 +1,6 @@ # 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. diff --git a/en/application-dev/dfx/hilog-guidelines.md b/en/application-dev/dfx/hilog-guidelines.md index 25b4a7f9cc5c92d9f20ed6582299d5dd65b937d0..45d46c01fb4c601241120ce9cf5d249bd0bc893f 100644 --- a/en/application-dev/dfx/hilog-guidelines.md +++ b/en/application-dev/dfx/hilog-guidelines.md @@ -1,6 +1,6 @@ # 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. diff --git a/en/application-dev/dfx/hitracechain-guidelines.md b/en/application-dev/dfx/hitracechain-guidelines.md index affd260b0503f3c4f4c4b748d5911d94f7fef9e3..44e2da92dfbf985f27a275ac6e02e61a934d199e 100644 --- a/en/application-dev/dfx/hitracechain-guidelines.md +++ b/en/application-dev/dfx/hitracechain-guidelines.md @@ -1,6 +1,6 @@ # 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. diff --git a/en/application-dev/dfx/hitracemeter-guidelines.md b/en/application-dev/dfx/hitracemeter-guidelines.md index ed99e4e89d5b6fce3d5bd50ef8dedcfc32b04fb1..195aae4b2d98dd1ab950613c6c97ed07cfcfe98e 100644 --- a/en/application-dev/dfx/hitracemeter-guidelines.md +++ b/en/application-dev/dfx/hitracemeter-guidelines.md @@ -1,6 +1,6 @@ # 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,60 +35,16 @@ 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'; - + @Entry @Component struct Index { @State message: string = 'Hello World'; - + build() { Row() { Column() { @@ -97,7 +53,7 @@ In this example, distributed call chain tracing begins when the application star .fontWeight(FontWeight.Bold) .onClick(() => { this.message = 'Hello ArkUI'; - + // Start trace tasks with the same name concurrently. hitrace.startTrace("HITRACE_TAG_APP", 1001); // Keep the service process running. @@ -107,7 +63,7 @@ In this example, distributed call chain tracing begins when the application star hitrace.startTrace("HITRACE_TAG_APP", 1002); // Keep the service process running. console.log(`HITRACE_TAG_APP running`); - + hitrace.finishTrace("HITRACE_TAG_APP", 1001); hitrace.finishTrace("HITRACE_TAG_APP", 1002); @@ -143,7 +99,7 @@ In this example, distributed call chain tracing begins when the application star ``` 3. Click the run button on the application page. Then, run the following commands in sequence in shell: - + ```shell hdc shell hitrace --trace_begin app diff --git a/en/application-dev/dfx/hitracemeter-native-guidelines.md b/en/application-dev/dfx/hitracemeter-native-guidelines.md index bb0274f7c4077b016061430250e7a949cf826864..912ec1c5f87b6ebfdd6f14cb4da568e251501af2 100644 --- a/en/application-dev/dfx/hitracemeter-native-guidelines.md +++ b/en/application-dev/dfx/hitracemeter-native-guidelines.md @@ -1,6 +1,6 @@ # 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** diff --git a/en/application-dev/faqs/faqs-graphics.md b/en/application-dev/faqs/faqs-graphics.md index 345cbf83c5b2976c810e78237cb2587eaa4b1404..4cc8b196d5b8210e2360a598c1b24fdc0edb891b 100644 --- a/en/application-dev/faqs/faqs-graphics.md +++ b/en/application-dev/faqs/faqs-graphics.md @@ -21,42 +21,6 @@ try { } ``` -## How do I hide the status bar to get the immersive effect? - -Applicable to: OpenHarmony 3.2 Beta5 (API version 9) - -**Solution** - -1. Use **onWindowStageCreate** to obtain a **windowClass** object. - - ``` - onWindowStageCreate(windowStage) { - // When the main window is created, set the main page for this ability. - console.log("[Demo] MainAbility onWindowStageCreate") - windowStage.getMainWindow((err, data) => { - if (err.code) { - console.error('Failed to obtain the main window.') - return; - } - // Obtain a windowClass object. - globalThis.windowClass = data; - }) - } - ``` - -2. Enable the full-screen mode for the window and hide the status bar. - - ``` - globalThis.windowClass.setFullScreen(isFullScreen, (err, data) => { - if (err.code) { - console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); - }); - ``` - - ## How do I obtain the window width and height? Applicable to: OpenHarmony 3.2 Beta5 (API version 9, stage model) diff --git a/en/application-dev/media/using-avrecorder-for-recording.md b/en/application-dev/media/using-avrecorder-for-recording.md index 71ab8557df470671088adfaa0473a6448d935881..aa204062795339cf425cb95d9726001f56b66d9a 100644 --- a/en/application-dev/media/using-avrecorder-for-recording.md +++ b/en/application-dev/media/using-avrecorder-for-recording.md @@ -20,11 +20,11 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re ```ts import media from '@ohos.multimedia.media'; - let avRecorder = undefined; - media.createAVRecorder().then((recorder) => { + let avRecorder: media.AVRecorder; + media.createAVRecorder().then((recorder: media.AVRecorder) => { avRecorder = recorder; - }, (err) => { - console.error(`Invoke createAVRecorder failed, code is ${err.code}, message is ${err.message}`); + }, (error: Error) => { + console.error(`createAVRecorder failed`); }) ``` @@ -37,13 +37,13 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re ```ts // Callback function for state changes. - avRecorder.on('stateChange', (state, reason) => { + avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => { console.log(`current state is ${state}`); // You can add the action to be performed after the state is switched. }) // Callback function for errors. - avRecorder.on('error', (err) => { + avRecorder.on('error', (err: BusinessError) => { console.error(`avRecorder failed, code is ${err.code}, message is ${err.message}`); }) ``` @@ -62,21 +62,21 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re ```ts - let avProfile = { + let avProfile: media.AVRecorderProfile = { audioBitrate: 100000, // Audio bit rate. audioChannels: 2, // Number of audio channels. audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format. Currently, only AAC is supported. audioSampleRate: 48000, // Audio sampling rate. fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // Encapsulation format. Currently, only M4A is supported. } - let avConfig = { + let avConfig: media.AVRecorderConfig = { audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // Audio input source. In this example, the microphone is used. profile: avProfile, url: 'fd://35', // Obtain the file descriptor of the created audio file by referring to the sample code in Application File Access and Management. } avRecorder.prepare(avConfig).then(() => { console.log('Invoke prepare succeeded.'); - }, (err) => { + }, (err: BusinessError) => { console.error(`Invoke prepare failed, code is ${err.code}, message is ${err.message}`); }) ``` @@ -100,17 +100,17 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re ```ts import media from '@ohos.multimedia.media'; - +import { BusinessError } from '@ohos.base'; export class AudioRecorderDemo { - private avRecorder; - private avProfile = { + private avRecorder: media.AVRecorder; + private avProfile: media.AVRecorderProfile = { audioBitrate: 100000, // Audio bit rate. audioChannels: 2, // Number of audio channels. audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format. Currently, only AAC is supported. audioSampleRate: 48000, // Audio sampling rate. fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // Encapsulation format. Currently, only M4A is supported. }; - private avConfig = { + private avConfig: media.AVRecorderConfig = { audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // Audio input source. In this example, the microphone is used. profile: this.avProfile, url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management. @@ -119,11 +119,11 @@ export class AudioRecorderDemo { // Set AVRecorder callback functions. setAudioRecorderCallback() { // Callback function for state changes. - this.avRecorder.on('stateChange', (state, reason) => { + this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => { console.log(`AudioRecorder current state is ${state}`); }) // Callback function for errors. - this.avRecorder.on('error', (err) => { + this.avRecorder.on('error', (err: BusinessError) => { console.error(`AudioRecorder failed, code is ${err.code}, message is ${err.message}`); }) } diff --git a/en/application-dev/media/video-recording.md b/en/application-dev/media/video-recording.md index 8eabb4e1aad61f954135832ff2e5439912acdb34..d2f5affc31bca6badec8329a918a2aed2e498779 100644 --- a/en/application-dev/media/video-recording.md +++ b/en/application-dev/media/video-recording.md @@ -24,10 +24,10 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re ```ts import media from '@ohos.multimedia.media' - let avRecorder - media.createAVRecorder().then((recorder) => { + let avRecorder: media.AVRecorder; + media.createAVRecorder().then((recorder: media.AVRecorder) => { avRecorder = recorder - }, (error) => { + }, (error: Error) => { console.error('createAVRecorder failed') }) ``` @@ -40,11 +40,11 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re ```ts // Callback function for state changes. - avRecorder.on('stateChange', (state, reason) => { + avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => { console.info('current state is: ' + state); }) // Callback function for errors. - avRecorder.on('error', (err) => { + avRecorder.on('error', (err: BusinessError) => { console.error('error happened, error message is ' + err); }) ``` @@ -62,7 +62,7 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re > - The recording output URL (URL in **avConfig** in the sample code) must be in the format of fd://xx (where xx indicates a file descriptor). You must call [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement access to the application file. For details, see [Application File Access and Management](../file-management/app-file-access.md). ```ts - let avProfile = { + let avProfile: media.AVRecorderProfile = { fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported. videoBitrate: 200000, // Video bit rate. videoCodec: media.CodecMimeType.VIDEO_AVC, // Video file encoding format. Both MPEG-4 and AVC are supported. @@ -70,15 +70,15 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re videoFrameHeight: 480, // Video frame height. videoFrameRate: 30 // Video frame rate. } - let avConfig = { + let avConfig: media.AVRecorderConfig = { videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // Video source type. YUV and ES are supported. - profile : this.avProfile, + profile : avProfile, url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management. rotation: 0, // Video rotation angle. The default value is 0, indicating that the video is not rotated. The value can be 0, 90, 180, or 270. } avRecorder.prepare(avConfig).then(() => { console.info('avRecorder prepare success') - }, (error) => { + }, (error: Error) => { console.error('avRecorder prepare failed') }) ``` @@ -90,9 +90,9 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re The video data collection module obtains the surface based on the surface ID and transmits video data to the AVRecorder through the surface. Then the AVRecorder processes the video data. ```ts - avRecorder.getInputSurface().then((surfaceId) => { + avRecorder.getInputSurface().then((surfaceId: string) => { console.info('avRecorder getInputSurface success') - }, (error) => { + }, (error: Error) => { console.error('avRecorder getInputSurface failed') }) ``` @@ -123,19 +123,20 @@ Refer to the sample code below to complete the process of starting, pausing, res ```ts import media from '@ohos.multimedia.media' +import { BusinessError } from '@ohos.base'; const TAG = 'VideoRecorderDemo:' export class VideoRecorderDemo { - private avRecorder; - private videoOutSurfaceId; - private avProfile = { + private avRecorder: media.AVRecorder; + private videoOutSurfaceId: string; + private avProfile: media.AVRecorderProfile = { fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported. - videoBitrate : 100000, // Video bit rate. + videoBitrate: 100000, // Video bit rate. videoCodec: media.CodecMimeType.VIDEO_AVC, // Video file encoding format. Both MPEG-4 and AVC are supported. videoFrameWidth: 640, // Video frame width. videoFrameHeight: 480, // Video frame height. videoFrameRate: 30 // Video frame rate. } - private avConfig = { + private avConfig: media.AVRecorderConfig = { videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // Video source type. YUV and ES are supported. profile : this.avProfile, url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management. @@ -145,11 +146,11 @@ export class VideoRecorderDemo { // Set AVRecorder callback functions. setAvRecorderCallback() { // Callback function for state changes. - this.avRecorder.on('stateChange', (state, reason) => { + this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => { console.info(TAG + 'current state is: ' + state); }) // Callback function for errors. - this.avRecorder.on('error', (err) => { + this.avRecorder.on('error', (err: BusinessError) => { console.error(TAG + 'error ocConstantSourceNode, error message is ' + err); }) } @@ -188,7 +189,7 @@ export class VideoRecorderDemo { // 5. Start the camera stream output. await this.startCameraOutput(); // 6. Start recording. - await this.videoRecorder.start(); + await this.avRecorder.start(); } // Process of pausing recording. diff --git a/en/application-dev/napi/neural-network-runtime-guidelines.md b/en/application-dev/napi/neural-network-runtime-guidelines.md index 344ae4f1d623f67fcd3b093e8dec6653b806c4f2..974ccc5bafbfe7169034924ba27d0eb3c91606a8 100644 --- a/en/application-dev/napi/neural-network-runtime-guidelines.md +++ b/en/application-dev/napi/neural-network-runtime-guidelines.md @@ -1,4 +1,4 @@ -# 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 @@ -19,8 +19,7 @@ The environment requirements for the Neural Network Runtime are as follows: - Development environment: Ubuntu 18.04 or later. - Access device: a standard device running OpenHarmony. The built-in hardware accelerator driver has been connected to the Neural Network Runtime through an HDI API. -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. - +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 @@ -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 @@ -488,4 +486,4 @@ The development process of the Neural Network Runtime consists of three phases: ```shell rm /data/local/tmp/*nncache - ``` \ No newline at end of file + ``` diff --git a/en/application-dev/quick-start/arkts-appstorage.md b/en/application-dev/quick-start/arkts-appstorage.md index 50cbcf6aa0854fc901eb6bbf80b41da7c990eaa1..c1ebb9c91252d5b75a96b837e6f07bd2f1053a56 100644 --- a/en/application-dev/quick-start/arkts-appstorage.md +++ b/en/application-dev/quick-start/arkts-appstorage.md @@ -23,8 +23,7 @@ Selected state attributes of AppStorage can be synced with different data source As mentioned above, if you want to establish a binding between AppStorage and a custom component, you'll need the \@StorageProp and \@StorageLink decorators. Use \@StorageProp(key) or \@StorageLink(key) to decorate variables in the component, where **key** identifies the attribute in AppStorage. -When a custom component is initialized, the \@StorageProp(key)/\@StorageLink(key) decorated variable is initialized with the value of the attribute with the given key in AppStorage. Local initialization is mandatory. If an attribute with the given key is missing from AppStorage, it will be added with the stated initializing value. (Whether the attribute with the given key exists in AppStorage depends on the application logic.) - +When a custom component is initialized, the \@StorageProp(key)/\@StorageLink(key) decorated variable is initialized with the value of the attribute with the given key in AppStorage. Whether the attribute with the given key exists in AppStorage depends on the application logic. This means that the attribute with the given key may be missing from AppStorage. In light of this, local initialization is mandatory for the \@StorageProp(key)/\@StorageLink(key) decorated variable. By decorating a variable with \@StorageProp(key), a one-way data synchronization is established with the attribute with the given key in AppStorage. A local change can be made, but it will not be synchronized to AppStorage. An update to the attribute with the given key in AppStorage will overwrite local changes. @@ -193,9 +192,85 @@ struct CompA { } ``` -### Persistent Subscription and Callback +### Unrecommended: Using @StorageLink to Implement Event Notification + +Compared with the common mechanism for event notification, the two-way synchronization mechanism of @StorageLink and AppStorage is far less cost efficient and therefore not recommended. This is because AppStorage stores UI-related data, and its changes will cause costly UI refresh. + +In the following example, any tap event in the **TapImage** component will trigger a change of the **tapIndex** attribute. As @StorageLink establishes a two-way data synchronization with AppStorage, the local change is synchronized to AppStorage. As a result, all visible custom components owning the **tapIndex** attribute bound to AppStorage are notified to refresh the UI. + + +```ts +// xxx.ets +class ViewData { + title: string; + uri: Resource; + color: Color = Color.Black; + + constructor(title: string, uri: Resource) { + this.title = title; + this.uri = uri + } +} + +@Entry +@Component +struct Gallery2 { + dataList: Array = [new ViewData('flower', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon'))] + scroller: Scroller = new Scroller() + + build() { + Column() { + Grid(this.scroller) { + ForEach(this.dataList, (item: ViewData, index?: number) => { + GridItem() { + TapImage({ + uri: item.uri, + index: index + }) + }.aspectRatio(1) + + }, (item: ViewData, index?: number) => { + return JSON.stringify(item) + index; + }) + }.columnsTemplate('1fr 1fr') + } + + } +} + +@Component +export struct TapImage { + @StorageLink('tapIndex') @Watch('onTapIndexChange') tapIndex: number = -1; + @State tapColor: Color = Color.Black; + private index: number; + private uri: Resource; + + // Check whether the component is selected. + onTapIndexChange() { + if (this.tapIndex >= 0 && this.index === this.tapIndex) { + console.info(`tapindex: ${this.tapIndex}, index: ${this.index}, red`) + this.tapColor = Color.Red; + } else { + console.info(`tapindex: ${this.tapIndex}, index: ${this.index}, black`) + this.tapColor = Color.Black; + } + } -The persistent subscription and callback can help reduce overhead and enhance code readability. + build() { + Column() { + Image(this.uri) + .objectFit(ImageFit.Cover) + .onClick(() => { + this.tapIndex = this.index; + }) + .border({ width: 5, style: BorderStyle.Dotted, color: this.tapColor }) + } + + } +} +``` + +To implement event notification with less overhead and higher code readability, use **emit** instead, with which you can subscribe to an event and receive event callback. ```ts @@ -294,10 +369,9 @@ export struct TapImage { } ``` -The following example uses the message mechanism to subscribe to events. Because this mechanism can result in a large number of nodes to listen for and a long implementation time, it is not recommended. - +The preceding notification logic is simple. It can be simplified into a ternary expression as follows: -```ts +``` // xxx.ets class ViewData { title: string; @@ -338,22 +412,11 @@ struct Gallery2 { @Component export struct TapImage { - @StorageLink('tapIndex') @Watch('onTapIndexChange') tapIndex: number = -1; + @StorageLink('tapIndex') tapIndex: number = -1; @State tapColor: Color = Color.Black; private index: number; private uri: Resource; - // Check whether the component is selected. - onTapIndexChange() { - if (this.tapIndex >= 0 && this.index === this.tapIndex) { - console.info(`tapindex: ${this.tapIndex}, index: ${this.index}, red`) - this.tapColor = Color.Red; - } else { - console.info(`tapindex: ${this.tapIndex}, index: ${this.index}, black`) - this.tapColor = Color.Black; - } - } - build() { Column() { Image(this.uri) @@ -361,14 +424,18 @@ export struct TapImage { .onClick(() => { this.tapIndex = this.index; }) - .border({ width: 5, style: BorderStyle.Dotted, color: this.tapColor }) + .border({ + width: 5, + style: BorderStyle.Dotted, + color: (this.tapIndex >= 0 && this.index === this.tapIndex) ? Color.Red : Color.Black + }) } - } } ``` + ## Restrictions When using AppStorage together with [PersistentStorage](arkts-persiststorage.md) and [Environment](arkts-environment.md), pay attention to the following: @@ -377,5 +444,5 @@ When using AppStorage together with [PersistentStorage](arkts-persiststorage.md) - A call to **Environment.EnvProp()** after creating the attribute in AppStorage will fail. This is because AppStorage already has an attribute with the same name, and the environment variable will not be written into AppStorage. Therefore, you are advised not to use the preset environment variable name in AppStorage. -- Changes to the variables decorated by state decorators will cause UI re-render. If the changes are for message communication, rather than for UI re-render, the emitter mode is recommended. For the example, see [Persistent Subscription and Callback](#persistent-subscription-and-callback). +- Changes to the variables decorated by state decorators will cause UI re-render. If the changes are for message communication, rather than for UI re-render, the emitter mode is recommended. For the example, see [Unrecommended: Using @StorageLink to Implement Event Notification](#unrecommended-using-storagelink-to-implement-event-notification). diff --git a/en/application-dev/quick-start/arkts-builder.md b/en/application-dev/quick-start/arkts-builder.md index 80a262fcd97a0dcf6808bf8cdb84bf78849cb0e1..ab1c53b103db98c49fa42a21f69adff6ea32b86b 100644 --- a/en/application-dev/quick-start/arkts-builder.md +++ b/en/application-dev/quick-start/arkts-builder.md @@ -21,14 +21,14 @@ Syntax: ```ts -@Builder myBuilderFunction({ ... }) +@Builder MyBuilderFunction({ ... }) ``` Usage: ```ts -this.myBuilderFunction({ ... }) +this.MyBuilderFunction({ ... }) ``` - Defining one or more custom builder (\@Builder decorated) functions inside a custom component is allowed. Such a custom builder function can be considered as a private, special type of member functions of that component. @@ -66,7 +66,7 @@ There are two types of parameter passing for custom builder functions: [by-value - The parameter type must be the same as the declared parameter type. The **undefined** or **null** constants as well as expressions evaluating to these values are not allowed. -- All parameters are immutable inside the custom builder function. If mutability and synchronization of the mutation is required, the custom builder should be replaced by a custom component with a [@Link](arkts-link.md) decorated variable. +- All parameters are immutable inside the@Builder decorated function. - The \@Builder function body follows the same [syntax rules](arkts-create-custom-components.md#build-function) as the **build** function. diff --git a/en/application-dev/quick-start/arkts-environment.md b/en/application-dev/quick-start/arkts-environment.md index 2f0718290460508c4510acc298fa85c855bbec26..ac80bd54590b0dffdfa6b3bf82351d27f09917a1 100644 --- a/en/application-dev/quick-start/arkts-environment.md +++ b/en/application-dev/quick-start/arkts-environment.md @@ -15,12 +15,11 @@ Environment is a singleton object created by the ArkUI framework at application - Use **Environment.EnvProp** to save the environment variables of the device to AppStorage. ```ts - // Save the language code of the device to AppStorage. The default value is en. - // Whenever its value changes in the device environment, it will update its value in AppStorage. + // Save languageCode to AppStorage. The default value is en. Environment.EnvProp('languageCode', 'en'); ``` -- To keep a component variable updated with changes in the device environment, this variable should be decorated with \@StorageProp. +- Decorate the variables with \@StorageProp to link them with components. ```ts @StorageProp('languageCode') lang : string = 'en'; @@ -29,6 +28,7 @@ Environment is a singleton object created by the ArkUI framework at application The chain of updates is as follows: Environment > AppStorage > Component. > **NOTE** +> > An \@StorageProp decorated variable can be locally modified, but the change will not be updated to AppStorage. This is because the environment variable parameters are read-only to the application. @@ -69,3 +69,29 @@ if (lang.get() === 'en') { console.info('Hello!'); } ``` + + +## Restrictions + + +Environment can be called only when the [UIContext](../reference/apis/js-apis-arkui-UIContext.md#uicontext), which can be obtained through [runScopedTask](../reference/apis/js-apis-arkui-UIContext.md#runscopedtask), is specified. If Environment is called otherwise, no device environment data can be obtained. + + +```ts +// EntryAbility.ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; + +export default class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + windowStage.loadContent('pages/Index'); + let window = windowStage.getMainWindow() + window.then(window => { + let uicontext = window.getUIContext() + uicontext.runScopedTask(() => { + Environment.EnvProp('languageCode', 'en'); + }) + }) + } +} +``` diff --git a/en/application-dev/quick-start/arkts-observed-and-objectlink.md b/en/application-dev/quick-start/arkts-observed-and-objectlink.md index 61f1bd8ae476f5984405eed97fb127161bb131e2..a7e47fb63e57896158a6a03aaa6896bea7ac644f 100644 --- a/en/application-dev/quick-start/arkts-observed-and-objectlink.md +++ b/en/application-dev/quick-start/arkts-observed-and-objectlink.md @@ -162,6 +162,26 @@ class ClassB { this.a = a; } } + +@Observed +class ClassD { + public c: ClassC; + + constructor(c: ClassC) { + this.c = c; + } +} + +@Observed +class ClassC extends ClassA { + public k: number; + + constructor(k: number) { + // Invoke the parent class method to process k. + super(k); + this.k = k; + } +} ``` @@ -169,60 +189,64 @@ class ClassB { ```ts @Component -struct ViewA { - label: string = 'ViewA1'; - @ObjectLink a: ClassA; +struct ViewC { + label: string = 'ViewC1'; + @ObjectLink c: ClassC; build() { Row() { - Button(`ViewA [${this.label}] this.a.c=${this.a.c} +1`) - .onClick(() => { - this.a.c += 1; - }) - } + Column() { + Text(`ViewC [${this.label}] this.a.c = ${this.c.c}`) + .fontColor('#ffffffff') + .backgroundColor('#ff3fc4c4') + .height(50) + .borderRadius(25) + Button(`ViewC: this.c.c add 1`) + .backgroundColor('#ff7fcf58') + .onClick(() => { + this.c.c += 1; + console.log('this.c.c:' + this.c.c) + }) + } + .width(300) } } +} @Entry @Component struct ViewB { @State b: ClassB = new ClassB(new ClassA(0)); - + @State child : ClassD = new ClassD(new ClassC(0)); build() { Column() { - ViewA({ label: 'ViewA #1', a: this.b.a }) - ViewA({ label: 'ViewA #2', a: this.b.a }) - - Button(`ViewB: this.b.a.c+= 1`) - .onClick(() => { - this.b.a.c += 1; - }) - Button(`ViewB: this.b.a = new ClassA(0)`) + ViewC({ label: 'ViewC #3', c: this.child.c}) + Button(`ViewC: this.child.c.c add 10`) + .backgroundColor('#ff7fcf58') .onClick(() => { - this.b.a = new ClassA(0); - }) - Button(`ViewB: this.b = new ClassB(ClassA(0))`) - .onClick(() => { - this.b = new ClassB(new ClassA(0)); + this.child.c.c += 10 + console.log('this.child.c.c:' + this.child.c.c) }) } } } ``` +The @Observed decorated **ClassC** class can observe changes in attributes inherited from the base class. + Event handlers in **ViewB**: -- this.b.a = new ClassA(0) and this.b = new ClassB(new ClassA(0)): Change to the \@State decorated variable **b** and its attributes. +- this.child.c = new ClassA(0) and this.b = new ClassB(new ClassA(0)): Change to the \@State decorated variable **b** and its attributes. -- this.b.a.c = ... : Change at the second layer. Though [@State](arkts-state.md#observed-changes) cannot observe the change at the second layer, the change of an attribute of \@Observed decorated ClassA, which is attribute **c** in this example, can be observed by \@ObjectLink. +- this.child.c.c = ... : Change at the second layer. Though [@State](arkts-state.md#observed-changes) cannot observe the change at the second layer, the change of an attribute of \@Observed decorated ClassA, which is attribute **c** in this example, can be observed by \@ObjectLink. -Event handlers in **ViewA**: +Event handle in **ViewC**: -- this.a.c += 1: Changes to the \@ObjectLink decorated variable cause the button label to be updated. Unlike \@Prop, \@ObjectLink does not have a copy of its source. Instead, \@ObjectLink creates a reference to its source. +- this.c.c += 1: Changes to the \@ObjectLink decorated variable **a** cause the button label to be updated. Unlike \@Prop, \@ObjectLink does not have a copy of its source. Instead, \@ObjectLink creates a reference to its source. - The \@ObjectLink decorated variable is read-only. Assigning **this.a = new ClassA(...)** is not allowed. Once value assignment occurs, the reference to the data source is reset and the synchronization is interrupted. @@ -297,7 +321,7 @@ struct ViewB { 2. ViewA({ label: ViewA this.arrA[first], a: this.arrA[0] }): The preceding update changes the first element in the array. Therefore, the **ViewA** component instance bound to **this.arrA[0]** is updated. - this.arrA.push(new ClassA(0)): The change of this state variable triggers two updates with different effects. - 1. ForEach: The newly added Class A object is unknown to the **ForEach** [itemGenerator](arkts-rendering-control-foreach.md#api-description). The item builder of **ForEach** will be executed to create a **View A** component instance. + 1. ForEach: The newly added **ClassA** object is unknown to the **ForEach** [itemGenerator](arkts-rendering-control-foreach.md#api-description). The item builder of **ForEach** will be executed to create a **ViewA** component instance. 2. ViewA({ label: ViewA this.arrA[last], a: this.arrA[this.arrA.length-1] }): The last item of the array is changed. As a result, the second **View A** component instance is changed. For **ViewA({ label: ViewA this.arrA[first], a: this.arrA[0] })**, a change to the array does not trigger a change to the array item, so the first **View A** component instance is not refreshed. - this.arrA[Math.floor (this.arrA.length/2)].c: [@State](arkts-state.md#observed-changes) cannot observe changes at the second layer. However, as **ClassA** is decorated by \@Observed, the change of its attributes will be observed by \@ObjectLink. diff --git a/en/application-dev/quick-start/arkts-persiststorage.md b/en/application-dev/quick-start/arkts-persiststorage.md index fdbacd4235dcd50ea2777e8e3695227ff02be70c..21c854c26557e5fcd5027623b0429b625d6c9c91 100644 --- a/en/application-dev/quick-start/arkts-persiststorage.md +++ b/en/application-dev/quick-start/arkts-persiststorage.md @@ -24,7 +24,7 @@ Persistence of data is a relatively slow operation. Applications should avoid th The preceding situations may overload the change process of persisted data. As a result, the PersistentStorage implementation may limit the change frequency of persisted attributes. -PersistentStorage is associated with UIContext and can be called to persist data only when [UIContext](../reference/apis/js-apis-arkui-UIContext.md#uicontext) is specified. The context can be identified in [runScopedTask](../reference/apis/js-apis-arkui-UIContext.md#runscopedtask). +PersistentStorage can be called to persist data only when the [UIContext](../reference/apis/js-apis-arkui-UIContext.md#uicontext), which can be obtained through [runScopedTask](../reference/apis/js-apis-arkui-UIContext.md#runscopedtask), is specified. ## Application Scenarios diff --git a/en/application-dev/quick-start/arkts-rendering-control-foreach.md b/en/application-dev/quick-start/arkts-rendering-control-foreach.md index 4c916bec86f9c9d22b9bdb60ca476f9cbdcd4846..dc6ae173f51df82fbc48f26df56368450fa6fa79 100644 --- a/en/application-dev/quick-start/arkts-rendering-control-foreach.md +++ b/en/application-dev/quick-start/arkts-rendering-control-foreach.md @@ -3,6 +3,9 @@ **ForEach** enables repeated content based on array-type data. +> **NOTE** +> +> Since API version 9, this API is supported in ArkTS widgets. ## API Description @@ -19,15 +22,15 @@ ForEach( | Name | Type | Mandatory | Description | | ------------- | ---------------------------------------- | ---- | ---------------------------------------- | | arr | Array | Yes | An array, which can be empty, in which case no child component is created. The functions that return array-type values are also allowed, for example, **arr.slice (1, 3)**. The set functions cannot change any state variables including the array itself, such as **Array.splice**, **Array.sort**, and **Array.reverse**.| -| itemGenerator | (item: any, index?: number) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. Each component and its child component list must be contained in parentheses.
**NOTE**
- The type of the child component must be the one allowed inside the parent container component of **ForEach**. For example, a **\** child component is allowed only when the parent container component of **ForEach** is **\**.
- The child build function is allowed to return an **if** or another **ForEach**. **ForEach** can be placed inside **if**.
- The optional **index** parameter should only be specified in the function signature if used in its body.| -| keyGenerator | (item: any, index?: number) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **ForEach**.
**NOTE**
- Two items inside the same array must never work out the same ID.
- If **index** is not used, an item's ID must not change when the item's position within the array changes. However, if **index** is used, then the ID must change when the item is moved within the array.
- When an item is replaced by a new one (with a different value), the ID of the replaced and the ID of the new item must be different.
- When **index** is used in the build function, it should also be used in the ID generation function.
- The ID generation function is not allowed to mutate any component state.| +| itemGenerator | (item: any, index?: number) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. Each component and its child component list must be contained in parentheses.
**NOTE**
- The type of the child component must be the one allowed inside the parent container component of **ForEach**. For example, a **\** child component is allowed only when the parent container component of **ForEach** is **\**.
- The child build function is allowed to return an **if** or another **ForEach**. **ForEach** can be placed inside **if**.
- The optional **index** parameter should only be specified in the function signature if used in its body.| +| keyGenerator | (item: any, index?: number) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **ForEach**.
**NOTE**
- Two items inside the same array must never work out the same ID.
- If **index** is not used, an item's ID must not change when the item's position within the array changes. However, if **index** is used, then the ID must change when the item is moved within the array.
- When an item is replaced by a new one (with a different value), the ID of the replaced and the ID of the new item must be different.
- When **index** is used in the build function, it should also be used in the ID generation function.
- The ID generation function is not allowed to mutate any component state.| ## Restrictions - **ForEach** must be used in container components. -- The type of the child component must be the one allowed inside the parent container component of **ForEach**. +- The type of the child component must be the one allowed inside the parent container component of **ForEach**. - The **itemGenerator** function can contain an **if/else** statement, and an **if/else** statement can contain **ForEach**. diff --git a/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md b/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md index b717abf0ad082e4ea7586cc8713596a08e7b3740..de2f146c7226f3a1ef3d61dad588c84b6cc2a1ab 100644 --- a/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @@ -1,15 +1,13 @@ # @ohos.WorkSchedulerExtensionAbility (Deferred Task Scheduling Callbacks) -The **WorkSchedulerExtensionAbility** module provides callbacks for deferred task scheduling. - -When developing an application, you can override the APIs of this module and add your own task logic to the APIs. +The **WorkSchedulerExtensionAbility** module provides callbacks for deferred task scheduling. You can override the APIs provided by this module. When a deferred task is triggered, the system calls back the application through the APIs and processes the task logic in the callback. > **NOTE** > > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > - The APIs of this module can be used only in the stage model. - ## Modules to Import ```ts @@ -36,7 +34,7 @@ Called when the system starts scheduling the deferred task. | Name | Type | Mandatory | Description | | ---- | ---------------------------------------- | ---- | -------------- | -| work | [workScheduler.WorkInfo](js-apis-resourceschedule-workScheduler.md#workinfo) | Yes | Target task.| +| work | [workScheduler.WorkInfo](js-apis-resourceschedule-workScheduler.md#workinfo) | Yes | Deferred task that starts.| **Example** @@ -60,7 +58,7 @@ Called when the system stops scheduling the deferred task. | Name | Type | Mandatory | Description | | ---- | ---------------------------------------- | ---- | -------------- | -| work | [workScheduler.WorkInfo](js-apis-resourceschedule-workScheduler.md#workinfo) | Yes | Target task.| +| work | [workScheduler.WorkInfo](js-apis-resourceschedule-workScheduler.md#workinfo) | Yes | Deferred task that stops.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 5a4af7f39f321fc486a4e359b567666dc359135a..ff3fb9a3d6af1c9ab3250d892ad729dabb5220ad 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -12,6 +12,8 @@ The **CommonEvent** module provides common event capabilities, including the cap ```ts import CommonEvent from '@ohos.commonEvent'; +import CommonEventManager from '@ohos.commonEventManager'; +import Base from '@ohos.base'; ``` ## Support @@ -43,7 +45,7 @@ Publishes a common event. This API uses an asynchronous callback to return the r ```ts // Callback for common event publication -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err.code) { console.error(`publish failed, code is ${err.code}`); } else { @@ -80,14 +82,14 @@ Publishes a common event with given attributes. This API uses an asynchronous ca ```ts // Attributes of a common event. -let options = { +let options:CommonEventManager.CommonEventPublishData = { code: 0, // Result code of the common event. - data: "initial data";// Result data of the common event. + data: "initial data",// Result data of the common event. isOrdered: true // The common event is an ordered one. } // Callback for common event publication -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err.code) { console.error(`publish failed, code is ${err.code}`); } else { @@ -125,7 +127,7 @@ Publishes a common event to a specific user. This API uses an asynchronous callb ```ts // Callback for common event publication -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err.code) { console.error(`publishAsUser failed, code is ${err.code}`); } else { @@ -168,13 +170,13 @@ Publishes a common event with given attributes to a specific user. This API uses ```ts // Attributes of a common event. -let options = { +let options:CommonEventManager.CommonEventPublishData = { code: 0, // Result code of the common event. data: "initial data",// Result data of the common event. } // Callback for common event publication -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err.code) { console.error(`publishAsUser failed, code is ${err.code}`); } else { @@ -212,15 +214,15 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul ```ts -let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -let subscribeInfo = { - events: ["event"] +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { + events: ["event"] }; // Callback for subscriber creation. -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if (err.code) { console.error(`createSubscriber failed, code is ${err.code}`); } else { @@ -259,18 +261,18 @@ Creates a subscriber. This API uses a promise to return the result. **Example** ```ts -let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; // Create a subscriber. -CommonEvent.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { +CommonEvent.createSubscriber(subscribeInfo).then((commonEventSubscriber:CommonEventManager.CommonEventSubscriber) => { console.info("createSubscriber"); subscriber = commonEventSubscriber; -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`createSubscriber failed, code is ${err.code}`); }); ``` @@ -297,15 +299,15 @@ Subscribes to common events. This API uses an asynchronous callback to return th **Example** ```ts -let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; // Callback for common event subscription. -function subscribeCB(err, data) { +function subscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) { if (err.code) { console.error(`subscribe failed, code is ${err.code}`); } else { @@ -314,7 +316,7 @@ function subscribeCB(err, data) { } // Callback for subscriber creation. -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if (err.code) { console.error(`createSubscriber failed, code is ${err.code}`); } else { @@ -351,15 +353,15 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur **Example** ```ts -let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; // Callback for common event subscription. -function subscribeCB(err, data) { +function subscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) { if (err.code) { console.error(`subscribe failed, code is ${err.code}`); } else { @@ -368,7 +370,7 @@ function subscribeCB(err, data) { } // Callback for subscriber creation. -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if (err.code) { console.error(`createSubscriber failed, code is ${err.code}`); } else { @@ -380,7 +382,7 @@ function createCB(err, commonEventSubscriber) { } // Callback for common event unsubscription. -function unsubscribeCB(err) { +function unsubscribeCB(err:Base.BusinessError) { if (err.code) { console.error(`unsubscribe failed, code is ${err.code}`); } else { diff --git a/en/application-dev/reference/apis/js-apis-commonEventManager.md b/en/application-dev/reference/apis/js-apis-commonEventManager.md index 61d22613c35ceb0556ab66748f635c3e92c7b412..070fee6a9381edfea0ceaf7758b01f41a137b861 100644 --- a/en/application-dev/reference/apis/js-apis-commonEventManager.md +++ b/en/application-dev/reference/apis/js-apis-commonEventManager.md @@ -10,6 +10,7 @@ The **CommonEventManager** module provides common event capabilities, including ```ts import CommonEventManager from '@ohos.commonEventManager'; +import Base from '@ohos.base'; ``` ## Support @@ -48,7 +49,7 @@ Publishes a common event and executes an asynchronous callback after the event i ```ts // Callback for common event publication -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err) { console.error(`publish failed, code is ${err.code}, message is ${err.message}`); } else { @@ -95,14 +96,14 @@ Publishes a common event with given attributes. This API uses an asynchronous ca ```ts // Attributes of a common event. -let options = { +let options:CommonEventManager.CommonEventPublishData = { code: 0, // Result code of the common event. data: "initial data",// Result data of the common event. isOrdered: true // The common event is an ordered one. } // Callback for common event publication -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err) { console.error(`publish failed, code is ${err.code}, message is ${err.message}`); } else { @@ -151,7 +152,7 @@ Publishes a common event to a specific user. This API uses an asynchronous callb ```ts // Callback for common event publication -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err) { console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`); } else { @@ -205,13 +206,13 @@ Publishes a common event with given attributes to a specific user. This API uses ```ts // Attributes of a common event. -let options = { +let options:CommonEventManager.CommonEventPublishData = { code: 0, // Result code of the common event. data: "initial data",// Result data of the common event. } // Callback for common event publication. -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err) { console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`); } else { @@ -248,15 +249,15 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul **Example** ```ts -let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; // Callback for subscriber creation. -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if(!err) { console.info("createSubscriber"); subscriber = commonEventSubscriber; @@ -295,18 +296,18 @@ Creates a subscriber. This API uses a promise to return the result. **Example** ```ts -let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; // Create a subscriber. -CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { +CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber:CommonEventManager.CommonEventSubscriber) => { console.info("createSubscriber"); subscriber = commonEventSubscriber; -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); }); @@ -341,15 +342,15 @@ Subscribes to common events. This API uses an asynchronous callback to return th ```ts // Subscriber information. -let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; // Callback for common event subscription. -function SubscribeCB(err, data) { +function SubscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) { if (err) { console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { @@ -358,7 +359,7 @@ function SubscribeCB(err, data) { } // Callback for subscriber creation. -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if(!err) { console.info("createSubscriber"); subscriber = commonEventSubscriber; @@ -409,13 +410,13 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur **Example** ```ts -let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; // Callback for common event subscription. -function subscribeCB(err, data) { +function subscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) { if (err) { console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { @@ -423,7 +424,7 @@ function subscribeCB(err, data) { } } // Callback for subscriber creation. -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if (err) { console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); } else { @@ -438,7 +439,7 @@ function createCB(err, commonEventSubscriber) { } } // Callback for common event unsubscription. -function unsubscribeCB(err) { +function unsubscribeCB(err:Base.BusinessError) { if (err) { console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`); } else { @@ -493,7 +494,7 @@ Removes a sticky common event. This API uses an asynchronous callback to return ```ts -CommonEventManager.removeStickyCommonEvent("sticky_event", (err) => { +CommonEventManager.removeStickyCommonEvent("sticky_event", (err:Base.BusinessError) => { if (err) { console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`); return; @@ -542,7 +543,7 @@ Removes a sticky common event. This API uses a promise to return the result. ```ts CommonEventManager.removeStickyCommonEvent("sticky_event").then(() => { console.info(`Remove sticky event AsyncCallback success`); -}).catch ((err) => { +}).catch ((err:Base.BusinessError) => { console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`); }); ``` @@ -577,7 +578,7 @@ Enables or disables static subscription for the current application. This API us ```ts -CommonEventManager.setStaticSubscriberState(true, (err) => { +CommonEventManager.setStaticSubscriberState(true, (err:Base.BusinessError) => { if (!err) { console.info(`Set static subscriber state callback failed, err is null.`); return; @@ -627,7 +628,7 @@ Enables or disables static subscription for the current application. This API us ```ts CommonEventManager.setStaticSubscriberState(false).then(() => { console.info(`Set static subscriber state promise success`); -}).catch ((err) => { +}).catch ((err:Base.BusinessError) => { console.info(`Set static subscriber state promise failed, errCode: ${err.code}, errMes: ${err.message}`); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-devicestatus-cooperate.md b/en/application-dev/reference/apis/js-apis-devicestatus-cooperate.md index 737c91f0036c5217469a254aaad8974913eed1d9..bae8a5884f39618b18c4ed00d60ed3c6fa432b9e 100644 --- a/en/application-dev/reference/apis/js-apis-devicestatus-cooperate.md +++ b/en/application-dev/reference/apis/js-apis-devicestatus-cooperate.md @@ -4,9 +4,9 @@ The **cooperate** module implements screen hopping for two or more networked dev > **NOTE** > -> - The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> - The APIs provided by this module are system APIs. +> - The APIs provided by this module are system APIs. ## Modules to Import @@ -26,7 +26,7 @@ Prepares for screen hopping. This API uses an asynchronous callback to return th | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | --------------------------- | -| callback | AsyncCallback<void> | Yes|Callback used to return the result. | +| callback | AsyncCallback<void> | 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<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| @@ -75,7 +75,6 @@ try { ``` - ## cooperate.unprepare unprepare(callback: AsyncCallback<void>): void; @@ -86,7 +85,7 @@ Cancels the preparation for screen hopping. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------ | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | 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<void>; @@ -118,7 +115,7 @@ Cancels the preparation for screen hopping. This API uses a promise to return th | Parameters | Description | | ------------------- | --------------------------------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| ```js try { @@ -133,7 +130,6 @@ try { ``` - ## cooperate.activate activate(targetNetworkId: string, inputDeviceId: number, callback: AsyncCallback<void>): 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<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | 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<void> | Promise used to return the result. | +| Promise<void> | 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<void> | Yes | Callback used to return the result. | +| isUnchained | boolean | Yes| Whether to disable the cross-device link.
The value **true** means to disable the cross-device link, and the value **false** means the opposite.| +| callback | AsyncCallback<void> | 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.
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<void> | Promise used to return the result. | +| Promise<void> | 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<boolean> | Yes | Callback used to return the result.| +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** indicates that screen hopping is enabled, and the value **false** indicates the opposite.| **Example** @@ -336,9 +332,9 @@ Obtains the screen hopping status of the target device. This API uses a promise **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------- | ---- | ---------------------------- | -| networkId | string | Yes | Descriptor of the target device for screen hopping. | +| Name | Type | Mandatory | Description | +| -------- | --------- | ---- | ---------------------------- | +| networkId | string | Yes | Descriptor of the target device for screen hopping. | @@ -346,7 +342,7 @@ Obtains the screen hopping status of the target device. This API uses a promise | Parameters | Description | | ------------------- | ------------------------------- | -| Promise<boolean> | Promise used to return the result.| +| Promise<boolean> | Promise used to return the result. The value **true** indicates that screen hopping is enabled, and the value **false** indicates the opposite.| diff --git a/en/application-dev/reference/apis/js-apis-distributedMissionManager.md b/en/application-dev/reference/apis/js-apis-distributedMissionManager.md index 93e460019144b0e321b1f39b4c41a37f9c908d37..ddc6fb296b8e88bd3866696cb7a0e409918c7745 100644 --- a/en/application-dev/reference/apis/js-apis-distributedMissionManager.md +++ b/en/application-dev/reference/apis/js-apis-distributedMissionManager.md @@ -1,6 +1,6 @@ # @ohos.distributedMissionManager (Distributed Mission Management) -The **distributedMissionManager** module implements system mission management across devices. You can use the APIs provided by this module to register or deregister a mission status listener, start or stop synchronizing a remote mission list, and continue a mission on a remote device. +The **distributedMissionManager** module implements mission management across devices. You can use the APIs provided by this module to register or deregister a mission status listener, start or stop synchronizing a remote mission list, and continue a mission on a remote device by mission ID or bundle name. > **NOTE** > @@ -14,7 +14,6 @@ The **distributedMissionManager** module implements system mission management ac import distributedMissionManager from '@ohos.distributedMissionManager' ``` - ## distributedMissionManager.registerMissionListener registerMissionListener(parameter: MissionDeviceInfo, options: MissionCallback, callback: AsyncCallback<void>): void; @@ -30,8 +29,8 @@ Registers a mission status listener. This API uses an asynchronous callback to r | Name | Type | Mandatory | Description | | --------- | --------------------------------------- | ---- | --------- | | parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Information about the device to listen for.| -| options | [MissionCallback](#missioncallback) | Yes | Callback to register. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| options | [MissionCallback](#missioncallback) | Yes | Callback to register.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the listener is registered, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** @@ -80,14 +79,14 @@ Registers a mission status listener. This API uses a promise to return the resul | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------- | -| parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Information about the device to listen for. | +| parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Information about the device to listen for. | | options | MissionCallback | Yes | Callback to register.| **Return value** | Type | Description | | ------------------- | ---------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** @@ -123,7 +122,6 @@ Registers a mission status listener. This API uses a promise to return the resul } ``` - ## distributedMissionManager.unRegisterMissionListener unRegisterMissionListener(parameter: MissionDeviceInfo, callback: AsyncCallback<void>): void; @@ -138,8 +136,8 @@ Deregisters a mission status listener. This API uses an asynchronous callback to | Name | Type | Mandatory | Description | | --------- | --------------------------------------- | ---- | --------- | -| parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Information about the device to listen for. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Information about the device to listen for. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the listener is deregistered, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** @@ -159,7 +157,6 @@ Deregisters a mission status listener. This API uses an asynchronous callback to } ``` - ## distributedMissionManager.unRegisterMissionListener unRegisterMissionListener(parameter: MissionDeviceInfo): Promise<void> @@ -180,7 +177,7 @@ Deregisters a mission status listener. This API uses a promise to return the res | Type | Description | | ------------------- | ---------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -215,7 +212,7 @@ Starts to synchronize the remote mission list. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | --------- | ------------------------------------- | ---- | --------- | | parameter | [MissionParameter](#missionparameter) | Yes | Parameters required for synchronization. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the synchronization is started, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** @@ -257,7 +254,7 @@ Starts to synchronize the remote mission list. This API uses a promise to return | Type | Description | | ------------------- | ---------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** @@ -294,7 +291,7 @@ Stops synchronizing the remote mission list. This API uses an asynchronous callb | Name | Type | Mandatory | Description | | --------- | --------------------------------------- | ---- | --------- | | parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Parameters required for synchronization. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the synchronization is stopped, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** @@ -334,7 +331,7 @@ Stops synchronizing the remote mission list. This API uses a promise to return t | Type | Description | | ------------------- | ---------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** @@ -358,7 +355,7 @@ Stops synchronizing the remote mission list. This API uses a promise to return t continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback, callback: AsyncCallback<void>): void; -Continues a mission on a remote device. This API uses an asynchronous callback to return the result. +Continues a mission on a remote device, with the mission ID specified. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_MISSIONS and ohos.permission.DISTRIBUTED_DATASYNC @@ -370,7 +367,7 @@ Continues a mission on a remote device. This API uses an asynchronous callback t | --------- | --------------------------------------- | ---- | ----- | | parameter | [ContinueDeviceInfo](js-apis-inner-application-continueDeviceInfo.md) | Yes | Parameters required for mission continuation.| | options | [ContinueCallback](js-apis-inner-application-continueCallback.md) | Yes | Callback invoked when the mission continuation is complete.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the mission is continued, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -416,7 +413,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback): Promise<void> -Continues a mission on a remote device. This API uses a promise to return the result. +Continues a mission on a remote device, with the mission ID specified. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_MISSIONS and ohos.permission.DISTRIBUTED_DATASYNC @@ -433,7 +430,7 @@ Continues a mission on a remote device. This API uses a promise to return the re | Type | Description | | ------------------- | ---------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Error codes** @@ -490,7 +487,7 @@ Continues a mission on a remote device, with the bundle name specified. This API | Name | Type | Mandatory | Description | | --------- | --------------------------------------- | ---- | ----- | | parameter | [ContinueMissionInfo](./js-apis-inner-application-continueMissionInfo.md) | Yes | Parameters required for mission continuation.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the mission continuation is complete.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the mission is continued, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -546,7 +543,7 @@ Continues a mission on a remote device, with the bundle name specified. This API | Type | Description | | ------------------- | ---------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Error codes** @@ -586,7 +583,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er on(type: 'continueStateChange', callback: Callback<{ state: ContinueState, info: ContinuableInfo }>): void -Registers a listener for the mission continuation state of the current application. +Subscribes to continuation state change events of the current mission. **Required permissions**: ohos.permission.MANAGE_MISSIONS @@ -596,8 +593,8 @@ Registers a listener for the mission continuation state of the current applicati | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------- | -| type | string | Yes | Type of the listener. The value is fixed at **'continueStateChange'**. | -| callback | Callback<{ state: [ContinueState](#continuestate10), info: [ContinuableInfo](./js-apis-inner-application-continuableInfo.md) }> | Yes | Callback used to return the mission continuation state and information. | +| type | string | Yes | Event type. The value **'continueStateChange'** indicates the continuation state change event of the current mission. | +| callback | Callback<{ state: [ContinueState](#continuestate10), info: [ContinuableInfo](./js-apis-inner-application-continuableInfo.md) }> | Yes | Callback used to return the continuation state and information of the current mission. | **Example** @@ -615,7 +612,7 @@ Registers a listener for the mission continuation state of the current applicati off(type: 'continueStateChange', callback?: Callback<{ state: ContinueState, info: ContinuableInfo }>): void -Deregisters a listener for the mission continuation state of the current application. +Unsubscribes from continuation state change events of the current mission. **Required permissions**: ohos.permission.MANAGE_MISSIONS @@ -625,8 +622,8 @@ Deregisters a listener for the mission continuation state of the current applica | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------- | -| type | string | Yes | Type of the listener. The value is fixed at **'continueStateChange'**. | -| callback | Callback<{ state: [ContinueState](#continuestate10), info: [ContinuableInfo](./js-apis-inner-application-continuableInfo.md) }> | No | Callback used for the listener to be deregistered. | +| type | string | Yes | Event type. The value **'continueStateChange'** indicates the continuation state change event of the current mission. | +| callback | Callback<{ state: [ContinueState](#continuestate10), info: [ContinuableInfo](./js-apis-inner-application-continuableInfo.md) }> | No | Callback used to return the continuation state and information of the current mission.
If the callback is unspecified, all subscriptions to the specified event are canceled. | **Example** @@ -688,5 +685,5 @@ Enumerates the mission continuation states. | Name | Value | Description | | ------------- | --------- | ------------------------------------------------------------ | -| ACTIVE | 0 | Mission continuation is activated for the current application. | -| INACTIVE | 1 | Mission continuation is not activated for the current application. | +| ACTIVE | 0 | Continuation is activated for the current mission. | +| INACTIVE | 1 | Continuation is not activated for the current mission. | diff --git a/en/application-dev/reference/apis/js-apis-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiappevent.md index e2ff3f6fa98d46577475cdaa86222b0eb3522b1f..ed0fdfc9c2f1a1d9e58683f19d11f7d2e9194f48 100644 --- a/en/application-dev/reference/apis/js-apis-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiappevent.md @@ -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 10M. 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 diff --git a/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md index 03cad26cfecb5295b611d48fbc9f69862895ddb0..41d5566ed0ffaa6a9327f3da04e2c92c6a31465b 100644 --- a/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md @@ -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:
- 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 (_).
- 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.
- 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:
- 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 (_).
- 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.
- 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 diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md index 50069e993211374ce83715a18f42f6bae26d2895..6f8d2c742f12ebd5d32855d72548266abc308160 100644 --- a/en/application-dev/reference/apis/js-apis-http.md +++ b/en/application-dev/reference/apis/js-apis-http.md @@ -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(); ``` -### request210+ +### requestInStream10+ -request2(url: string, callback: AsyncCallback\): void +requestInStream(url: string, callback: AsyncCallback\): 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)); } }) ``` -### request210+ +### requestInStream10+ -request2(url: string, options: HttpRequestOptions, callback: AsyncCallback\): void +requestInStream(url: string, options: HttpRequestOptions, callback: AsyncCallback\): 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)); } }) ``` -### request210+ +### requestInStream10+ -request2(url: string, options? : HttpRequestOptions): Promise\ +requestInStream(url: string, options? : HttpRequestOptions): Promise\ 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')10+ +### on('dataReceiveProgress')10+ -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.
- **receiveSize**: number of received bytes.
- **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')10+ +### off('dataReceiveProgress')10+ -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'); ``` ## HttpRequestOptions6+ diff --git a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md index 02112d5b265e73139c9cd662246a819bc16c0b1f..cc3d507ee9d208bc66571ca56daf1cf518c3d5fe 100644 --- a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md +++ b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md @@ -10,15 +10,17 @@ Before using the **CommonEventSubscriber** module, you must obtain a **subscribe ```ts import CommonEvent from '@ohos.commonEvent'; -let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +import CommonEventManager from '@ohos.commonEventManager'; +import Base from '@ohos.base'; +let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; // Callback for subscriber creation. -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if (err.code) { console.error(`createSubscriber failed, code is ${err.code}`); } else { @@ -49,7 +51,7 @@ Obtains the code of this common event. This API uses an asynchronous callback to ```ts // Callback for result code obtaining of an ordered common event. -function getCodeCB(err, code) { +function getCodeCB(err:Base.BusinessError, code:number) { if (err.code) { console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); } else { @@ -76,9 +78,9 @@ Obtains the code of this common event. This API uses a promise to return the res **Example** ```ts -subscriber.getCode().then((code) => { +subscriber.getCode().then((code:number) => { console.info("getCode " + JSON.stringify(code)); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -102,7 +104,7 @@ Sets the code for this common event. This API uses an asynchronous callback to r ```ts // Callback for result code setting of an ordered common event. -function setCodeCB(err) { +function setCodeCB(err:Base.BusinessError) { if (err.code) { console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); } else { @@ -137,7 +139,7 @@ Sets the code for this common event. This API uses a promise to return the resul ```ts subscriber.setCode(1).then(() => { console.info("setCode"); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -160,7 +162,7 @@ Obtains the data of this common event. This API uses an asynchronous callback to ```ts // Callback for result data obtaining of an ordered common event. -function getDataCB(err, data) { +function getDataCB(err:Base.BusinessError, data:string) { if (err.code) { console.error(`getData failed, code is ${err.code}, message is ${err.message}`); } else { @@ -187,9 +189,9 @@ Obtains the data of this common event. This API uses a promise to return the res **Example** ```ts -subscriber.getData().then((data) => { +subscriber.getData().then((data:string) => { console.info("getData " + JSON.stringify(data)); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`getData failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -213,7 +215,7 @@ Sets the data for this common event. This API uses an asynchronous callback to r ```ts // Callback for result data setting of an ordered common event -function setDataCB(err) { +function setDataCB(err:Base.BusinessError) { if (err.code) { console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); } else { @@ -248,7 +250,7 @@ Sets the data for this common event. This API uses a promise to return the resul ```ts subscriber.setData("publish_data_changed").then(() => { console.info("setData"); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -273,7 +275,7 @@ Sets the code and data for this common event. This API uses an asynchronous call ```ts // Callback for code and data setting of an ordered common event. -function setCodeDataCB(err) { +function setCodeDataCB(err:Base.BusinessError) { if (err.code) { console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); } else { @@ -309,7 +311,7 @@ Sets the code and data for this common event. This API uses a promise to return ```ts subscriber.setCodeAndData(1, "publish_data_changed").then(() => { console.info("setCodeAndData"); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -332,7 +334,7 @@ Checks whether this common event is an ordered one. This API uses an asynchronou ```ts // Callback for checking whether the current common event is an ordered one. -function isOrderedCB(err, isOrdered) { +function isOrderedCB(err:Base.BusinessError, isOrdered:boolean) { if (err.code) { console.error(`isOrderedCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { @@ -359,9 +361,9 @@ Checks whether this common event is an ordered one. This API uses a promise to r **Example** ```ts -subscriber.isOrderedCommonEvent().then((isOrdered) => { +subscriber.isOrderedCommonEvent().then((isOrdered:boolean) => { console.info("isOrdered " + JSON.stringify(isOrdered)); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`isOrdered failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -384,7 +386,7 @@ Checks whether this common event is a sticky one. This API uses an asynchronous ```ts // Callback for checking whether the current common event is a sticky one. -function isStickyCB(err, isSticky) { +function isStickyCB(err:Base.BusinessError, isSticky:boolean) { if (err.code) { console.error(`isStickyCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { @@ -411,9 +413,9 @@ Checks whether this common event is a sticky one. This API uses a promise to ret **Example** ```ts -subscriber.isStickyCommonEvent().then((isSticky) => { +subscriber.isStickyCommonEvent().then((isSticky:boolean) => { console.info("isSticky " + JSON.stringify(isSticky)); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`isSticky failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -436,7 +438,7 @@ Aborts this common event. After the abort, the common event is not sent to the n ```ts // Callback for common event aborting. -function abortCB(err) { +function abortCB(err:Base.BusinessError) { if (err.code) { console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { @@ -465,7 +467,7 @@ Aborts this common event. After the abort, the common event is not sent to the n ```ts subscriber.abortCommonEvent().then(() => { console.info("abortCommonEvent"); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -488,7 +490,7 @@ Clears the aborted state of this common event. This API takes effect only for or ```ts // Callback for clearing the aborted state of the current common event. -function clearAbortCB(err) { +function clearAbortCB(err:Base.BusinessError) { if (err.code) { console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { @@ -517,7 +519,7 @@ Clears the aborted state of this common event. This API takes effect only for or ```ts subscriber.clearAbortCommonEvent().then(() => { console.info("clearAbortCommonEvent"); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -540,7 +542,7 @@ Checks whether this common event is in the aborted state. This API takes effect ```ts // Callback for checking whether the current common event is in the aborted state. -function getAbortCB(err, abortEvent) { +function getAbortCB(err:Base.BusinessError, abortEvent:boolean) { if (err.code) { console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { @@ -567,9 +569,9 @@ Checks whether this common event is in the aborted state. This API takes effect **Example** ```ts -subscriber.getAbortCommonEvent().then((abortEvent) => { +subscriber.getAbortCommonEvent().then((abortEvent:boolean) => { console.info("abortCommonEvent " + JSON.stringify(abortEvent)); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -592,7 +594,7 @@ Obtains the subscriber information. This API uses an asynchronous callback to re ```ts // Callback for subscriber information obtaining. -function getCB(err, subscribeInfo) { +function getCB(err:Base.BusinessError, subscribeInfo:CommonEventManager.CommonEventSubscribeInfo) { if (err.code) { console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); } else { @@ -619,9 +621,9 @@ Obtains the subscriber information. This API uses a promise to return the result **Example** ```ts -subscriber.getSubscribeInfo().then((subscribeInfo) => { +subscriber.getSubscribeInfo().then((subscribeInfo:CommonEventManager.CommonEventSubscribeInfo) => { console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -644,7 +646,7 @@ Finishes this common event. This API takes effect only for ordered common events ```ts // Callback for ordered common event finishing. -function finishCB(err) { +function finishCB(err:Base.BusinessError) { if (err.code) { console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { @@ -674,7 +676,7 @@ Finishes this common event. This API takes effect only for ordered common events ```ts subscriber.finishCommonEvent().then(() => { console.info("FinishCommonEvent"); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index 0bd9b716421a85fdc2e28582d2799ced24b12109..0dc717e3b5f35c05502cad7e898740c383e67077 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -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\ | 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\; 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** diff --git a/en/application-dev/reference/apis/js-apis-net-ethernet.md b/en/application-dev/reference/apis/js-apis-net-ethernet.md index 21fdb44e402a4a0cb4a6f39d883522ab84513217..e7aae4ef5ef646af82499c8d3fdfd2bfd53cf905 100644 --- a/en/application-dev/reference/apis/js-apis-net-ethernet.md +++ b/en/application-dev/reference/apis/js-apis-net-ethernet.md @@ -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 (,).| -| httpProxy10+ | [HttpProxy](js-apis-net-connection.md#httpproxy) | No| HTTP proxy of the Ethernet connection. By default, no proxy is configured.| +| httpProxy10+ | [HttpProxy](js-apis-net-connection.md#httpproxy10) | No| HTTP proxy of the Ethernet connection. By default, no proxy is configured.| ## IPSetMode9+ diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index 646f07fc4d30ec6ad4585eacd840a99954b34973..5ab31338dad186152b29dab25f05f1175822902a 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -4,7 +4,7 @@ The **Notification** module provides notification management capabilities, cover > **NOTE** > -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. This module is deprecated since API version 9. > > Notification subscription and unsubscription APIs are available only to system applications. @@ -1460,7 +1460,7 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal | --------------- | ----------------------------------| ---- | -------------------- | | bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application. | | notificationKey | [NotificationKey](#notificationkeydeprecated) | Yes | Notification key. | -| reason | [RemoveReason](#removereason9-deprecated) | Yes | Indicates the reason for deleting a notification. | +| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting a notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1502,7 +1502,7 @@ Removes a notification for a specified bundle. This API uses a promise to return | --------------- | --------------- | ---- | ---------- | | bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application.| | notificationKey | [NotificationKey](#notificationkeydeprecated) | Yes | Notification key. | -| reason | [RemoveReason](#removereason9-deprecated) | Yes | Reason for deleting the notification. | +| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting the notification. | **Example** @@ -1536,8 +1536,8 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | -| hashCode | string | Yes | Unique notification ID. It is the **hashCode** in the [NotificationRequest](#notificationrequest) object of [SubscribeCallbackData](#subscribecallbackdata) of the [onConsume](js-apis-inner-notification-notificationSubscriber.md#onconsume) callback. | -| reason | [RemoveReason](#removereason9-deprecated) | Yes | Indicates the reason for deleting a notification. | +| hashCode | string | Yes | Unique notification ID. It is the **hashCode** in the [NotificationRequest](#notificationrequest) object of [SubscribeCallbackData](#subscribecallbackdata) of the [onConsume](js-apis-inner-notification-notificationSubscriber.md#onconsume) callback.| +| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting a notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1573,7 +1573,7 @@ Removes a notification for a specified bundle. This API uses a promise to return | Name | Type | Mandatory| Description | | -------- | ---------- | ---- | ---------- | | hashCode | string | Yes | Unique notification ID.| -| reason | [RemoveReason](#removereason9-deprecated) | Yes | Reason for deleting the notification. | +| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting the notification. | **Example** @@ -2872,10 +2872,10 @@ Notification.getDeviceRemindType().then((data) => { > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [notificationManager.BundleOption](js-apis-inner-notification-notificationCommonDef.md#bundleoption) instead. -| Name | Type | Read-only| Mandatory| Description | -| ------ | ------ |---- | --- | ------ | -| bundle | string | No | Yes | Bundle information of the application.| -| uid | number | No | No | User ID.| +| Name | Type | Mandatory| Description | +| ------ | ------ | --- | ------ | +| bundle | string | Yes | Bundle information of the application.| +| uid | number | No | User ID.| ## NotificationKeydeprecated @@ -3059,7 +3059,7 @@ Describes the notification request. | classification | string | Yes | Yes | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | | groupName8+| string | Yes | Yes | Notification group name. | | template8+ | [NotificationTemplate](#notificationtemplate8) | Yes | Yes | Notification template. | -| isRemoveAllowed8+ | boolean | Yes | No | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | +| isRemoveAllowed10+ | boolean | Yes | No | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | | source8+ | number | Yes | No | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. | | distributedOption8+ | [DistributedOptions](#distributedoptions8) | Yes | Yes | Distributed notification options. | | deviceId8+ | string | Yes | No | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. | @@ -3203,7 +3203,7 @@ Provides the notification user input. | TYPE_CONTINUOUS | 1 | Continuous notification. | | TYPE_TIMER | 2 | Timed notification. | -## RemoveReason9+ deprecated +## RemoveReason deprecated **System capability**: SystemCapability.Notification.Notification @@ -3211,9 +3211,9 @@ Provides the notification user input. > **NOTE** > -> This API is supported since API version 9 and deprecated since API version 9. You are advised to use [notificationManager.RemoveReason](js-apis-notificationSubscribe.md#removereason) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [notificationManager.RemoveReason](js-apis-notificationSubscribe.md#removereason) instead. | Name | Value | Description | | -------------------- | --- | -------------------- | -| CLICK_REASON_REMOVE9+ | 1 | The notification is removed after a click on it. | -| CANCEL_REASON_REMOVE9+ | 2 | The notification is removed by the user. | +| CLICK_REASON_REMOVE | 1 | The notification is removed after a click on it. | +| CANCEL_REASON_REMOVE | 2 | The notification is removed by the user. | diff --git a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md index 1ca3f7833aadfde7058e24f8231d0e0360d82122..10a7091a75c1e9354921fe46bdbc1ce4bccb1a2e 100644 --- a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md +++ b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md @@ -443,6 +443,90 @@ notificationSubscribe.remove(hashCode, reason).then(() => { console.info("remove success"); }); ``` +## NotificationSubscribe.remove + +remove(hashCodes: Array\, reason: RemoveReason, callback: AsyncCallback\): void + +Removes specified notifications. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +|-----------|-------------------------------| ---- |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| hashCodes | Array\ | Yes | Array of unique notification IDs. It is the **hashCode** in the [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) object of [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata) of the [onConsume](js-apis-inner-notification-notificationSubscriber.md#onConsume) callback.| +| reason | [RemoveReason](#removereason) | Yes | Reason for removing the notification. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +let hashCodes = ['hashCode1', 'hashCode2']; + +function removeCallback(err) { + if (err) { + console.error(`remove failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("remove success"); + } +} +let reason = notificationSubscribe.RemoveReason.CANCEL_REASON_REMOVE; +notificationSubscribe.remove(hashCodes, reason, removeCallback); +``` + +## NotificationSubscribe.remove + +remove(hashCodes: Array\, reason: RemoveReason): Promise\ + +Removes specified notifications. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +|-----------|-------------------------------| ---- |-------------| +| hashCodes | Array\ | Yes | Array of unique notification IDs.| +| reason | [RemoveReason](#removereason) | Yes | Reason for removing the notification. | + +**Error codes** + +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +let hashCodes = ['hashCode1','hashCode2']; +let reason = notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE; +notificationSubscribe.remove(hashCodes, reason).then(() => { + console.info("remove success"); +}); +``` ## NotificationSubscribe.removeAll diff --git a/en/application-dev/reference/apis/js-apis-pointer.md b/en/application-dev/reference/apis/js-apis-pointer.md index 9f949c10e762e34ae641d648d676f0d754c9b52c..39d64c64f8d0f015b44823b5fe87f42f8a06bde2 100644 --- a/en/application-dev/reference/apis/js-apis-pointer.md +++ b/en/application-dev/reference/apis/js-apis-pointer.md @@ -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_CURSOR10+ | 39 | Horizontal text selection|![Horizontal_Text_Cursor.png](./figures/Horizontal_Text_Cursor.png)| +| HORIZONTAL_TEXT_CURSOR10+ | 39 | Horizontal text cursor|![Horizontal_Text_Cursor.png](./figures/Horizontal_Text_Cursor.png)| | CURSOR_CROSS10+ | 40 | Cross cursor|![Cursor_Cross.png](./figures/Cursor_Cross.png)| | CURSOR_CIRCLE10+ | 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.setPointerSize10+ + +setPointerSize(size: number, callback: AsyncCallback<void>): 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<void> | 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.setPointerSize10+ + +setPointerSize(size: number): Promise<void> + +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<void> | 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.setPointerSizeSync10+ + +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.getPointerSize10+ + +getPointerSize(callback: AsyncCallback<number>): 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<number> | 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.getPointerSize10+ + +getPointerSize(): Promise<number> + +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<number> | 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.getPointerSizeSync10+ + +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.setPointerColor10+ + +setPointerColor(color: number, callback: AsyncCallback<void>): 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<void> | 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.setPointerColor10+ + +setPointerColor(color: number): Promise<void> + +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<void> | 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.setPointerColorSync10+ + +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.getPointerColor10+ + +getPointerColor(callback: AsyncCallback<number>): 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<number> | 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.getPointerColor10+ + +getPointerColor(): Promise<number> + +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<number> | 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.getPointerColorSync10+ + +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`])}`); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md index 644759435975c722de9fd274b704ecd01804d2fd..de1e1e04ddfc51d5e24ef783f022ab2f400f09dc 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md @@ -1,8 +1,6 @@ -# @ohos.reminderAgentManager (reminderAgentManager) +# @ohos.reminderAgentManager (Agent-Powered Reminders) -The **reminderAgentManager** module provides APIs for publishing scheduled reminders through the reminder agent. - -You can use the APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits. +The **reminderAgentManager** module provides APIs related to agent-powered reminders. When your application is frozen or exits, the timing and notification functions of your application will be taken over by a system service running in the background. You can use the APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. > **NOTE** > @@ -15,12 +13,15 @@ You can use the APIs to create scheduled reminders for countdown timers, calenda import reminderAgentManager from'@ohos.reminderAgentManager'; ``` - ## reminderAgentManager.publishReminder publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback\): void -Publishes a reminder through the reminder agent. This API uses an asynchronous callback to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). +Publishes a reminder. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API can be called only after the [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8) permission is obtained. **Required permissions**: ohos.permission.PUBLISH_AGENT_REMINDER @@ -28,10 +29,10 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| - | callback | AsyncCallback\ | Yes| Callback used to return the published reminder's ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| reminderReq | [ReminderRequest](#reminderrequest) | Yes| Request used for publishing the reminder.| +| callback | AsyncCallback\ | Yes| Callback used to return the published reminder's ID.| **Error codes** @@ -62,26 +63,29 @@ try { }; ``` - ## reminderAgentManager.publishReminder publishReminder(reminderReq: ReminderRequest): Promise\ -Publishes a reminder through the reminder agent. This API uses a promise to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). +Publishes a reminder. This API uses a promise to return the result. + +> **NOTE** +> +> This API can be called only after the [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8) permission is obtained. **Required permissions**: ohos.permission.PUBLISH_AGENT_REMINDER **System capability**: SystemCapability.Notification.ReminderAgent **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| reminderReq | [ReminderRequest](#reminderrequest) | Yes| Request used for publishing the reminder.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise\ | Promise used to return the published reminder's ID.| +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the published reminder's ID.| **Error codes** @@ -115,7 +119,7 @@ try { cancelReminder(reminderId: number, callback: AsyncCallback\): void -Cancels the reminder with the specified ID. This API uses an asynchronous callback to return the cancellation result. +Cancels a reminder published. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -124,7 +128,7 @@ Cancels the reminder with the specified ID. This API uses an asynchronous callba | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderId | number | Yes| ID of the reminder to cancel.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| callback | AsyncCallback\ | Yes| Callback used to return the result. If the reminder is canceled, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -151,12 +155,11 @@ try { }; ``` - ## reminderAgentManager.cancelReminder cancelReminder(reminderId: number): Promise\ -Cancels the reminder with the specified ID. This API uses a promise to return the cancellation result. +Cancels a reminder published. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -170,7 +173,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Error codes** @@ -199,8 +202,7 @@ try { getValidReminders(callback: AsyncCallback>): void - -Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the reminders. +Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -208,7 +210,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.| +| callback | AsyncCallback\> | Yes| Callback used to return all the valid reminders.| **Error codes** @@ -259,7 +261,7 @@ try { getValidReminders(): Promise\> -Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the reminders. +Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -267,7 +269,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Type| Description| | -------- | -------- | -| Promise\> | Promise used to return an array of all valid reminders set by the current application.| +| Promise\> | Promise used to return all the valid reminders.| **Error codes** @@ -312,12 +314,11 @@ try { }; ``` - ## reminderAgentManager.cancelAllReminders cancelAllReminders(callback: AsyncCallback\): void -Cancels all reminders set by the current application. This API uses an asynchronous callback to return the cancellation result. +Cancels all reminders set by the current application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -325,7 +326,7 @@ Cancels all reminders set by the current application. This API uses an asynchron | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| callback | AsyncCallback\ | Yes| Callback used to return the result. If all the reminders are canceled, **err** is **undefined**. Otherwise, **err** is an error object. | **Error codes** @@ -351,12 +352,11 @@ try { }; ``` - ## reminderAgentManager.cancelAllReminders cancelAllReminders(): Promise\ -Cancels all reminders set by the current application. This API uses a promise to return the cancellation result. +Cancels all reminders set by the current application. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -364,7 +364,7 @@ Cancels all reminders set by the current application. This API uses a promise to | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Error codes** @@ -401,8 +401,8 @@ Adds a notification slot. This API uses an asynchronous callback to return the r | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot. Only the type can be set.| +| callback | AsyncCallback\ | Yes| Callback used to return the result. If the notification slot is added, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** @@ -438,13 +438,13 @@ Adds a notification slot. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.| +| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot. Only the type can be set.| **Return value** | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Example** @@ -470,7 +470,7 @@ try { removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback\): void -Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result. +Removes a notification slot. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -479,7 +479,7 @@ Removes a notification slot of a specified type. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| callback | AsyncCallback\ | Yes| Callback used to return the result. If the notification slot is removed, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** @@ -504,7 +504,7 @@ try { removeNotificationSlot(slotType: notification.SlotType): Promise\ -Removes a notification slot of a specified type. This API uses a promise to return the result. +Removes a notification slot. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -518,7 +518,7 @@ Removes a notification slot of a specified type. This API uses a promise to retu | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Example** @@ -538,7 +538,7 @@ try { ## ActionButtonType -Enumerates button types. +Enumerates the button types. **System capability**: SystemCapability.Notification.ReminderAgent @@ -551,7 +551,7 @@ Enumerates button types. ## ReminderType -Enumerates reminder types. +Enumerates the reminder types. **System capability**: SystemCapability.Notification.ReminderAgent @@ -564,8 +564,7 @@ Enumerates reminder types. ## ActionButton -Defines a button displayed for the reminder in the notification panel. - +Defines the button on the reminder displayed. **System capability**: SystemCapability.Notification.ReminderAgent @@ -573,7 +572,7 @@ Defines a button displayed for the reminder in the notification panel. | -------- | -------- | -------- | -------- | | title | string | Yes| Text on the button.| | type | [ActionButtonType](#actionbuttontype) | Yes| Button type.| -| wantAgent10+ | [WantAgent](#wantagent) | No| Ability information that is displayed after the button is clicked.
**System API**: This is a system API and cannot be called by third-party applications.| +| wantAgent10+ | [WantAgent](#wantagent) | No| Information about the ability that is displayed after the button is clicked.
**System API**: This is a system API and cannot be called by third-party applications.| ## WantAgent @@ -592,19 +591,19 @@ Defines the information about the redirected-to ability. ## MaxScreenWantAgent -Provides the information about the target package and ability to start automatically when the reminder is displayed in full-screen mode. This API is reserved. +Provides the information about the ability that is started automatically and displayed in full-screen mode when the reminder arrives. This API is reserved. **System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the package that is automatically started when the reminder arrives and the device is not in use.| -| abilityName | string | Yes| Name of the ability that is automatically started when the reminder arrives and the device is not in use.| +| pkgName | string | Yes| Name of the target package. (If the device is in use, only a notification banner is displayed.)| +| abilityName | string | Yes| Name of the target ability. (If the device is in use, only a notification banner is displayed.)| ## ReminderRequest -Defines the reminder to publish. +Defines the request for publishing a reminder. **System capability**: SystemCapability.Notification.ReminderAgent @@ -613,7 +612,7 @@ Defines the reminder to publish. | reminderType | [ReminderType](#remindertype) | Yes| Type of the reminder.| | actionButton | [ActionButton](#actionbutton) | No| Buttons displayed for the reminder in the notification panel.
- For common applications, a maximum of two buttons are supported.
- For system applications, a maximum of two buttons are supported in API version 9, and a maximum of three buttons are supported in API version 10 and later versions.| | wantAgent | [WantAgent](#wantagent) | No| Information about the ability that is redirected to when the reminder is clicked.| -| maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.| +| maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | No| Information about the ability that is started automatically and displayed in full-screen mode when the reminder arrives. If the device is in use, only a notification banner is displayed.
This API is reserved.| | ringDuration | number | No| Ringing duration, in seconds. The default value is **1**.| | snoozeTimes | number | No| Number of reminder snooze times. The default value is **0**.| | timeInterval | number | No| Reminder snooze interval, in seconds. The minimum value is 5 minutes.| @@ -623,8 +622,8 @@ Defines the reminder to publish. | snoozeContent | string | No| Content to be displayed when the reminder is snoozing.| | notificationId | number | No| Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one.| | slotType | [notification.SlotType](js-apis-notificationManager.md#slottype) | No| Type of the slot used by the reminder.| -| tapDismissed10+ | boolean | No| Whether the notification is automatically cleared. The value is the same as that of [NotificationRequest.tapDismissed](js-apis-inner-notification-notificationRequest.md#notificationrequest).| -| autoDeletedTime10+ | number | No| Time when the notification is automatically cleared. The value is the same as that of [NotificationRequest.autoDeletedTime](js-apis-inner-notification-notificationRequest.md#notificationrequest).| +| tapDismissed10+ | boolean | No| Whether the reminder is automatically cleared. For details, see [NotificationRequest.tapDismissed](js-apis-inner-notification-notificationRequest.md#notificationrequest). | +| autoDeletedTime10+ | number | No| Time when the reminder is automatically cleared. For details, see [NotificationRequest.autoDeletedTime](js-apis-inner-notification-notificationRequest.md#notificationrequest).| ## ReminderRequestCalendar diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md index 40cb3dc087b7b7a756a602925699597ec557c294..d4807f0517fc537ac7283d612c856dae10c235d7 100644 --- a/en/application-dev/reference/apis/js-apis-resource-manager.md +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -22,10 +22,10 @@ For details about how to reference context in the stage model, see [Context in t import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { - let context = this.context; - let resourceManager = context.resourceManager; - } + onWindowStageCreate(windowStage) { + let context = this.context; + let resourceManager = context.resourceManager; + } } ``` @@ -48,17 +48,17 @@ Obtains the **ResourceManager** object of this application. This API uses an asy **Example** ```js resourceManager.getResourceManager((error, mgr) => { + if (error != null) { + console.log("error is " + error); + return; + } + mgr.getStringValue(0x1000000, (error, value) => { if (error != null) { - console.log("error is " + error); - return; + console.log("error is " + error); + } else { + let str = value; } - mgr.getStringValue(0x1000000, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let str = value; - } - }); + }); }); ``` > **NOTE**
In the sample code, **0x1000000** indicates the resource ID, which can be found in the compiled **ResourceTable.txt** file. @@ -107,15 +107,15 @@ Obtains the **ResourceManager** object of this application. This API uses a prom **Example** ```js resourceManager.getResourceManager().then(mgr => { - mgr.getStringValue(0x1000000, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let str = value; - } - }); + mgr.getStringValue(0x1000000, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } + }); }).catch(error => { - console.log("error is " + error); + console.log("error is " + error); }); ``` > **NOTE**
In the sample code, **0x1000000** indicates the resource ID, which can be found in the compiled **ResourceTable.txt** file. @@ -150,7 +150,6 @@ Obtains the **ResourceManager** object of an application based on the specified }); ``` - ## resourceManager.getSystemResourceManager10+ 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; + let str = value; }).catch(error => { - console.log("systemResourceManager getStringValue promise error is " + 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. | ## RawFileDescriptor8+ @@ -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**. -### getStringValue9+ +### getStringSync9+ -getStringValue(resId: number, callback: AsyncCallback<string>): 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<string> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| 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. | -| 9001002 | If the resource not found by resId. | -| 9001006 | If the resource re-ref too much. | +| 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; - } - }); - } catch (error) { - console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`); - } + try { + this.context.resourceManager.getStringSync($r('app.string.test').id); + } catch (error) { + console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`); + } ``` +### getStringSync10+ -### getStringValue9+ - -getStringValue(resId: number): Promise<string> +getStringSync(resId: number, ...args: Array): 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 | No | Arguments for formatting strings.
Supported arguments:
%d, %f, %s, and %%
Note: **%%** is used to translate **%**.
Example: **%%d** is translated into the **%d** string.| **Return value** -| Type | Description | -| --------------------- | ----------- | -| Promise<string> | Promise used to return the result.| +| Type | Description | +| ------ | ---------------------------- | +| 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. | +| -------- | ----------------------------------------------- | +| 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}.`); } ``` +### getStringSync9+ -### getStringValue9+ - -getStringValue(resource: Resource, callback: AsyncCallback<string>): 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 @@ -398,10 +392,15 @@ 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<string> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| resource | [Resource](#resource9) | Yes | Resource object.| + +**Return value** + +| Type | Description | +| ------ | ---------------- | +| string | String corresponding to the specified resource object.| **Error codes** @@ -416,30 +415,22 @@ 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.string.test').id + bundleName: "com.example.myapplication", + moduleName: "entry", + 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}.`); } - ``` +### getStringSync10+ -### getStringValue9+ - -getStringValue(resource: Resource): Promise<string> +getStringSync(resource: Resource, ...args: Array): 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 | No | Arguments for formatting strings.
Supported arguments:
%d, %f, %s, and %%
Note: **%%** is used to translate **%**.
Example: **%%d** is translated into the **%d** string.| **Return value** -| Type | Description | -| --------------------- | ---------------- | -| Promise<string> | Promise used to return the result.| +| Type | Description | +| ------ | ---------------------------- | +| string | Formatted string.| **Error codes** @@ -466,40 +458,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. | +| 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 + bundleName: "com.example.myapplication", + moduleName: "entry", + 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}.`); } - ``` - + ``` -### getStringArrayValue9+ +### getStringByNameSync9+ -getStringArrayValue(resId: number, callback: AsyncCallback<Array<string>>): 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<Array<string>> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| 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}.`); } ``` +### getStringByNameSync10+ -### getStringArrayValue9+ - -getStringArrayValue(resId: number): Promise<Array<string>> +getStringByNameSync(resName: string, ...args: Array): 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.| +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| +| args | Array | No | Arguments for formatting strings.
Supported arguments:
%d, %f, %s, and %%
Note: **%%** is used to translate **%**.
Example: **%%d** is translated into the **%d** string.| **Return value** -| Type | Description | -| ---------------------------------- | ------------- | -| Promise<Array<string>> | Promise used to return the result.| +| Type | Description | +| ------ | ---------------------------- | +| 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}.`); } - ``` + ``` -### getStringArrayValue9+ +### getStringValue9+ -getStringArrayValue(resource: Resource, callback: AsyncCallback<Array<string>>): void +getStringValue(resId: number, callback: AsyncCallback<string>): 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<Array<string>> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------- | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<string> | 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. | -| 9001002 | If the resource not found by resId. | -| 9001006 | If the resource re-ref too much. | +| 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); + 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}.`); } ``` -### getStringArrayValue9+ +### getStringValue9+ -getStringArrayValue(resource: Resource): Promise<Array<string>> +getStringValue(resId: number): Promise<string> -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.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| **Return value** -| Type | Description | -| ---------------------------------- | ------------------ | -| Promise<Array<string>> | Promise used to return the result.| +| Type | Description | +| --------------------- | ----------- | +| Promise<string> | 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}.`); } ``` -### getMediaContent9+ +### getStringValue9+ -getMediaContent(resId: number, callback: AsyncCallback<Uint8Array>): void +getStringValue(resource: Resource, callback: AsyncCallback<string>): 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<Uint8Array> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------- | +| resource | [Resource](#resource9) | Yes | Resource object. | +| callback | AsyncCallback<string> | 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) => { - if (error != null) { - console.log("error is " + error); - } else { - let media = value; - } + this.context.resourceManager.getStringValue(resource, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + 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}.`); } ``` -### getMediaContent10+ +### getStringValue9+ -getMediaContent(resId: number, density: number, callback: AsyncCallback<Uint8Array>): void +getStringValue(resource: Resource): Promise<string> -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<Uint8Array> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| resource | [Resource](#resource9) | Yes | Resource object.| + +**Return value** + +| Type | Description | +| --------------------- | ---------------- | +| Promise<string> | 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) => { - if (error != null) { - console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); - } else { - let media = value; - } + this.context.resourceManager.getStringValue(resource).then(value => { + let str = value; + }).catch(error => { + console.log("getStringValue promise error is " + error); }); } catch (error) { - console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getStringValue failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaContent9+ +### getStringByName9+ -getMediaContent(resId: number): Promise<Uint8Array> +getStringByName(resName: string, callback: AsyncCallback<string>): void -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 an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | ---- | ----- | -| resId | number | Yes | Resource ID.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------- | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<string> | 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.log("error is " + error); + } else { + let str = value; + } + }); + } catch (error) { + console.error(`callback getStringByName failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### getStringByName9+ + +getStringByName(resName: string): Promise<string> + +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 | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| **Return value** -| Type | Description | -| ------------------------- | -------------- | -| Promise<Uint8Array> | Promise used to return the result.| +| Type | Description | +| --------------------- | ---------- | +| Promise<string> | 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; - }).catch(error => { - console.log("getMediaContent promise error is " + error); - }); + this.context.resourceManager.getStringByName("test").then(value => { + let str = value; + }).catch(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}.`); } ``` -### getMediaContent10+ +### getStringArrayValueSync10+ -getMediaContent(resId: number, density: number): Promise<Uint8Array> +getStringArrayValueSync(resId: number): Array<string> -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<Uint8Array> | Promise used to return the result.| +| Type | Description | +| --------------------- | ----------- | +| Array<string> | 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}.`); } ``` -### getMediaContent9+ +### getStringArrayValueSync10+ -getMediaContent(resource: Resource, callback: AsyncCallback<Uint8Array>): void +getStringArrayValueSync(resource: Resource): Array<string> -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 @@ -843,10 +868,15 @@ 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<Uint8Array> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resource | [Resource](#resource9) | Yes | Resource object.| + +**Return value** + +| Type | Description | +| --------------------- | ----------- | +| Array<string> | 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 + bundleName: "com.example.myapplication", + moduleName: "entry", + 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}.`); } ``` -### getMediaContent10+ +### getStringArrayValue9+ -getMediaContent(resource: Resource, density: number, callback: AsyncCallback<Uint8Array>): void +getStringArrayValue(resId: number, callback: AsyncCallback<Array<string>>): 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<Uint8Array> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------- | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<Array<string>> | 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) => { - if (error != null) { - console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); - } else { - let media = value; - } + this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + 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}.`); } ``` -### getMediaContent9+ +### getStringArrayValue9+ -getMediaContent(resource: Resource): Promise<Uint8Array> +getStringArrayValue(resId: number): Promise<Array<string>> -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.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| **Return value** -| Type | Description | -| ------------------------- | ------------------- | -| Promise<Uint8Array> | Promise used to return the result.| +| Type | Description | +| ---------------------------------- | ------------- | +| Promise<Array<string>> | 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}.`); } ``` -### getMediaContent10+ +### getStringArrayValue9+ -getMediaContent(resource: Resource, density: number): Promise<Uint8Array> +getStringArrayValue(resource: Resource, callback: AsyncCallback<Array<string>>): 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 @@ -985,16 +997,10 @@ 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<Uint8Array> | Promise used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------- | +| resource | [Resource](#resource9) | Yes | Resource object. | +| callback | AsyncCallback<Array<string>> | 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 + bundleName: "com.example.myapplication", + moduleName: "entry", + 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}.`); } ``` -### getMediaContentBase649+ +### getStringArrayValue9+ -getMediaContentBase64(resId: number, callback: AsyncCallback<string>): void +getStringArrayValue(resource: Resource): Promise<Array<string>> -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<string> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| resource | [Resource](#resource9) | Yes | Resource object.| + +**Return value** + +| Type | Description | +| ---------------------------------- | ------------------ | +| Promise<Array<string>> | 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}.`); } ``` -### getMediaContentBase6410+ +### getStringArrayByName9+ -getMediaContentBase64(resId: number, density: number, callback: AsyncCallback<string>): void +getStringArrayByName(resName: string, callback: AsyncCallback<Array<string>>): 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<string> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------- | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<Array<string>> | 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) => { - if (error != null) { - console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); - } else { - let media = value; - } - }); + this.context.resourceManager.getStringArrayByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + 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}.`); } ``` -### getMediaContentBase649+ +### getStringArrayByName9+ -getMediaContentBase64(resId: number): Promise<string> +getStringArrayByName(resName: string): Promise<Array<string>> -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.| +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| **Return value** -| Type | Description | -| --------------------- | -------------------- | -| Promise<string> | Promise used to return the result.| +| Type | Description | +| ---------------------------------- | ------------ | +| Promise<Array<string>> | 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}.`); } ``` -### getMediaContentBase6410+ +### getPluralStringValueSync10+ -getMediaContentBase64(resId: number, density: number): Promise<string> +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<string> | Promise used to return the result.| +| Type | Description | +| -------- | ----------- | +| 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}.`); } ``` -### getMediaContentBase649+ +### getPluralStringValueSync10+ -getMediaContentBase64(resource: Resource, callback: AsyncCallback<string>): 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 @@ -1199,10 +1217,16 @@ 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<string> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| 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 + bundleName: "com.example.myapplication", + moduleName: "entry", + 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}.`); } ``` -### getMediaContentBase6410+ +### getPluralStringValue9+ -getMediaContentBase64(resource: Resource, density: number, callback: AsyncCallback<string>): void +getPluralStringValue(resId: number, num: number, callback: AsyncCallback<string>): 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. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------------- | +| resId | number | Yes | Resource ID. | +| num | number | Yes | Number. | | callback | AsyncCallback<string> | Yes | Callback used to return the result.| **Error codes** @@ -1259,48 +1276,84 @@ 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) => { - if (error != null) { - console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); - } else { - let media = value; - } + this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + 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}.`); } ``` -### getMediaContentBase649+ +### getPluralStringValue9+ -getMediaContentBase64(resource: Resource): Promise<string> +getPluralStringValue(resId: number, num: number): Promise<string> -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.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| +| num | number | Yes | Number. | **Return value** | Type | Description | | --------------------- | ------------------------- | -| Promise<string> | Promise used to return the result.| +| Promise<string> | 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. | +| 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}.`); + } + ``` + +### getPluralStringValue9+ + +getPluralStringValue(resource: Resource, num: number, callback: AsyncCallback<string>): 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<string> | Yes | Callback used to return the result.| **Error codes** @@ -1310,30 +1363,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.media.test').id + bundleName: "com.example.myapplication", + moduleName: "entry", + 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}.`); } ``` -### getMediaContentBase6410+ +### getPluralStringValue9+ -getMediaContentBase64(resource: Resource, density: number): Promise<string> +getPluralStringValue(resource: Resource, num: number): Promise<string> -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,13 +1400,13 @@ 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<string> | Promise used to return the result.| +| Type | Description | +| --------------------- | ------------------------------ | +| Promise<string> | Promise used to return the result.| **Error codes** @@ -1360,159 +1416,178 @@ 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 + bundleName: "com.example.myapplication", + moduleName: "entry", + 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 +### getPluralStringByName9+ -getConfiguration(callback: AsyncCallback<Configuration>): void +getPluralStringByName(resName: string, num: number, callback: AsyncCallback<string>): 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<[Configuration](#configuration)> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ----------------------------- | +| resName | string | Yes | Resource name. | +| num | number | Yes | Number. | +| callback | AsyncCallback<string> | 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}.`); } ``` +### getPluralStringByName9+ -### getConfiguration - -getConfiguration(): Promise<Configuration> +getPluralStringByName(resName: string, num: number): Promise<string> -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<[Configuration](#configuration)> | Promise used to return the result.| +| Type | Description | +| --------------------- | ---------------------- | +| Promise<string> | 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}.`); } ``` +### getMediaContentSync10+ -### getDeviceCapability - -getDeviceCapability(callback: AsyncCallback<DeviceCapability>): 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<[DeviceCapability](#devicecapability)> | 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 +| 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.| -getDeviceCapability(): Promise<DeviceCapability> +**Return value** -Obtains the device capability. This API uses a promise to return the result. +| Type | Description | +| -------- | ----------- | +| Uint8Array | Content of the media file corresponding to the specified resource ID.| -**System capability**: SystemCapability.Global.ResourceManager +**Error codes** -**Return value** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). -| Type | Description | -| ---------------------------------------- | ------------------- | -| Promise<[DeviceCapability](#devicecapability)> | Promise used to return the result.| +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **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); - }); + this.context.resourceManager.getMediaContentSync($r('app.media.test').id); // 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($r('app.media.test').id, 120); // Specified screen density + } catch (error) { + console.error(`getMediaContentSync failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getPluralStringValue9+ +### getMediaContentSync10+ -getPluralStringValue(resId: number, num: number, callback: AsyncCallback<string>): void +getMediaContentSync(resource: Resource, density?: number): Uint8Array -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 (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 | -| -------- | --------------------------- | ---- | ------------------------------- | -| resId | number | Yes | Resource ID. | -| num | number | Yes | Number. | -| callback | AsyncCallback<string> | Yes | Callback used to return the result.| +| 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 | +| --------------------- | ----------- | +| Uint8Array | Content of the media file corresponding to the specified resource object| **Error codes** @@ -1522,44 +1597,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 + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.test').id + }; try { - this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let str = value; - } - }); + this.context.resourceManager.getMediaContentSync(resource); // Default screen density } catch (error) { - console.error(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`); + 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}.`); + } + ``` -### getPluralStringValue9+ +### getMediaContent9+ -getPluralStringValue(resId: number, num: number): Promise<string> +getMediaContent(resId: number, callback: AsyncCallback<Uint8Array>): 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 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<string> | Promise used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------------ | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| **Error codes** @@ -1569,38 +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).then(value => { - let str = value; - }).catch(error => { - console.log("getPluralStringValue promise error is " + error); + this.context.resourceManager.getMediaContent($r('app.media.test').id, (error, value) => { + if (error != null) { + console.log("error is " + error); + } 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}.`); } ``` -### getPluralStringValue9+ +### getMediaContent10+ -getPluralStringValue(resource: Resource, num: number, callback: AsyncCallback<string>): void +getMediaContent(resId: number, density: number, callback: AsyncCallback<Uint8Array>): 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. +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 -**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<string> | Yes | Callback used to return the result.| +| 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<Uint8Array> | Yes | Callback used to return the result.| **Error codes** @@ -1610,50 +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 - 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, 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(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getPluralStringValue9+ +### getMediaContent9+ -getPluralStringValue(resource: Resource, num: number): Promise<string> +getMediaContent(resId: number): Promise<Uint8Array> -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 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. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| **Return value** -| Type | Description | -| --------------------- | ------------------------------ | -| Promise<string> | Promise used to return the result.| +| Type | Description | +| ------------------------- | -------------- | +| Promise<Uint8Array> | Promise used to return the result.| **Error codes** @@ -1663,41 +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).then(value => { - let str = value; + this.context.resourceManager.getMediaContent($r('app.media.test').id).then(value => { + let media = value; }).catch(error => { - console.log("getPluralStringValue promise error is " + error); + console.log("getMediaContent promise error is " + error); }); } 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}.`); } ``` +### getMediaContent10+ -### getRawFileContent9+ - -getRawFileContent(path: string, callback: AsyncCallback<Uint8Array>): void +getMediaContent(resId: number, density: number): Promise<Uint8Array> -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 (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 **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | ---- | ----------------------- | -| path | string | Yes | Path of the raw file. | -| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| +| 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<Uint8Array> | Promise used to return the result.| **Error codes** @@ -1705,42 +1766,38 @@ 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 try { - this.context.resourceManager.getRawFileContent("test.xml", (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let rawFile = value; - } + 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}.`); }); } catch (error) { - console.error(`callback getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getRawFileContent9+ +### getMediaContent9+ -getRawFileContent(path: string): Promise<Uint8Array> +getMediaContent(resource: Resource, callback: AsyncCallback<Uint8Array>): 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 corresponding to the specified resource object. 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.| +**Model restriction**: This API can be used only in the stage model. -**Return value** +**Parameters** -| Type | Description | -| ------------------------- | ----------- | -| Promise<Uint8Array> | Promise used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------------ | +| resource | [Resource](#resource9) | Yes | Resource object. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| **Error codes** @@ -1748,36 +1805,46 @@ 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").then(value => { - let rawFile = value; - }).catch(error => { - console.log("getRawFileContent promise error is " + error); + this.context.resourceManager.getMediaContent(resource, (error, value) => { + if (error != null) { + console.log("error is " + error); + } 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}.`); } ``` +### getMediaContent10+ -### getRawFd9+ - -getRawFd(path: string, callback: AsyncCallback<RawFileDescriptor>): void +getMediaContent(resource: Resource, density: number, callback: AsyncCallback<Uint8Array>): void -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 (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. | -| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | Yes | Callback used to return the result.| +| 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<Uint8Array> | Yes | Callback used to return the result.| **Error codes** @@ -1785,44 +1852,50 @@ 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, 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(`callback getRawFd failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getRawFd9+ +### getMediaContent9+ -getRawFd(path: string): Promise<RawFileDescriptor> +getMediaContent(resource: Resource): Promise<Uint8Array> -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 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.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| resource | [Resource](#resource9) | Yes | Resource object.| **Return value** -| Type | Description | -| ---------------------------------------- | ------------------- | -| Promise<[RawFileDescriptor](#rawfiledescriptor8)> | Promise used to return the result.| +| Type | Description | +| ------------------------- | ------------------- | +| Promise<Uint8Array> | Promise used to return the result.| **Error codes** @@ -1830,37 +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").then(value => { - 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(`promise getRawFd error error code: ${error.code}, message: ${error.message}.`); + console.log("getMediaContent promise error is " + error); }); } 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}.`); } ``` -### getRawFileList10+ +### getMediaContent10+ -getRawFileList(path: string, callback: AsyncCallback<Array\>): void; +getMediaContent(resource: Resource, density: number): Promise<Uint8Array> -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 (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 **rawfile** folder. | -| callback | AsyncCallback<Array\> | Yes| Callback used to return the result.| +| 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<Uint8Array> | Promise used to return the result.| **Error codes** @@ -1868,42 +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 - 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; - } + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.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}.`); }); } catch (error) { - console.error(`callback getRawFileList failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getRawFileList10+ +### getMediaByName9+ -getRawFileList(path: string): Promise<Array\> +getMediaByName(resName: string, callback: AsyncCallback<Uint8Array>): 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 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<Array\> | List of files in the **rawfile** folder.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------------ | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| **Error codes** @@ -1911,35 +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("").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", (error, value) => { + if (error != null) { + console.log("error is " + error); + } 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}.`); } ``` -### closeRawFd9+ +### getMediaByName10+ -closeRawFd(path: string, callback: AsyncCallback<void>): void +getMediaByName(resName: string, density: number, callback: AsyncCallback<Uint8Array>): void -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 (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 raw file.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| 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<Uint8Array> | Yes | Callback used to return the result.| **Error codes** @@ -1947,41 +2035,43 @@ 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", 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(`callback closeRawFd failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`); } - ``` -### closeRawFd9+ +### getMediaByName9+ -closeRawFd(path: string): Promise<void> +getMediaByName(resName: string): Promise<Uint8Array> -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 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.| +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| **Return value** -| Type | Description | -| ------------------- | ---- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------------- | ------------- | +| Promise<Uint8Array> | Promise used to return the result.| **Error codes** @@ -1989,97 +2079,85 @@ 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").then(value => { + let media = value; }).catch(error => { - console.log("closeRawFd promise error is " + error); + console.log("getMediaByName promise error is " + error); }); } 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}.`) } ``` -### release7+ +### getMediaByName10+ -release() +getMediaByName(resName: string, density: number): Promise<Uint8Array> -Releases a created **resourceManager** object. +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 -**Example** - ```ts - try { - this.context.resourceManager.release(); - } catch (error) { - console.error("release error is " + error); - } - ``` +**Parameters** -### getStringByName9+ +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | -getStringByName(resName: string, callback: AsyncCallback<string>): void +**Return value** -Obtains the string corresponding to the specified resource name. This API uses an asynchronous callback to return the result. +| Type | Description | +| ------------------------- | ------------- | +| Promise<Uint8Array> | Promise used to return the result.| -**System capability**: SystemCapability.Global.ResourceManager +**Error codes** -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | --------------- | -| resName | string | Yes | Resource name. | -| callback | AsyncCallback<string> | 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). +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.log("error is " + error); - } else { - let string = value; - } + this.context.resourceManager.getMediaByName("test", 120).then(value => { + let media = value; + }).catch(error => { + console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`); }); } catch (error) { - console.error(`callback getStringByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getStringByName9+ +### getMediaContentBase64Sync10+ -getStringByName(resName: string): Promise<string> +getMediaContentBase64Sync(resId: number, density?: number): string -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 (with the default or specified screen density) corresponding to the specified resource ID. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | ---- | -| resName | string | Yes | Resource name.| +| 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 | -| --------------------- | ---------- | -| Promise<string> | Promise used to return the result.| +| Type | Description | +| -------- | ----------- | +| string | Base64 code of the image corresponding to the specified resource ID.| **Error codes** @@ -2087,82 +2165,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. | -| 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.getMediaContentBase64Sync($r('app.media.test').id); // Default screen density } catch (error) { - console.error(`promise getStringByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getMediaContentBase64Sync failed, error code: ${error.code}, message: ${error.message}.`); } - ``` - -### getStringArrayByName9+ - -getStringArrayByName(resName: string, callback: AsyncCallback<Array<string>>): void - -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 | -| -------- | ---------------------------------------- | ---- | ----------------- | -| resName | string | Yes | Resource name. | -| callback | AsyncCallback<Array<string>> | 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.getStringArrayByName("test", (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let strArray = value; - } - }); + this.context.resourceManager.getMediaContentBase64Sync($r('app.media.test').id, 120); // Specified screen density } catch (error) { - console.error(`callback getStringArrayByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getMediaContentBase64Sync failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getStringArrayByName9+ +### getMediaContentBase64Sync10+ -getStringArrayByName(resName: string): Promise<Array<string>> +getMediaContentBase64Sync(resource: Resource, density?: number): string -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 (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.| +| 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<Array<string>> | Promise used to return the result.| +| Type | Description | +| --------------------- | ----------- | +| string | Base64 code of the media file corresponding to the specified resource object.| **Error codes** @@ -2170,37 +2212,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 + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.test').id + }; try { - this.context.resourceManager.getStringArrayByName("test").then(value => { - let strArray = value; - }).catch(error => { - console.log("getStringArrayByName promise error is " + error); - }); + this.context.resourceManager.getMediaContentBase64Sync(resource); // Default screen density } catch (error) { - console.error(`promise getStringArrayByName failed, error code: ${error.code}, message: ${error.message}.`); + 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(`getMediaContentBase64Sync failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaByName9+ +### getMediaContentBase649+ -getMediaByName(resName: string, callback: AsyncCallback<Uint8Array>): void +getMediaContentBase64(resId: number, callback: AsyncCallback<string>): 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 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. | -| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------ | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<string> | Yes | Callback used to return the result.| **Error codes** @@ -2208,39 +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. | +| 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 { - let media = value; - } + 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(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaByName10+ +### getMediaContentBase6410+ -getMediaByName(resName: string, density: number, callback: AsyncCallback<Uint8Array>): void +getMediaContentBase64(resId: number, density: number, callback: AsyncCallback<string>): 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 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. | +| 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<Uint8Array> | Yes | Callback used to return the result.| +| callback | AsyncCallback<string> | Yes | Callback used to return the result.| **Error codes** @@ -2248,43 +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. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **Example** ```ts 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; - } + this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 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.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaByName9+ +### getMediaContentBase649+ -getMediaByName(resName: string): Promise<Uint8Array> +getMediaContentBase64(resId: number): Promise<string> -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 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.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| **Return value** -| Type | Description | -| ------------------------- | ------------- | -| Promise<Uint8Array> | Promise used to return the result.| +| Type | Description | +| --------------------- | -------------------- | +| Promise<string> | Promise used to return the result.| **Error codes** @@ -2292,42 +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. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **Example** ```ts try { - this.context.resourceManager.getMediaByName("test").then(value => { - let media = value; + this.context.resourceManager.getMediaContentBase64($r('app.media.test').id).then(value => { + let media = value; }).catch(error => { - console.log("getMediaByName promise error is " + error); + 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}.`); } ``` -### getMediaByName10+ +### getMediaContentBase6410+ -getMediaByName(resName: string, density: number): Promise<Uint8Array> +getMediaContentBase64(resId: number, density: number): Promise<string> -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 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.| +| 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<Uint8Array> | Promise used to return the result.| +| Type | Description | +| --------------------- | -------------------- | +| Promise<string> | Promise used to return the result.| **Error codes** @@ -2335,35 +2383,37 @@ 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", 120).then(value => { - let media = value; + this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120).then(value => { + let media = value; }).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}.`); }); } 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}.`); } ``` -### getMediaBase64ByName9+ +### getMediaContentBase649+ -getMediaBase64ByName(resName: string, callback: AsyncCallback<string>): void +getMediaContentBase64(resource: Resource, callback: AsyncCallback<string>): void -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 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. | +| resource | [Resource](#resource9) | Yes | Resource object. | | callback | AsyncCallback<string> | Yes | Callback used to return the result.| **Error codes** @@ -2372,37 +2422,44 @@ 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.getMediaBase64ByName("test", (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let media = value; - } + this.context.resourceManager.getMediaContentBase64(resource, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } }); } catch (error) { - console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaBase64ByName10+ +### getMediaContentBase6410+ -getMediaBase64ByName(resName: string, density: number, callback: AsyncCallback<string>): void +getMediaContentBase64(resource: Resource, density: number, callback: AsyncCallback<string>): void -Obtains the Base64 code of an image with the screen density 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 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. | +| resource | [Resource](#resource9) | Yes | Resource object. | | [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | | callback | AsyncCallback<string> | Yes | Callback used to return the result.| @@ -2412,42 +2469,49 @@ 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.getMediaBase64ByName("test", 120, (error, value) => { - if (error != null) { - console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); - } else { - let media = 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.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaBase64ByName9+ +### getMediaContentBase649+ -getMediaBase64ByName(resName: string): Promise<string> +getMediaContentBase64(resource: Resource): Promise<string> -Obtains the Base64 code of the image 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.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| resource | [Resource](#resource9) | Yes | Resource object.| **Return value** -| Type | Description | -| --------------------- | ------------------- | +| Type | Description | +| --------------------- | ------------------------- | | Promise<string> | Promise used to return the result.| **Error codes** @@ -2456,41 +2520,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. | +| 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.getMediaBase64ByName("test").then(value => { - let media = value; + this.context.resourceManager.getMediaContentBase64(resource).then(value => { + let media = value; }).catch(error => { - console.log("getMediaBase64ByName promise error is " + error); + console.log("getMediaContentBase64 promise error is " + error); }); } catch (error) { - console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaBase64ByName10+ +### getMediaContentBase6410+ -getMediaBase64ByName(resName: string, density: number): Promise<string> +getMediaContentBase64(resource: Resource, density: number): Promise<string> -Obtains the Base64 code of an image with the screen density 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 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.| +| 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 | -| --------------------- | ------------------- | +| Type | Description | +| --------------------- | ------------------------- | | Promise<string> | Promise used to return the result.| **Error codes** @@ -2499,36 +2570,40 @@ 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.getMediaBase64ByName("test", 120).then(value => { - let media = value; + this.context.resourceManager.getMediaContentBase64(resource, 120).then(value => { + let media = value; }).catch(error => { - console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); }); } catch (error) { - console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getPluralStringByName9+ +### getMediaBase64ByName9+ -getPluralStringByName(resName: string, num: number, callback: AsyncCallback<string>): void +getMediaBase64ByName(resName: string, callback: AsyncCallback<string>): void -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 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. | -| num | number | Yes | Number. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------ | +| resName | string | Yes | Resource name. | | callback | AsyncCallback<string> | Yes | Callback used to return the result.| **Error codes** @@ -2539,44 +2614,37 @@ 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.getPluralStringByName("test", 1, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let str = value; - } + this.context.resourceManager.getMediaBase64ByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } }); } catch (error) { - console.error(`callback getPluralStringByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); } - ``` -### getPluralStringByName9+ +### getMediaBase64ByName10+ -getPluralStringByName(resName: string, num: number): Promise<string> +getMediaBase64ByName(resName: string, density: number, callback: AsyncCallback<string>): void -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 Base64 code of an image with the screen density 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.| -| num | number | Yes | Number. | - -**Return value** - -| Type | Description | -| --------------------- | ---------------------- | -| Promise<string> | Promise used to return the result.| +| 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<string> | Yes | Callback used to return the result.| **Error codes** @@ -2586,40 +2654,41 @@ 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.getPluralStringByName("test", 1).then(value => { - let str = value; - }).catch(error => { - console.log("getPluralStringByName promise error is " + error); + this.context.resourceManager.getMediaBase64ByName("test", 120, (error, value) => { + if (error != null) { + console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); + } else { + let media = value; + } }); } catch (error) { - console.error(`promise getPluralStringByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getStringSync9+ +### getMediaBase64ByName9+ -getStringSync(resId: number): string +getMediaBase64ByName(resName: string): Promise<string> -Obtains the string corresponding to the specified resource ID. This API returns the result synchronously. +Obtains the Base64 code of the image 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.| +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| **Return value** -| Type | Description | -| ------ | ----------- | -| string | String corresponding to the specified resource ID.| +| Type | Description | +| --------------------- | ------------------- | +| Promise<string> | Promise used to return the result.| **Error codes** @@ -2627,81 +2696,85 @@ 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.getMediaBase64ByName("test").then(value => { + let media = value; + }).catch(error => { + console.log("getMediaBase64ByName promise error is " + error); + }); } catch (error) { - console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getStringSync10+ +### getMediaBase64ByName10+ -getStringSync(resId: number, ...args: Array): string +getMediaBase64ByName(resName: string, density: number): Promise<string> -Obtains the string corresponding to the specified resource ID and formats the string based on **args**. This API returns the result synchronously. +Obtains the Base64 code of an image with the 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 | -| ----- | ------ | ---- | ----- | -| resId | number | Yes | Resource ID.| -| args | Array | No | Arguments for formatting strings.
Supported arguments:
-%d, %f, %s, and %%
Note: **%%** is used to translate **%**.
Example: **%%d** is translated into the **%d** string.| +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | **Return value** -| Type | Description | -| ------ | ---------------------------- | -| string | Formatted string.| +| Type | Description | +| --------------------- | ------------------- | +| Promise<string> | 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. | -| 9001006 | If the resource re-ref too much. | -| 9001007 | If the resource obtained by resId formatting error. | +| -------- | ---------------------------------------- | +| 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, "format string", 10, 98.78); + this.context.resourceManager.getMediaBase64ByName("test", 120).then(value => { + let media = value; + }).catch(error => { + console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); + }); } catch (error) { - console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getStringSync9+ +### getDrawableDescriptor10+ -getStringSync(resource: Resource): string +getDrawableDescriptor(resId: number, density?: number): DrawableDescriptor; -Obtains the string corresponding to the specified resource object. This API returns the result synchronously. +Obtains the **DrawableDescriptor** object corresponding to the specified resource ID. 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.| +| 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 | String corresponding to the specified resource object.| +| Type | Description | +| ------ | ---------- | +| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.| **Error codes** @@ -2711,27 +2784,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.string.test').id - }; try { - this.context.resourceManager.getStringSync(resource); + this.context.resourceManager.getDrawableDescriptor($r('app.media.icon').id); } catch (error) { - console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`); + 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(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getStringSync10+ +### getDrawableDescriptor10+ -getStringSync(resource: Resource, ...args: Array): string +getDrawableDescriptor(resource: Resource, density?: number): DrawableDescriptor; -Obtains the string corresponding to the specified resource object and formats the string based on **args**. This API returns the result synchronously. +Obtains the **DrawableDescriptor** object corresponding to the specified resource object. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -2742,13 +2814,13 @@ Obtains the string corresponding to the specified resource object and formats th | Name | Type | Mandatory | Description | | -------- | ---------------------- | ---- | ---- | | resource | [Resource](#resource9) | Yes | Resource object.| -| args | Array | No | Arguments for formatting strings.
Supported arguments:
-%d, %f, %s, and %%
Note: **%%** is used to translate **%**.
Example: **%%d** is translated into the **%d** string.| +| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.| **Return value** -| Type | Description | -| ------ | ---------------------------- | -| string | Formatted string.| +| Type | Description | +| ------- | ----------------- | +| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.| **Error codes** @@ -2758,28 +2830,31 @@ 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 let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.string.test').id + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.icon').id }; try { - this.context.resourceManager.getStringSync(resource, "format string", 10, 98.78); + this.context.resourceManager.getDrawableDescriptor(resource); } catch (error) { - console.error(`getStringSync 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}.`); + } + ``` -### getStringByNameSync9+ +### getDrawableDescriptorByName10+ -getStringByNameSync(resName: string): string +getDrawableDescriptorByName(resName: string, density?: number): DrawableDescriptor; -Obtains the string corresponding to the specified resource name. 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 @@ -2788,12 +2863,13 @@ Obtains the string corresponding to the specified resource name. This API return | Name | Type | Mandatory | Description | | ------- | ------ | ---- | ---- | | 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 name.| +| Type | Description | +| ------ | --------- | +| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.| **Error codes** @@ -2803,57 +2879,20 @@ 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.getStringByNameSync("test"); + this.context.resourceManager.getDrawableDescriptorByName('icon'); } catch (error) { - console.error(`getStringByNameSync failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getDrawableDescriptorByName failed, error code: ${error.code}, message: ${error.message}.`); } - ``` - -### getStringByNameSync10+ - -getStringByNameSync(resName: string, ...args: Array): string - -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 | -| ------- | ------ | ---- | ---- | -| resName | string | Yes | Resource name.| -| args | Array | No | Arguments for formatting strings.
Supported arguments:
-%d, %f, %s, and %%
Note: **%%** is used to translate **%**.
Example: **%%d** is translated into the **%d** string.| - -**Return value** - -| Type | Description | -| ------ | ---------------------------- | -| string | Formatted string.| - -**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. | -| 9001008 | If the resource obtained by resName formatting error. | - -**Example** - ```ts try { - this.context.resourceManager.getStringByNameSync("test", "format string", 10, 98.78); + this.context.resourceManager.getDrawableDescriptorByName('icon', 120); } catch (error) { - console.error(`getStringByNameSync failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getDrawableDescriptorByName failed, error code: ${error.code}, message: ${error.message}.`); } - ``` + ``` ### getBoolean9+ @@ -2928,9 +2967,9 @@ 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 + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.boolean.boolean_test').id }; try { this.context.resourceManager.getBoolean(resource); @@ -3058,9 +3097,9 @@ 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.integer.integer_test').id + 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. @@ -3114,11 +3153,11 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco } ``` -### getDrawableDescriptor10+ +### getColorSync10+ -getDrawableDescriptor(resId: number, density?: number): DrawableDescriptor; +getColorSync(resId: number) : number; -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 ID. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -3127,13 +3166,12 @@ Obtains the **DrawableDescriptor** object corresponding to the specified resourc | 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.| +| Type | Description | +| ------ | ----------- | +| number | Color value corresponding to the resource ID (decimal).| **Error codes** @@ -3143,26 +3181,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.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); + this.context.resourceManager.getColorSync($r('app.color.test').id); } catch (error) { - console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getColorSync failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getDrawableDescriptor10+ +### getColorSync10+ -getDrawableDescriptor(resource: Resource, density?: number): DrawableDescriptor; +getColorSync(resource: Resource): number -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 returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -3173,13 +3207,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.| +| Type | Description | +| ------ | ---------------- | +| number | Color value corresponding to the resource object (decimal).| **Error codes** @@ -3189,31 +3222,27 @@ 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 + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.color.test').id }; try { - this.context.resourceManager.getDrawableDescriptor(resource); - } catch (error) { - console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`); - } - try { - this.context.resourceManager.getDrawableDescriptor(resource, 120); + this.context.resourceManager.getColorSync(resource); } catch (error) { - console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getColorSync failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getDrawableDescriptorByName10+ +### getColorByNameSync10+ -getDrawableDescriptorByName(resName: string, density?: number): DrawableDescriptor; +getColorByNameSync(resName: string) : number; -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 returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -3222,13 +3251,12 @@ Obtains the **DrawableDescriptor** object corresponding to the specified resourc | 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.| +| Type | Description | +| ------ | ---------- | +| number | Color value corresponding to the resource name (decimal).| **Error codes** @@ -3238,18 +3266,14 @@ 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}.`); - } - try { - this.context.resourceManager.getDrawableDescriptorByName('icon', 120); + this.context.resourceManager.getColorByNameSync("test"); } catch (error) { - console.error(`getDrawableDescriptorByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getColorByNameSync failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -3280,17 +3304,17 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco **Example (stage)** ```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; - } - }); - } catch (error) { - console.error(`callback getColor failed, error code: ${error.code}, message: ${error.message}.`); - } + try { + 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(`callback getColor failed, error code: ${error.code}, message: ${error.message}.`); + } ``` ### getColor10+ @@ -3311,7 +3335,7 @@ Obtains the color value corresponding to the specified resource ID. This API use | Type | Description | | --------------------- | ----------- | -| Promise<number> | Color value corresponding to the resource ID (decimal).| +| Promise<number> | Promise used to return the result.| **Error codes** @@ -3327,9 +3351,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco ```ts try { this.context.resourceManager.getColor($r('app.color.test').id).then(value => { - let str = value; + let str = value; }).catch(error => { - console.log("getColor promise error is " + error); + console.log("getColor promise error is " + error); }); } catch (error) { console.error(`promise getColor failed, error code: ${error.code}, message: ${error.message}.`); @@ -3366,17 +3390,17 @@ 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.color.test').id + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.color.test').id }; try { this.context.resourceManager.getColor(resource, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let str = value; - } + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } }); } catch (error) { console.error(`callback getColor failed, error code: ${error.code}, message: ${error.message}.`); @@ -3403,7 +3427,7 @@ Obtains the color value corresponding to the specified resource object. This API | Type | Description | | --------------------- | ---------------- | -| Promise<number> | Color value corresponding to the resource object (decimal).| +| Promise<number> | Promise used to return the result.| **Error codes** @@ -3418,9 +3442,9 @@ 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.color.test').id + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.color.test').id }; try { this.context.resourceManager.getColor(resource).then(value => { @@ -3462,11 +3486,11 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco ```ts try { this.context.resourceManager.getColorByName("test", (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let string = value; - } + if (error != null) { + console.log("error is " + error); + } else { + let string = value; + } }); } catch (error) { console.error(`callback getColorByName failed, error code: ${error.code}, message: ${error.message}.`); @@ -3491,7 +3515,7 @@ Obtains the color value corresponding to the specified resource name. This API u | Type | Description | | --------------------- | ---------- | -| Promise<number> | Color value corresponding to the resource name (decimal).| +| Promise<number> | Promise used to return the result.| **Error codes** @@ -3507,34 +3531,34 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco ```ts try { this.context.resourceManager.getColorByName("test").then(value => { - let string = value; + let string = value; }).catch(error => { - console.log("getColorByName promise error is " + error); + console.log("getColorByName promise error is " + error); }); } catch (error) { console.error(`promise getColorByName failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getColorSync10+ +### getRawFileContentSync10+ -getColorSync(resId: number) : number; +getRawFileContentSync(path: string): Uint8Array -Obtains the color value corresponding to the specified resource ID. This API returns the result synchronously. +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.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ----------------------- | +| path | string | Yes | Path of the raw file. | **Return value** -| Type | Description | -| ------ | ----------- | -| number | Color value corresponding to the resource ID (decimal).| +| Type | Description | +| --------------------- | ---------- | +| Uint8Array | Content of the raw file.| **Error codes** @@ -3542,40 +3566,74 @@ 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); + this.context.resourceManager.getRawFileContentSync("test.txt"); } catch (error) { - console.error(`getColorSync failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getRawFileContentSync failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getColorSync10+ +### getRawFileContent9+ -getColorSync(resource: Resource): number +getRawFileContent(path: string, callback: AsyncCallback<Uint8Array>): void -Obtains the color value corresponding to the specified resource object. This API returns the result synchronously. +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 | +| -------- | ------------------------------- | ---- | ----------------------- | +| path | string | Yes | Path of the raw file. | +| callback | AsyncCallback<Uint8Array> | 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.getRawFileContent("test.xml", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let rawFile = value; + } + }); + } catch (error) { + console.error(`callback getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### getRawFileContent9+ + +getRawFileContent(path: string): Promise<Uint8Array> + +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 **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | ---- | ---- | -| resource | [Resource](#resource9) | Yes | Resource object.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------- | +| path | string | Yes | Path of the raw file.| **Return value** -| Type | Description | -| ------ | ---------------- | -| number | Color value corresponding to the resource object (decimal).| +| Type | Description | +| ------------------------- | ----------- | +| Promise<Uint8Array> | Promise used to return the result.| **Error codes** @@ -3583,43 +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.getColorSync(resource); + this.context.resourceManager.getRawFileContent("test.xml").then(value => { + let rawFile = value; + }).catch(error => { + console.log("getRawFileContent promise error is " + error); + }); } catch (error) { - console.error(`getColorSync failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getColorByNameSync10+ +### getRawFileListSync10+ -getColorByNameSync(resName: string) : number; +getRawFileListSync(path: string): Array\ -Obtains the color value corresponding to the specified resource name. This API returns the result synchronously. +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.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ----------------------- | +| path | string | Yes | Path of the **rawfile** folder. | **Return value** -| Type | Description | -| ------ | ---------- | -| number | Color value corresponding to the resource name (decimal).| +| Type | Description | +| ------------------------- | ----------- | +| Array\ | List of files in the **resources/rawfile** directory.| **Error codes** @@ -3627,16 +3682,454 @@ 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"); + 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(`getColorByNameSync failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getRawFileListSync failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### getRawFileList10+ + +getRawFileList(path: string, callback: AsyncCallback<Array\>): void; + +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 | +| -------- | ------------------------------- | ---- | ----------------------- | +| path | string | Yes | Path of the **rawfile** folder. | +| callback | AsyncCallback<Array\> | 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 { // 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(`callback getRawFileList failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### getRawFileList10+ + +getRawFileList(path: string): Promise<Array\> + +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 | +| ---- | ------ | ---- | ----------- | +| path | string | Yes | Path of the **rawfile** folder.| + +**Return value** + +| Type | Description | +| ------------------------- | ----------- | +| Promise<Array\> | 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| +| -------- | ---------------------------------------- | +| 9001005 | If the resource not found by path. | + +**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}.`); + }); + } catch (error) { + console.error(`promise getRawFileList failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### getRawFdSync10+ + +getRawFdSync(path: string): RawFileDescriptor + +Obtains 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. | + +**Return value** + +| Type | Description | +| ------------------------- | ----------- | +| [RawFileDescriptor](#rawfiledescriptor8) | Descriptor 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 | If the resource not found by path. | + +**Example** + ```ts + try { + this.context.resourceManager.getRawFdSync("test.txt"); + } catch (error) { + console.error(`getRawFdSync failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### getRawFd9+ + +getRawFd(path: string, callback: AsyncCallback<RawFileDescriptor>): void + +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 | +| -------- | ---------------------------------------- | ---- | -------------------------------- | +| path | string | Yes | Path of the raw file. | +| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | 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}.`); + } + ``` + +### getRawFd9+ + +getRawFd(path: string): Promise<RawFileDescriptor> + +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 | +| ---------------------------------------- | ------------------- | +| Promise<[RawFileDescriptor](#rawfiledescriptor8)> | 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| +| -------- | ---------------------------------------- | +| 9001005 | If the resource not found by path. | + +**Example** + ```ts + try { + 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(`promise getRawFd failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### closeRawFdSync10+ + +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}.`); + } + ``` + +### closeRawFd9+ + +closeRawFd(path: string, callback: AsyncCallback<void>): 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<void> | 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}.`); + } + ``` + +### closeRawFd9+ + +closeRawFd(path: string): Promise<void> + +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<void> | 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<Configuration>): 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<[Configuration](#configuration)> | 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<Configuration> + +Obtains the device configuration. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise<[Configuration](#configuration)> | 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<DeviceCapability>): 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<[DeviceCapability](#devicecapability)> | 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<DeviceCapability> + +Obtains the device capability. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------- | +| Promise<[DeviceCapability](#devicecapability)> | 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); + } + ``` + +### release7+ + +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); } ``` @@ -3666,9 +4159,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco ```ts let path = getContext().bundleCodeDir + "/library1-default-signed.hsp"; try { - this.context.resourceManager.addResource(path); + this.context.resourceManager.addResource(path); } catch (error) { - console.error(`addResource failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`addResource failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -3698,9 +4191,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco ```ts let path = getContext().bundleCodeDir + "/library1-default-signed.hsp"; try { - this.resmgr.removeResource(path); + this.resmgr.removeResource(path); } catch (error) { - console.error(`removeResource failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`removeResource failed, error code: ${error.code}, message: ${error.message}.`); } ``` diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md index d61b8272edee9b2b522139a9976df17027be98a5..99eb42bd5720fa12a833abcc030b45d02c7aefaf 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @@ -1,16 +1,9 @@ # @ohos.resourceschedule.backgroundTaskManager (Background Task Management) -The **BackgroundTaskManager** module provides APIs to manage background tasks. - -If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task to delay the suspension or a continuous task to prevent the suspension. - -If an application has a task that needs to be continued when the application is switched to the background and can be completed within a short period of time, the application can request a transient task. For example, if a user chooses to clear junk files in the **Files** application and exits the application, the application can request a transient task to complete the cleanup. - -If an application has a service that can be intuitively perceived by users and needs to run in the background for a long period of time (for example, music playback in the background), the application can request a continuous task. - -If a privileged system application needs to use certain system resources (for example, it wants to receive common events when suspended), it can request efficiency resources. +The **backgroundTaskManager** module provides APIs to request background tasks. You can use the APIs to request transient tasks, continuous tasks, or efficiency resources to prevent the application process from being terminated or suspended when your application is switched to the background. > **NOTE** +> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -24,9 +17,11 @@ import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager' requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspendInfo -Requests delayed suspension after the application switches to the background. +Requests a transient task. -The default duration of delayed suspension is 3 minutes when the battery level is higher than or equal to the broadcast low battery level and 1 minute when the battery level is lower than the broadcast low battery level. +> **NOTE** +> +> The maximum duration of a transient task is 3 minutes in normal cases. In the case of a [low battery](js-apis-battery-info.md), the maximum duration is decreased to 1 minute. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask @@ -34,14 +29,14 @@ The default duration of delayed suspension is 3 minutes when the battery level i | Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | ------------------------------ | -| reason | string | Yes | Reason for delayed transition to the suspended state. | -| callback | Callback<void> | Yes | Invoked when a delay is about to time out. Generally, this callback is used to notify the application 6 seconds before the delay times out.| +| reason | string | Yes | Reason for requesting the transient task. | +| callback | Callback<void> | Yes | Callback used to notify the application that the transient task is about to time out. Generally, the callback is invoked 6 seconds before the timeout.| **Return value** | Type | Description | | ------------------------------------- | --------- | -| [DelaySuspendInfo](#delaysuspendinfo) | Information about the suspension delay.| +| [DelaySuspendInfo](#delaysuspendinfo) | Information about the transient task.| **Error codes** @@ -80,7 +75,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void -Obtains the remaining duration before the application is suspended. This API uses an asynchronous callback to return the result. +Obtains the remaining time of a transient task. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask @@ -88,8 +83,8 @@ Obtains the remaining duration before the application is suspended. This API use | Name | Type | Mandatory | Description | | --------- | --------------------------- | ---- | ---------------------------------------- | -| requestId | number | Yes | ID of the suspension delay request. | -| callback | AsyncCallback<number> | Yes | Callback used to return the remaining duration before the application is suspended, in milliseconds.| +| requestId | number | Yes | Request ID of the transient task. | +| callback | AsyncCallback<number> | Yes | Callback used to return the remaining time, in milliseconds.| **Error codes** @@ -129,9 +124,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er getRemainingDelayTime(requestId: number): Promise<number> -Obtains the remaining duration before the application is suspended. This API uses a promise to return the result. - - +Obtains the remaining time of a transient task. This API uses a promise to return the result. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask @@ -139,13 +132,13 @@ Obtains the remaining duration before the application is suspended. This API use | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ---------- | -| requestId | number | Yes | ID of the suspension delay request.| +| requestId | number | Yes | Request ID of the transient task.| **Return value** | Type | Description | | --------------------- | ---------------------------------------- | -| Promise<number> | Promise used to return the remaining duration before the application is suspended, in milliseconds.| +| Promise<number> | Promise used to return the remaining time, in milliseconds.| **Error codes** @@ -182,7 +175,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er cancelSuspendDelay(requestId: number): void -Cancels the suspension delay. +Cancels a transient task. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask @@ -190,7 +183,7 @@ Cancels the suspension delay. | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ---------- | -| requestId | number | Yes | ID of the suspension delay request.| +| requestId | number | Yes | Request ID of the transient task.| **Error codes** @@ -218,12 +211,11 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er } ``` - ## backgroundTaskManager.startBackgroundRunning startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback<void>): void -Requests a continuous task from the system. This API uses an asynchronous callback to return the result. +Requests a continuous task. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING @@ -234,9 +226,9 @@ Requests a continuous task from the system. This API uses an asynchronous callba | Name | Type | Mandatory | Description | | --------- | ---------------------------------- | ---- | ---------------------------------------- | | context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| -| bgMode | [BackgroundMode](#backgroundmode) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| bgMode | [BackgroundMode](#backgroundmode) | Yes | Continuous task mode. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameters, which are used to specify the target page that is redirected to when a continuous task notification is clicked. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the continuous task is requested, **err** is **undefined**. Otherwise, **err** is an error object. | **Error codes** @@ -301,7 +293,7 @@ export default class EntryAbility extends UIAbility { startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void> -Requests a continuous task from the system. This API uses a promise to return the result. +Requests a continuous task. This API uses a promise to return the result. **Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING @@ -312,14 +304,14 @@ Requests a continuous task from the system. This API uses a promise to return th | Name | Type | Mandatory | Description | | --------- | ---------------------------------- | ---- | ---------------------------------------- | | context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| -| bgMode | [BackgroundMode](#backgroundmode) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | +| bgMode | [BackgroundMode](#backgroundmode) | Yes | Continuous task mode. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameters, which are used to specify the target page that is redirected to when a continuous task notification is clicked. | **Return value** | Type | Description | | -------------- | ---------------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Error codes** @@ -380,7 +372,7 @@ export default class EntryAbility extends UIAbility { stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void -Requests to cancel a continuous task. This API uses an asynchronous callback to return the result. +Cancels a continuous task. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask @@ -389,7 +381,7 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------------------------------- | | context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the continuous task is canceled, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -434,9 +426,7 @@ export default class EntryAbility extends UIAbility { stopBackgroundRunning(context: Context): Promise<void> -Requests to cancel a continuous task. This API uses a promise to return the result. - - +Cancels a continuous task. This API uses a promise to return the result. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask @@ -450,7 +440,7 @@ Requests to cancel a continuous task. This API uses a promise to return the resu | Type | Description | | -------------- | ---------------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Error codes** @@ -489,10 +479,9 @@ export default class EntryAbility extends UIAbility { ## backgroundTaskManager.applyEfficiencyResources -applyEfficiencyResources(request: [EfficiencyResourcesRequest](#efficiencyresourcesrequest)): void +applyEfficiencyResources(request: EfficiencyResourcesRequest): void -Requests efficiency resources from the system. -A process and its application can request the same type of resources at the same time, for example, CPU resources. When the application releases the resources, the same type of resources requested by the process are also released. +Requests efficiency resources. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply @@ -502,7 +491,7 @@ A process and its application can request the same type of resources at the same | Name | Type | Mandatory | Description | | ------- | ------- | ---- | ---------------------------------------- | -| request | [EfficiencyResourcesRequest](#efficiencyresourcesrequest) | Yes | Necessary information carried in the request, including the resource type and timeout interval. For details, see [EfficiencyResourcesRequest](#efficiencyresourcesrequest).| +| request | [EfficiencyResourcesRequest](#efficiencyresourcesrequest) | Yes | Necessary information carried in the request, including the resource type and timeout interval.| **Error codes** @@ -542,7 +531,7 @@ try { resetAllEfficiencyResources(): void -Releases all resources that have been requested. +Releases all efficiency resources. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply @@ -574,18 +563,19 @@ try { ## DelaySuspendInfo -Provides the information about the suspension delay. +Defines the information about the transient task. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask | Name | Type | Mandatory | Description | | --------------- | ------ | ---- | ---------------------------------------- | -| requestId | number | Yes | ID of the suspension delay request. | -| actualDelayTime | number | Yes | Actual suspension delay duration of the application, in milliseconds.
The default duration is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level.| - +| requestId | number | Yes | Request ID of the transient task. | +| actualDelayTime | number | Yes | Actual duration of the transient task that the application requests, in milliseconds.
The maximum duration of a transient task is 3 minutes in normal cases. In the case of a [low battery](js-apis-battery-info.md), the maximum duration is decreased to 1 minute.| ## BackgroundMode +Enumerates the continuous task modes. + **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask | Name | Value | Description | @@ -596,9 +586,9 @@ Provides the information about the suspension delay. | LOCATION | 4 | Positioning and navigation. | | BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. | | MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. | -| WIFI_INTERACTION | 7 | WLAN-related (system API).| -| VOIP | 8 | Audio and video calls (system API). | -| TASK_KEEPING | 9 | Computing task (effective only for specific devices). | +| WIFI_INTERACTION | 7 | WLAN-related.
**System API**: This is a system API.| +| VOIP | 8 |Audio and video calls.
**System API**: This is a system API.| +| TASK_KEEPING | 9 | Computing task (for specific devices only). | ## EfficiencyResourcesRequest @@ -611,10 +601,10 @@ Describes the parameters for requesting efficiency resources. | Name | Type | Mandatory | Description | | --------------- | ------ | ---- | ---------------------------------------- | | resourceTypes | number | Yes | Type of the resource to request. | -| isApply | boolean | Yes | Whether the request is used to apply for resources. The value **true** means that the request is used to apply for resources, and **false** means that the request is used to release resources. | +| isApply | boolean | Yes | Whether the request is used to apply for resources.
The value **true** means that the request is used to apply for resources, and **false** means that the request is used to release resources.| | timeOut | number | Yes | Duration for which the resource will be used, in milliseconds. | -| isPersist | boolean | No | Whether the resource is permanently held. If the value is **true**, **timeOut** is invalid. | -| isProcess | boolean | No | Whether the request is initiated by a process. The value **true** means that the request is initiated by a process, and **false** means that the request is initiated by an application. | +| isPersist | boolean | No | Whether the resource is permanently held. The default value is **false**.
The value **true** means that the resource is permanently held, and **false** means the resource is held within a given period of time.| +| isProcess | boolean | No | Whether the request is initiated by a process. The default value is **false**.
The value **true** means that the request is initiated by a process, and **false** means that the request is initiated by an application. | | reason | string | Yes | Reason for requesting the resource. | ## ResourceType @@ -627,12 +617,12 @@ Enumerates the efficiency resource types. | Name | Value | Description | | ----------------------- | ---- | --------------------- | -| CPU | 1 | CPU resources, which prevent the application from being suspended. | -| COMMON_EVENT | 2 | Common events are not proxied when the application is suspended.| -| TIMER | 4 | System timers are not proxied when the application is suspended.| -| WORK_SCHEDULER | 8 | Work Scheduler uses a loose control policy by default. For details about the constraints on the Work Scheduler usage, see [Constraints](../../task-management/work-scheduler.md#constraints).| -| BLUETOOTH | 16 | Bluetooth resources are not proxied when the application is suspended.| -| GPS | 32 | GPS resources are not proxied when the application is suspended.| -| AUDIO | 64 | Audio resources are not proxied when the application is suspended.| +| CPU | 1 | CPU resource. Such type of resource prevents an application from being suspended. | +| COMMON_EVENT | 2 | Common event resource. Such type of resource ensures that an application in the suspended state can receive common events.| +| TIMER | 4 | Timer resource. Such type of resource ensures that an application in the suspended state can be woken up by system timers.| +| WORK_SCHEDULER | 8 | Deferred task resource. Such type of resource provides a loose control policy for an application.| +| BLUETOOTH | 16 | Bluetooth resource. Such type of resource ensures that an application in the suspended state can be woken up by Bluetooth-related events.| +| GPS | 32 | GPS resource. Such type of resource ensures that an application in the suspended state can be woken up by GPS-related events.| +| AUDIO | 64 | Audio resource. Such type of resource prevents an application from being suspended when the application has an audio being played.| | RUNNING_LOCK10+ | 128 | RUNNING_LOCK resources are not proxied when the application is suspended.| | SENSOR10+ | 256 | Sensor callbacks are not intercepted.| diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md index 85c085f6fb9ef65fb711aecbfe3610ab3d17f5d9..5fad64915cde48a0fe0150e83f1661bc0abb1aaa 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @@ -1,15 +1,12 @@ # @ohos.resourceschedule.workScheduler (Deferred Task Scheduling) -The **workScheduler** module provides the APIs for registering, canceling, and querying deferred tasks. - -The system schedules and executes deferred tasks at an appropriate time, subject to the storage space, power consumption, temperature, and more. +The **workScheduler** module provides the APIs for registering, canceling, and querying deferred tasks. You can use the APIs to register tasks that do not have high requirements on real-time performance as deferred tasks. The system schedules and executes the deferred tasks at an appropriate time, subject to the storage space, power consumption, and more. > **NOTE** > > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > - The APIs of this module can be used only in the stage model. -> - For details about the constraints on deferred task scheduling, see [Constraints](../../task-management/work-scheduler.md#constraints). - ## Modules to Import @@ -18,9 +15,10 @@ import workScheduler from '@ohos.resourceschedule.workScheduler'; ``` ## workScheduler.startWork + startWork(work: WorkInfo): void -Instructs the WorkSchedulerService to add a task to the execution queue. +Starts a deferred task. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -28,7 +26,7 @@ Instructs the WorkSchedulerService to add a task to the execution queue. | Name | Type | Mandatory | Description | | ---- | --------------------- | ---- | -------------- | -| work | [WorkInfo](#workinfo) | Yes | Task to be added to the execution queue.| +| work | [WorkInfo](#workinfo) | Yes | Deferred task to start.| **Error codes** @@ -42,7 +40,6 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes | 9700004 | Check workInfo failed. | | 9700005 | StartWork failed. | - **Example** ```js @@ -69,9 +66,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ``` ## workScheduler.stopWork + stopWork(work: WorkInfo, needCancel?: boolean): void -Instructs the WorkSchedulerService to stop a task. +Stops a deferred task. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -79,8 +77,8 @@ Instructs the WorkSchedulerService to stop a task. | Name | Type | Mandatory | Description | | ---------- | --------------------- | ---- | ---------- | -| work | [WorkInfo](#workinfo) | Yes | Task to stop. | -| needCancel | boolean | No | Whether to cancel the task. The default value is **false**.| +| work | [WorkInfo](#workinfo) | Yes | Deferred task to stop.| +| needCancel | boolean | No | Whether to clear the task while stopping it.
The value **true** means to clear the task while stopping it, and **false** means to stop the task only. The default value is **false**.| **Error codes** @@ -119,9 +117,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ``` ## workScheduler.getWorkStatus + getWorkStatus(workId: number, callback : AsyncCallback\): void -Obtains the latest task status. This API uses an asynchronous callback to return the result. +Obtains the information a deferred task. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -129,8 +128,8 @@ Obtains the latest task status. This API uses an asynchronous callback to return | Name | Type | Mandatory | Description | | -------- | ------------------------------------- | ---- | ---------------------------------------- | -| workId | number | Yes | Task ID. | -| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. If the specified task ID is valid, the task status obtained from the WorkSchedulerService is returned. Otherwise, an exception is thrown.| +| workId | number | Yes | ID of the deferred task. | +| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. If **workId** is valid, the task information obtained from WorkSchedulerService is returned. Otherwise, an exception is thrown.| **Error codes** @@ -162,9 +161,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ``` ## workScheduler.getWorkStatus + getWorkStatus(workId: number): Promise\ -Obtains the latest task status. This API uses a promise to return the result. +Obtains the information a deferred task. This API uses a promise to return the result. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -172,13 +172,13 @@ Obtains the latest task status. This API uses a promise to return the result. | Name | Type | Mandatory | Description | | ------ | ------ | ---- | -------- | -| workId | number | Yes | Task ID.| +| workId | number | Yes | ID of the deferred task.| **Return value** | Type | Description | | ------------------------------- | ---------------------------------------- | -| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. If the specified task ID is valid, the task status obtained from the WorkSchedulerService is returned. Otherwise, an exception is thrown.| +| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. If **workId** is valid, the task information obtained from WorkSchedulerService is returned.| **Error codes** @@ -208,9 +208,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ``` ## workScheduler.obtainAllWorks + obtainAllWorks(callback : AsyncCallback\): Array\ -Obtains all tasks associated with the application. This API uses an asynchronous callback to return the result. +Obtains all the deferred tasks. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -218,13 +219,13 @@ Obtains all tasks associated with the application. This API uses an asynchronous | Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | ------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If all the deferred tasks are obtained, **err** is **undefined**. Otherwise, **err** is an error object.| **Return value** | Type | Description | | ----------------------------- | --------------- | -| Array\<[WorkInfo](#workinfo)> | All tasks associated with the application.| +| Array\<[WorkInfo](#workinfo)> | All the deferred tasks.| **Error codes** @@ -253,9 +254,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ``` ## workScheduler.obtainAllWorks + obtainAllWorks(): Promise\> -Obtains all tasks associated with the application. This API uses a promise to return the result. +Obtains all the deferred tasks. This API uses a promise to return the result. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -263,7 +265,7 @@ Obtains all tasks associated with the application. This API uses a promise to re | Type | Description | | -------------------------------------- | ------------------------------ | -| Promise> | Promise used to return all tasks associated with the application.| +| Promise> | Promise used to return all the deferred tasks.| **Error codes** @@ -290,9 +292,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ``` ## workScheduler.stopAndClearWorks + stopAndClearWorks(): void -Stops and cancels all tasks associated with the application. +Stops and clears all the deferred tasks. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -318,6 +321,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ``` ## workScheduler.isLastWorkTimeOut + isLastWorkTimeOut(workId: number, callback : AsyncCallback\): boolean Checks whether the last execution of a task timed out. This API uses an asynchronous callback to return the result. @@ -328,14 +332,14 @@ Checks whether the last execution of a task timed out. This API uses an asynchro | Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | ---------------------------------------- | -| workId | number | Yes | Task ID. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| workId | number | Yes | ID of the deferred task. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Return value** | Type | Description | | ------- | ---------------------------------------- | -| boolean | Returns **true** if the last execution of the task timed out; returns **false** otherwise.| +| boolean | The value **true** means that the last execution of the specified task times out, and **false** means the opposite.| **Error codes** @@ -365,6 +369,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ``` ## workScheduler.isLastWorkTimeOut + isLastWorkTimeOut(workId: number): Promise\ Checks whether the last execution of a task timed out. This API uses a promise to return the result. @@ -375,13 +380,13 @@ Checks whether the last execution of a task timed out. This API uses a promise t | Name | Type | Mandatory | Description | | ------ | ------ | ---- | -------- | -| workId | number | Yes | Task ID.| +| workId | number | Yes | ID of the deferred task.| **Return value** | Type | Description | | ----------------- | ---------------------------------------- | -| Promise\ | Promise used to return the result. If the last execution of the task timed out, **true** is returned. Otherwise, **false** is returned.| +| Promise\ | Promise used to return the result. The value **true** means that the last execution of the specified task times out, and **false** means the opposite.| **Error codes** @@ -411,31 +416,33 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ``` ## WorkInfo -Provides detailed information about the task. For details about the constraints on setting the **WorkInfo** parameter, see [Constraints](../../task-management/work-scheduler.md#constraints). + +Defines the information about the deferred task. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler | Name | Type | Mandatory | Description | | --------------- | --------------------------------- | ---- | ---------------- | -| workId | number | Yes | Task ID. | +| workId | number | Yes | ID of the deferred task. | | bundleName | string | Yes | Bundle name of the application that requests the task. | | abilityName | string | Yes | Name of the component to be notified by a deferred task scheduling callback.| | networkType | [NetworkType](#networktype) | No | Network type. | -| isCharging | boolean | No | Whether the device is charging. | +| isCharging | boolean | No | Whether the device needs to enter the charging state to trigger deferred task scheduling.
The value **true** means that the device needs to enter the charging state to trigger deferred task scheduling, and **false** means the opposite.| | chargerType | [ChargingType](#chargingtype) | No | Charging type. | -| batteryLevel | number | No | Battery level. | +| batteryLevel | number | No | Battery level. | | batteryStatus | [BatteryStatus](#batterystatus) | No | Battery status. | | storageRequest | [StorageRequest](#storagerequest) | No | Storage status. | -| isRepeat | boolean | No | Whether the task is repeated. | +| isRepeat | boolean | No | Whether the task is repeated.
The value** true** means that the task is repeated, and **false** means the opposite.| | repeatCycleTime | number | No | Repeat interval. | | repeatCount | number | No | Number of repeat times. | -| isPersisted | boolean | No | Whether to enable persistent storage for the task. | -| isDeepIdle | boolean | No | Whether the device needs to enter the idle state. | -| idleWaitTime | number | No | Time to wait in the idle state. | -| parameters | {[key: string]: number \| string \| boolean} | No | Carried parameters. | +| isPersisted | boolean | No | Whether to enable persistent storage for the task.
The value **true** means to enable persistent storage for the task, and **false** means the opposite.| +| isDeepIdle | boolean | No | Whether the device needs to enter the idle state to trigger deferred task scheduling.
The value **true** means that the device needs to enter the idle state to trigger deferred task scheduling, and **false** means the opposite. | +| idleWaitTime | number | No | Time to wait in the idle state before triggering deferred task scheduling. | +| parameters | [key: string]: number \| string \| boolean | No | Carried parameters.| ## NetworkType -Enumerates the network types that can trigger task scheduling. + +Enumerates the network types that can trigger deferred task scheduling. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -449,7 +456,8 @@ Enumerates the network types that can trigger task scheduling. | NETWORK_TYPE_ETHERNET | 5 | Ethernet. | ## ChargingType -Enumerates the charging types that can trigger task scheduling. + +Enumerates the charging types that can trigger deferred task scheduling. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -461,7 +469,8 @@ Enumerates the charging types that can trigger task scheduling. | CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. | ## BatteryStatus -Enumerates the battery states that can trigger task scheduling. + +Enumerates the battery statuses that can trigger deferred task scheduling. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -472,7 +481,8 @@ Enumerates the battery states that can trigger task scheduling. | BATTERY_STATUS_LOW_OR_OKAY | 2 | The battery level is restored from low to normal, or a low battery alert is displayed.| ## StorageRequest -Enumerates the storage states that can trigger task scheduling. + +Enumerates the storage statuses that can trigger deferred task scheduling. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -480,4 +490,4 @@ Enumerates the storage states that can trigger task scheduling. | ------------------------- | ---- | ------------------------------ | | STORAGE_LEVEL_LOW | 0 | The storage space is insufficient. | | STORAGE_LEVEL_OKAY | 1 | The storage space is restored from insufficient to normal. | -| STORAGE_LEVEL_LOW_OR_OKAY | 2 | The storage space is restored from insufficient to normal, or the storage space is insufficient.| +| STORAGE_LEVEL_LOW_OR_OKAY | 2 | The storage space is insufficient, or the storage space is restored from insufficient to normal.| diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md index 2d97910441aa8dc3d5fe958c5424a0b449ce0620..0643de31173d0737a10431bc0bb8eb7d06428f01 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -51,21 +51,19 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** ```ts -router.pushUrl({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] +try { + router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } } - } -}) - .then(() => { - // success - }) - .catch(err => { - console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); }) +} catch (err) { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); +} ``` ## router.pushUrl9+ @@ -146,21 +144,19 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** ```ts -router.pushUrl({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] +try { + router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } } - } -}, router.RouterMode.Standard) - .then(() => { - // success - }) - .catch(err => { - console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); - }) + }, router.RouterMode.Standard) +} catch (err) { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); +} ``` ## router.pushUrl9+ @@ -241,18 +237,16 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** ```ts -router.replaceUrl({ - url: 'pages/detail', - params: { - data1: 'message' - } -}) - .then(() => { - // success - }) - .catch(err => { - console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); +try { + router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } }) +} catch (err) { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); +} ``` ## router.replaceUrl9+ @@ -330,18 +324,16 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** ```ts -router.replaceUrl({ - url: 'pages/detail', - params: { - data1: 'message' - } -}, router.RouterMode.Standard) - .then(() => { - // success - }) - .catch(err => { - console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); - }) +try { + router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } + }, router.RouterMode.Standard) +} catch (err) { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); +} ``` ## router.replaceUrl9+ @@ -420,23 +412,23 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** ```ts -router.pushNamedRoute({ - name: 'myPage', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] +try { + router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } } - } -}) - .then(() => { - // success - }) - .catch(err => { - console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); }) +} catch (err) { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); +} ``` +For details, see [UI Development-Named Route](../../ui/arkts-routing.md#named-route). + ## router.pushNamedRoute10+ pushNamedRoute(options: NamedRouterOptions, callback: AsyncCallback<void>): void @@ -515,21 +507,19 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** ```ts -router.pushNamedRoute({ - name: 'myPage', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] +try { + router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } } - } -}, router.RouterMode.Standard) - .then(() => { - // success - }) - .catch(err => { - console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); - }) + }, router.RouterMode.Standard) +} catch (err) { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); +} ``` ## router.pushNamedRoute10+ @@ -610,18 +600,16 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** ```ts -router.replaceNamedRoute({ - name: 'myPage', - params: { - data1: 'message' - } -}) - .then(() => { - // success - }) - .catch(err => { - console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); +try { + router.replaceNamedRoute({ + name: 'myPage', + params: { + data1: 'message' + } }) +} catch (err) { + console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); +} ``` ## router.replaceNamedRoute10+ @@ -693,24 +681,22 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | if UI execution context not found, only throw in standard system. | +| 100001 | if can not get the delegate, only throw in standard system. | | 100004 | if the named route is not exist. | **Example** ```ts -router.replaceNamedRoute({ - name: 'myPage', - params: { - data1: 'message' - } -}, router.RouterMode.Standard) - .then(() => { - // success - }) - .catch(err => { - console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); - }) +try { + router.replaceNamedRoute({ + name: 'myPage', + params: { + data1: 'message' + } + }, router.RouterMode.Standard) +} catch (err) { + console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); +} ``` ## router.replaceNamedRoute10+ @@ -932,7 +918,7 @@ Describes the page routing options. | Name | Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | | url | string | Yes | URL of the target page, in either of the following formats:
- Absolute path of the page. The value is available in the pages list in the **config.json** file, for example:
- pages/index/index
- pages/detail/detail
- Particular path. If the URL is a slash (/), the home page is displayed.| -| params | object | No | Data that needs to be passed to the target page during redirection. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is the value of a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.| +| params | object | No | Data that needs to be passed to the target page during redirection. The received data becomes invalid when the page is switched to another page. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is the value of a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.
**NOTE**
The **params** parameter cannot pass objects returned by methods and system APIs, for example, **PixelMap** objects defined and returned by media APIs. To pass such objects, extract from them the basic type attributes to be passed, and then construct objects of the object type.| > **NOTE** diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index fb3aa7540b8383f983436c0d713e09346ad6aa3e..cbc5ed086fff519da5b5c959304afeeac6f442d5 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -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 diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index 76c7829cf8fdadad378305ba795212ac10f621ea..f193ed010e3b0eb1ba6a87fad70f81b19bf9b732 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -1691,7 +1691,7 @@ listen(address: NetAddress, callback: AsyncCallback\): 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**
> 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\ 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**
> 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 diff --git a/en/application-dev/reference/apis/js-apis-webview.md b/en/application-dev/reference/apis/js-apis-webview.md index adea4c22a9473f43b8092d0314918537ecaa98b6..d0b51d00e6ddb980ac95cdeeb8a20de3db84c1a7 100644 --- a/en/application-dev/reference/apis/js-apis-webview.md +++ b/en/application-dev/reference/apis/js-apis-webview.md @@ -254,20 +254,20 @@ struct WebComponent { .onClick(() => { // Use the local port to send messages to HTML5. try { - console.log("In eTS side send true start"); + console.log("In ArkTS side send true start"); if (this.nativePort) { this.message.setString("helloFromEts"); this.nativePort.postMessageEventExt(this.message); } } catch (error) { - console.log("In eTS side send message catch error:" + error.code + ", msg:" + error.message); + console.log("In ArkTS side send message catch error:" + error.code + ", msg:" + error.message); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) .onPageEnd((e)=>{ - console.log("In eTS side message onPageEnd init mesaage channel"); + console.log("In ArkTS side message onPageEnd init mesaage channel"); // 1. Create a message port. this.ports = this.controller.createWebMessagePorts(true); // 2. Send port 1 to HTML5. @@ -276,10 +276,10 @@ struct WebComponent { this.nativePort = this.ports[0]; // 4. Set the callback. this.nativePort.onMessageEventExt((result) => { - console.log("In eTS side got message"); + console.log("In ArkTS side got message"); try { var type = result.getType(); - console.log("In eTS side getType:" + type); + console.log("In ArkTS side getType:" + type); switch (type) { case web_webview.WebMessageType.STRING: { this.msg1 = "result type:" + typeof (result.getString()); @@ -652,71 +652,71 @@ struct WebComponent { There are three methods for loading local resource files: 1. Using $rawfile - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - - @Entry - @Component - struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController(); - - build() { - Column() { - Button('loadUrl') - .onClick(() => { - try { - // Load a local resource file through $rawfile. - this.controller.loadUrl($rawfile('index.html')); - } catch (error) { - console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); - } - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('loadUrl') + .onClick(() => { + try { + // Load a local resource file through $rawfile. + this.controller.loadUrl($rawfile('index.html')); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` 2. Using the resources protocol - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - - @Entry - @Component - struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController(); - - build() { - Column() { - Button('loadUrl') - .onClick(() => { - try { - // Load a local resource file through the resource protocol. - this.controller.loadUrl("resource://rawfile/index.html"); - } catch (error) { - console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); - } - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('loadUrl') + .onClick(() => { + try { + // Load local resource files through the resource protocol. + this.controller.loadUrl("resource://rawfile/index.html"); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` 3. Using a sandbox path. For details, see the example of loading local resource files in the sandbox in [Web](../arkui-ts/ts-basic-components-web.md#web). - HTML file to be loaded: - ```html - - - - -

Hello World

- - - ``` +HTML file to be loaded: +```html + + + + +

Hello World

+ + +``` ### loadData @@ -4320,6 +4320,107 @@ export default class EntryAbility extends UIAbility { } ``` +### setCustomUserAgent10+ + +setCustomUserAgent(userAgent: string): void + +Set a custom user agent. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------| ------- | ---- | ------------- | +| userAgent | string | Yes | Information about the custom user agent.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID | Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + @State userAgent: string = 'test' + + build() { + Column() { + Button('setCustomUserAgent') + .onClick(() => { + try { + this.controller.setCustomUserAgent(this.userAgent); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### getCustomUserAgent10+ + +getCustomUserAgent(): string + +Obtains a custom user agent. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ------ | ------------------------- | +| string | Information about the custom user agent.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID | Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + @State userAgent: string = '' + + build() { + Column() { + Button('getCustomUserAgent') + .onClick(() => { + try { + this.userAgent = this.controller.getCustomUserAgent(); + console.log("userAgent: " + this.userAgent); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + ## WebCookieManager Implements a **WebCookieManager** instance to manage behavior of cookies in **\** components. All **\** components in an application share a **WebCookieManager** instance. diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md b/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md index cad8cd31309b0e6098e0ab5b521d5c6f10ce0843..110905369abcd03d58cccdab4380d31aadf03f33 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md @@ -13,44 +13,54 @@ Supported Since API version 9, it is recommended that this component be used together with the **[\](ts-basic-components-navrouter.md)** component. - ## APIs -**API 1**: Navigation() +### Navigation + +Navigation() + +### Navigation10+ -**API 2**: Navigation(pathInfos: NavPathStack)10+ +Navigation(pathInfos: NavPathStack)10+ Binds a navigation stack to the **\** component. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------------------------------- | ---- | ------------- | -| pathInfos | [NavPathStack](#navpathstack10) | No | Information about the navigation stack.| +| Name | Type | Mandatory | Description | +| --------- | ------------------------------- | ---- | ------ | +| pathInfos | [NavPathStack](#navpathstack10) | No | Information about the navigation stack.| ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name | Type | Description | -| ----------------------------- | ---------------------------------------- | ---------------------------------------- | -| title | [ResourceStr](ts-types.md#resourcestr)10+ \| [CustomBuilder](ts-types.md#custombuilder8)8+ \| [NavigationCommonTitle](#navigationcommontitle)9+ \| [NavigationCustomTitle](#navigationcustomtitle)9+ | Page title.
**NOTE**
When the NavigationCustomTitle type is used to set the height, the **titleMode** attribute does not take effect.
When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped with an ellipsis (...); (2) If a subtitle is set, the subtitle is scaled down and then clipped with an ellipsis (...).| -| subTitle(deprecated) | string | Subtitle of the page. If this attribute is not set, no subtitle is displayed. This attribute is deprecated since API version 9. You are advised to use **title** instead.| -| menus | Array<[NavigationMenuItem](#navigationmenuitem)> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Menu items in the upper right corner of the page. If this attribute is not set, no menu item is displayed. When the value type is Array\<[NavigationMenuItem](#navigationmenuitem)>, the menu shows a maximum of three icons in portrait mode and a maximum of five icons in landscape mode, with excess icons (if any) placed under the automatically generated **More** icon.| -| titleMode | [NavigationTitleMode](#navigationtitlemode) | Display mode of the page title bar.
Default value: **NavigationTitleMode.Free**| -| toolBar(deprecated) | [object](#object) \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**items**: items on the toolbar.
**NOTE**
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area. If the text is too long, it is scaled down level by level, wrapped in two lines, and then clipped with an ellipsis (...).
This API is deprecated since API version 10. You are advised to use **toolbarConfiguration** instead.| +| Name | Type | Description | +| ---------------------------------- | ---------------------------------------- | ---------------------------------------- | +| title | [ResourceStr](ts-types.md#resourcestr)10+ \| [CustomBuilder](ts-types.md#custombuilder8)8+ \| [NavigationCommonTitle](#navigationcommontitle)9+ \| [NavigationCustomTitle](#navigationcustomtitle)9+ | Page title.
**NOTE**
When the NavigationCustomTitle type is used to set the height, the **titleMode** attribute does not take effect.
When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped with an ellipsis (...); (2) If a subtitle is set, the subtitle is scaled down and then clipped with an ellipsis (...).| +| subTitle(deprecated) | string | Subtitle of the page. If this attribute is not set, no subtitle is displayed. This attribute is deprecated since API version 9. You are advised to use **title** instead.| +| menus | Array<[NavigationMenuItem](#navigationmenuitem)> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Menu items in the upper right corner of the page. If this attribute is not set, no menu item is displayed. When the value type is Array<[NavigationMenuItem](#navigationmenuitem)>, the menu shows a maximum of three icons in portrait mode and a maximum of five icons in landscape mode, with excess icons (if any) placed under the automatically generated **More** icon.| +| titleMode | [NavigationTitleMode](#navigationtitlemode) | Display mode of the page title bar.
Default value: **NavigationTitleMode.Free**| +| toolBar(deprecated) | [object](#object) \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**items**: all items on the toolbar.
**NOTE**
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area. If the text is too long, it is scaled down level by level, wrapped in two lines, and then clipped with an ellipsis (...).
This API is deprecated since API version 10. You are advised to use **toolbarConfiguration** instead.| | toolbarConfiguration10+ | Array<[ToolbarItem](#toolbaritem10)10+> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**NOTE**
When the value type is Array<[ToolbarItem](#ToolbarItem>, the toolbar exhibits the following features:
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area.
If any item contains overlong text and there are fewer than five items, the following measures are taken: 1. Increase the item's width to accommodate the text until it is as large as the screen width; 2. Scale down the text level by level; 3. Wrap the text in two lines; 4. Clip the text with an ellipsis (...).
The toolbar shows a maximum of five icons in portrait mode, with excess icons (if any) placed under the automatically generated **More** icon. In landscape mode, this attribute must be used together with Array<[NavigationMenuItem](#navigationmenuitem)> of the **menus** attribute; the toolbar at the bottom is automatically hidden, and all items on the toolbar are moved to the menu in the upper right corner of the screen.
When the value type is [CustomBuilder](ts-types.md#custombuilder8), and the toolbar does not exhibit the preceding features except that items are evenly distributed on the toolbar at the bottom.| -| hideToolBar | boolean | Whether to hide the toolbar.
Default value: **false**
**true**: Hide the toolbar.
**false**: Display the toolbar.| -| hideTitleBar | boolean | Whether to hide the title bar.
Default value: **false**
**true**: Hide the title bar.
**false**: Display the title bar.| -| hideBackButton | boolean | Whether to hide the back button.
Default value: **false**
**true**: Hide the back button.
**false**: Display the back button.
The back button in the title bar of the **\** component cannot be hidden.
**NOTE**
The back button works only when **titleMode** is set to **NavigationTitleMode.Mini**.| -| navBarWidth9+ | [Length](ts-types.md#length) | Width of the navigation bar.
Default value: **240**
Unit: vp
**NOTE**
This attribute is valid only when the **\** component is split.| -| navBarPosition9+ | [NavBarPosition](#navbarposition) | Position of the navigation bar.
Default value: **NavBarPosition.Start**
**NOTE**
This attribute is valid only when the **\** component is split.| -| mode9+ | [NavigationMode](#navigationmode) | Display mode of the navigation bar.
Default value: **NavigationMode.Auto**
At the default settings, the component adapts to a single column or two columns based on the component width.
**NOTE**
Available options are **Stack**, **Split**, and **Auto**.| -| backButtonIcon9+ | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Back button icon on the navigation bar. The back button in the title bar of the **\** component cannot be hidden.| -| hideNavBar9+ | boolean | Whether to hide the navigation bar. This attribute is valid only when **mode** is set to **NavigationMode.Split**.| -| navDestination10+ | builder: (name: string, param: unknown) => void | Creates a **\** component.
**NOTE**
The **builder** function is used, with the **name** and **param** parameters passed in. In the builder, a layer of custom components can be included outside the **\** component. However, no attributes or events can be set for the custom components. Otherwise, only blank components are displayed.| -| navBarWidthRange10+ | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | Minimum and maximum widths of the navigation bar (valid in dual-column mode).
Default value: **240** for the minimum value; 40% of the component width (not greater than 432) for the maximum value
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.| -| minContentWidth10+ | [Dimension](ts-types.md#dimension10) | Minimum width of the navigation bar content area (valid in dual-column mode).
Default value: **360**
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.
Breakpoint calculation in Auto mode: default 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp)| +| hideToolBar | boolean | Whether to hide the toolbar.
Default value: **false**
**true**: Hide the toolbar.
**false**: Display the toolbar.| +| hideTitleBar | boolean | Whether to hide the title bar.
Default value: **false**
**true**: Hide the title bar.
**false**: Display the title bar.| +| hideBackButton | boolean | Whether to hide the back button.
Default value: **false**
**true**: Hide the back button.
**false**: Display the back button.
The back button in the title bar of the **\** component cannot be hidden.
**NOTE**
The back button works only when **titleMode** is set to **NavigationTitleMode.Mini**.| +| navBarWidth9+ | [Length](ts-types.md#length) | Width of the navigation bar.
Default value: **240**
Unit: vp
**NOTE**
This attribute is valid only when the **\** component is split.| +| navBarPosition9+ | [NavBarPosition](#navbarposition) | Position of the navigation bar.
Default value: **NavBarPosition.Start**
**NOTE**
This attribute is valid only when the **\** component is split.| +| mode9+ | [NavigationMode](#navigationmode) | Display mode of the navigation bar.
Default value: **NavigationMode.Auto**
At the default settings, the component adapts to a single column or two columns based on the component width.
**NOTE**
Available options are **Stack**, **Split**, and **Auto**.| +| backButtonIcon9+ | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Back button icon on the navigation bar. The back button in the title bar of the **\** component cannot be hidden.| +| hideNavBar9+ | boolean | Whether to hide the navigation bar. This attribute is valid only when **mode** is set to **NavigationMode.Split**.| +| navDestination10+ | builder: (name: string, param: unknown) => void | Creates a **\** component.
**NOTE**
The **builder** function is used, with the **name** and **param** parameters passed in. In the builder, a layer of custom components can be included outside the **\** component. However, no attributes or events can be set for the custom components. Otherwise, only blank components are displayed.| +| navBarWidthRange10+ | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | Minimum and maximum widths of the navigation bar (valid in dual-column mode).
Default value: **240** for the minimum value; 40% of the component width (not greater than 432) for the maximum value
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.| +| minContentWidth10+ | [Dimension](ts-types.md#dimension10) | Minimum width of the navigation bar content area (valid in dual-column mode).
Default value: **360**
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.
Breakpoint calculation in Auto mode: default 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp)| + +## Events + +| Name | Description | +| ---------------------------------------- | ---------------------------------------- | +| onTitleModeChange(callback: (titleMode: NavigationTitleMode) => void) | Called when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.| +| onNavBarStateChange(callback: (isVisible: boolean) => void) | Called when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite.| ## NavPathStack10+ @@ -64,9 +74,9 @@ Pushes the NavDestination page information specified by **info** to the stack. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| info | [NavPathInfo](#navpathinfo10) | Yes | Information about the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ----------------------------- | ---- | -------------------- | +| info | [NavPathInfo](#navpathinfo10) | Yes | Information about the navigation destination page.| ### pushPathByName10+ @@ -76,10 +86,10 @@ Pushes the navigation destination page specified by **name** to the navigation s **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | -| param | unknown | Yes | Parameter information of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------- | ---- | --------------------- | +| name | string | Yes | Name of the navigation destination page. | +| param | unknown | Yes | Parameter information of the navigation destination page.| ### pop10+ @@ -89,10 +99,10 @@ Pops the top element out of the navigation stack. **Return value** -| Type | Description | -| ------ | -------- | +| Type | Description | +| ----------- | ------------------------ | | NavPathInfo | Returns the information about the navigation destination page at the top of the stack.| -| undefined | Returns **undefined** if the navigation stack is empty.| +| undefined | Returns **undefined** if the navigation stack is empty. | ### popToName10+ @@ -102,14 +112,14 @@ Returns the navigation stack to the first navigation destination page that match **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------------- | +| name | string | Yes | Name of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | +| Type | Description | +| ------ | ---------------------------------------- | | number | Returns the index of the first navigation destination page that matches the value of **name** if it exists in the navigation stack; returns **-1** otherwise.| ### popToIndex10+ @@ -120,9 +130,9 @@ Returns the navigation stack to the navigation destination page that matches the **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| index | number | Yes | Index of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------- | +| index | number | Yes | Index of the navigation destination page.| ### moveToTop10+ @@ -132,14 +142,14 @@ Moves to the top of the navigation stack the first navigation destination page t **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------------- | +| name | string | Yes | Name of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | +| Type | Description | +| ------ | ---------------------------------------- | | number | Returns the index of the first navigation destination page that matches the value of **name** if it exists in the navigation stack; returns **-1** otherwise.| ### moveIndexToTop10+ @@ -150,9 +160,9 @@ Moves to the top of the navigation stack the navigation destination page that ma **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| index | number | Yes | Index of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------- | +| index | number | Yes | Index of the navigation destination page.| ### clear10+ @@ -168,8 +178,8 @@ Obtains the names of all navigation destination pages in the navigation stack. **Return value** -| Type | Description | -| ------ | -------- | +| Type | Description | +| -------------- | -------------------------- | | Array | Names of all navigation destination pages in the navigation stack.| ### getParamByIndex10+ @@ -180,16 +190,16 @@ Obtains the parameter information of the navigation destination page that matche **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| index | number | Yes | Index of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------- | +| index | number | Yes | Index of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | -| unknown | Returns the parameter information of the matching navigation destination page.| -| undefined | Returns **undefined** if the passed index is invalid.| +| Type | Description | +| --------- | -------------------------- | +| unknown | Returns the parameter information of the matching navigation destination page.| +| undefined | Returns **undefined** if the passed index is invalid. | ### getParamByName10+ @@ -199,15 +209,15 @@ Obtains the parameter information of all the navigation destination pages that m **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------------- | +| name | string | Yes | Name of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | -| Array | Parameter information of all the matching navigation destination pages.| +| Type | Description | +| --------------- | --------------------------------- | +| Array | Parameter information of all the matching navigation destination pages.| ### getIndexByName10+ @@ -217,15 +227,15 @@ Obtains the indexes information of all the navigation destination pages that mat **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------------- | +| name | string | Yes | Name of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | -| Array | Indexes of all the matching navigation destination pages.| +| Type | Description | +| -------------- | --------------------------------- | +| Array | Indexes of all the matching navigation destination pages.| ### size10+ @@ -235,9 +245,9 @@ Obtains the stack size. **Return value** -| Type | Description | -| ------ | -------- | -| number | Stack size.| +| Type | Description | +| ------ | ------ | +| number | Stack size.| ## NavPathInfo10+ @@ -249,52 +259,52 @@ constructor(name: string, param: unknown) **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | -| param | unknown | No | Parameter information of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------- | ---- | --------------------- | +| name | string | Yes | Name of the navigation destination page. | +| param | unknown | No | Parameter information of the navigation destination page.| ## NavigationMenuItem -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| value | string | Yes | Text of a menu item. | -| icon | string | No | Icon path of a menu item.| +| Name | Type | Mandatory | Description | +| ------ | ------------- | ---- | --------------- | +| value | string | Yes | Text of a menu item. | +| icon | string | No | Icon path of a menu item.| | action | () => void | No | Callback invoked when a menu item is selected. | ## object -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| value | string | Yes | Text of a toolbar item. | -| icon | string | No | Icon path of a toolbar item.| +| Name | Type | Mandatory | Description | +| ------ | ------------- | ---- | --------------- | +| value | string | Yes | Text of a toolbar item. | +| icon | string | No | Icon path of a toolbar item.| | action | () => void | No | Callback invoked when a toolbar item is selected. | ## ToolbarItem10+ -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------------- | ---- | ----------------------------------------------------------- | -| value | ResourceStr | Yes | Text of a toolbar item. | -| icon | ResourceStr | No | Icon path of a toolbar item. | -| action | () => void | No | Callback invoked when a toolbar item is selected. | -| status | [ToolbarItemStatus](#toolbaritemstatus10) | No | Status of a toolbar item.
Default value: **ToolbarItemStatus.NORMAL**| -| activeIcon | ResourceStr | No | Icon path of the toolbar item in the active state. | +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------------------- | ---- | ---------------------------------------- | +| value | ResourceStr | Yes | Text of a toolbar item. | +| icon | ResourceStr | No | Icon path of a toolbar item. | +| action | () => void | No | Callback invoked when a toolbar item is selected. | +| status | [ToolbarItemStatus](#toolbaritemstatus10) | No | Status of a toolbar item.
Default value: **ToolbarItemStatus.NORMAL**| +| activeIcon | ResourceStr | No | Icon path of the toolbar item in the active state. | ## ToolbarItemStatus10+ -| Name | Description | -| -------- | ------------------------------------------------------------ | +| Name | Description | +| -------- | ---------------------------------------- | | NORMAL | Normal state. In this state, the toolbar item takes on the default style and can switch to another state-specific style by responding to the hover, press, and focus events.| | DISABLED | Disabled state. In this state, the toolbar item is disabled and does not allow for user interactions.| | ACTIVE | Active state. In this state, the toolbar item can update its icon to the one specified by **activeIcon** by responding to a click event.| ## NavigationTitleMode -| Name| Description | -| ---- | ------------------------------------------------------------ | -| Free | When the content is a scrollable component, the main title shrinks as the content scrolls down (the subtitle fades out with its size remaining unchanged) and restores when the content scrolls up to the top.
**NOTE**
The size linkage effect works only when **title** is set to **ResourceStr** or **NavigationCommonTitle**. If **title** is set to any other value type, the main title changes in mere location when pulled down.| -| Mini | The title is fixed at mini mode. | -| Full | The title is fixed at full mode. | +| Name | Description | +| ---- | ---------------------------------------- | +| Free | When the content is a scrollable component, the main title shrinks as the content scrolls down (the subtitle fades out with its size remaining unchanged) and restores as the content scrolls up to the top.
**NOTE**
The size linkage effect works only when **title** is set to **ResourceStr** or **NavigationCommonTitle**. If **title** is set to any other value type, the main title changes in mere location when pulled down.| +| Mini | The title is fixed at mini mode. | +| Full | The title is fixed at full mode. | ## NavigationCommonTitle @@ -322,7 +332,7 @@ constructor(name: string, param: unknown) | Name | Description | | ----- | ------------------------------------------------------------ | | Stack | The navigation bar and content area are displayed independently of each other, which are equivalent to two pages. | -| Split | The navigation bar and content area are displayed in different columns. | +| Split | The navigation bar and content area are displayed in different columns.
The values of **navBarWidthRange** are represented by [minNavBarWidth,maxNavBarWidth].
1. When the value of **navBarWidth** is beyond the value range specified by **navBarWidthRange**, **navBarWidth** is set according to the following rules:
Value of **navBarWidth** < Value of **minNavBarWidth**: The value of **navBarWidth** is changed to that of **minNavBarWidth**.
Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) > Value of **maxNavBarWidth**: The value of **navBarWidth** is changed to that of **maxNavBarWidth**.
Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) < Value of **minNavBarWidth**: The value of **navBarWidth** is changed to that of **minNavBarWidth**.
Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) is within the value range specified by **navBarWidthRange**: The value of **navBarWidth** is changed to Component width - Value of **minContentWidth** - Divider width (1 vp).
2. When the value of **navBarWidth** is within the value range specified by **navBarWidthRange**, **navBarWidth** is set according to the following rules:
Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) > = Component width: The value of **navBarWidth** is changed to that of **minNavBarWidth**.
Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width and Value of **navBarWidth** + Value of **minContentWidth** + Divider width (1 vp) > = Component width: The value of **navBarWidth** is changed to Component width - Value of **minContentWidth** - Divider width (1 vp).
Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width and Value of **navBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width: The value of **navBarWidth** is the set value.
3. When the component size is decreased, the content area is shrunk until its width reaches the value defined by **minContentWidth**, and then the navigation bar is shrunk until its width reaches the value defined by **minNavBarWidth**; if the component size is further decreased, the content area is further shrunk until it disappears, and then navigation bar is shrunk.
4. When the navigation bar is set to a fixed size and the component size is continuously decreased, the navigation bar is shrunk.
5. If only **navBarWidth** is set, the width of the navigation bar is fixed at the value of **navBarWidth**, and the divider cannot be dragged.| | Auto | In API version 9 and earlier versions: When the window width is greater than or equal to 520 vp, the Split mode is used. In other cases, the Stack mode is used.
In API version 10 and later versions: When the window width is greater than or equal to 600 vp, the Split mode is used. In other cases, the Stack mode is used. 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp).| ## TitleHeight @@ -334,17 +344,10 @@ constructor(name: string, param: unknown) > **NOTE** +> > Among the scrollable components, only **\** is supported. -## Events - -| Name | Description | -| ---------------------------------------- | ---------------------------------------- | -| onTitleModeChange(callback: (titleMode: NavigationTitleMode) => void) | Called when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.| -| onNavBarStateChange(callback: (isVisible: boolean) => void) | Called when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite.| - - ## Example ```ts diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md b/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md index 07b043411ed7ce7658cb575490e559e0dbd3aab0..daf26e98a24a303138f9f79c88c4340c73ba629a 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md @@ -26,6 +26,11 @@ StepperItem() | nextLabel | string | Text label of the button on the right. The default value is **Start** for the last page and **Next** for the other pages.| | status | [ItemState](#itemstate) | Display status of **nextLabel** in the stepper. Optional.
Default value: **ItemState.Normal**| +> **NOTE** +> +> - The **\** component does not support setting of the universal width attribute. By default, its width is the same as that of the parent **\** component. +> - The **\** component does not support setting of the universal height attribute. Its height is the height of the parent **\** component minus the height of the label button. +> - The **\** component does not support setting of the **aspectRadio** or **constrainSize** attribute, which may affect the length and width. ## ItemState | Name | Description| diff --git a/en/application-dev/reference/arkui-ts/ts-container-list.md b/en/application-dev/reference/arkui-ts/ts-container-list.md index 4dd9922e85fcbb464dc189c032af8a2136e44f28..38195901492db82a74671c4dcdbaff902f44e707 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-list.md +++ b/en/application-dev/reference/arkui-ts/ts-container-list.md @@ -41,7 +41,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Description | | ------------ | ---------------------------------------- | ---- | ---------------------------------------- | -| space | number \| string | No | Spacing between list items along the main axis.
Default value: **0**
**NOTE**
If the set value is a negative number, the default value will be used.
If the value of **space** is less than the width of the list divider, the latter is used as the spacing.| +| space | number \| string | No | Spacing between list items along the main axis.
Default value: **0**
**NOTE**
If this parameter is set to a negative number or a value greater than or equal to the length of the list content area, the default value is used.
If this parameter is set to a value less than the width of the list divider, the width of the list divider is used as the spacing.| | initialIndex | number | No | Item displayed at the beginning of the viewport when the current list is loaded for the first time, that is, the first item to be displayed.
Default value: **0**
**NOTE**
If the set value is a negative number or is greater than the index of the last item in the list, the value is invalid. In this case, the default value will be used.| | scroller | [Scroller](ts-container-scroll.md#scroller) | No | Scroller, which can be bound to scrollable components.
**NOTE**
The scroller cannot be bound to other scrollable components.| diff --git a/en/application-dev/reference/errorcodes/errorcode-hiappevent.md b/en/application-dev/reference/errorcodes/errorcode-hiappevent.md index e0b7e16e0510883addf190635795e08c35a68502..11ac6f8288c316c21a1b410cabfaa42e5e62c7c7 100644 --- a/en/application-dev/reference/errorcodes/errorcode-hiappevent.md +++ b/en/application-dev/reference/errorcodes/errorcode-hiappevent.md @@ -1,4 +1,4 @@ -# Application Event Logging Error Codes +# Application Event Logging Error Codes > **NOTE** > @@ -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** diff --git a/en/application-dev/task-management/figures/bgtask_choice.png b/en/application-dev/task-management/figures/bgtask_choice.png index a5200006128dcead88e00da8434b4621e6c36472..8ac048571e10bf6ba902bf844ba2a7e02d5a9ddb 100644 Binary files a/en/application-dev/task-management/figures/bgtask_choice.png and b/en/application-dev/task-management/figures/bgtask_choice.png differ diff --git a/en/application-dev/task-management/work-scheduler.md b/en/application-dev/task-management/work-scheduler.md index ca419ee8142d7cf281b2e0ce30e6e64a37b01694..22c012478ff92d8ab81e0490b8cad570ad17362e 100644 --- a/en/application-dev/task-management/work-scheduler.md +++ b/en/application-dev/task-management/work-scheduler.md @@ -62,8 +62,8 @@ The table below lists the APIs used for developing deferred tasks. For details a | -------- | -------- | | startWork(work: WorkInfo): void; | Starts a deferred task.| | stopWork(work: WorkInfo, needCancel?: boolean): void; | Stops a deferred task.| -| getWorkStatus(workId: number, callback: AsyncCallback<WorkInfo>): void; | Obtains the status of a deferred task. This API uses an asynchronous callback to return the result.| -| getWorkStatus(workId: number): Promise<WorkInfo>; | Obtains the status of a deferred task. This API uses a promise to return the result.| +| getWorkStatus(workId: number, callback: AsyncCallback<WorkInfo>): void; | Obtains the information about a deferred task. This API uses an asynchronous callback to return the result.| +| getWorkStatus(workId: number): Promise<WorkInfo>; | Obtains the information about a deferred task. This API uses a promise to return the result.| | obtainAllWorks(callback: AsyncCallback<void>): Array<WorkInfo>; | Obtains all the deferred tasks. This API uses an asynchronous callback to return the result.| | obtainAllWorks(): Promise<Array<WorkInfo>>; | Obtains all the deferred tasks. This API uses a promise to return the result.| | stopAndClearWorks(): void; | Stops and clears all the deferred tasks.| @@ -77,7 +77,7 @@ The table below lists the APIs used for developing deferred tasks. For details a | bundleName | string | Bundle name of the application that requests the deferred task.| | abilityName | string | Name of the ability to be notified by a deferred task scheduling callback. This parameter is mandatory.| | networkType | [NetworkType](../reference/apis/js-apis-resourceschedule-workScheduler.md#networktype) | Network type.| -| isCharging | boolean | Whether the device is charging.| +| isCharging | boolean | Whether the device needs to enter the charging state to trigger deferred task scheduling.| | chargerType | [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | Charging type.| | batteryLevel | number | Battery level.| | batteryStatus | [BatteryStatus](../reference/apis/js-apis-resourceschedule-workScheduler.md#batterystatus) | Battery status.| diff --git a/en/application-dev/ui/arkts-layout-development-create-list.md b/en/application-dev/ui/arkts-layout-development-create-list.md index 32c4322ae5247bbf8ac79b29667593d660795806..cbb633c5d19bda73a973fff66574dd537dd51f2c 100644 --- a/en/application-dev/ui/arkts-layout-development-create-list.md +++ b/en/application-dev/ui/arkts-layout-development-create-list.md @@ -299,7 +299,7 @@ List() { }) ``` -This example draws a divider with a stroke thickness of 1 vp from a position 60 vp away from the start edge of the list to a position 10 vp away from the end edge of the list. The effect is shown in Figure 8. +This example draws a divider with a stroke thickness of 1 vp from a position 60 vp away from the start edge of the list to a position 10 vp away from the end edge of the list. The effect is shown in Figure 9. >**NOTE** > @@ -653,8 +653,6 @@ The following describes the implementation of the pull-and-refresh feature: 3. Listen for the finger lift event. If the movement reaches the maximum value, trigger data loading and display the refresh view. After the loading is complete, hide the view. - You can also use the third-party component [PullToRefresh](https://gitee.com/openharmony-sig/PullToRefresh) to implement this feature. - ## Editing a List diff --git a/en/application-dev/ui/arkts-routing.md b/en/application-dev/ui/arkts-routing.md index 5ccf781293c12b40eedfb6949b0ef268c79d4699..ef6b72ab27dbd5847ceb16f9b732aadbff1ec402 100644 --- a/en/application-dev/ui/arkts-routing.md +++ b/en/application-dev/ui/arkts-routing.md @@ -11,23 +11,26 @@ Page redirection is an important part of the development process. When using an **Figure 1** Page redirection ![router-jump-to-detail](figures/router-jump-to-detail.gif) -The **Router** module provides two redirection modes: [router.pushUrl()](../reference/apis/js-apis-router.md#routerpushurl9) and [router.replaceUrl()](../reference/apis/js-apis-router.md#routerreplaceurl9). The two modes determine whether the target page will replace the current page. +The **Router** module provides two redirection modes: [router.pushUrl()](../reference/apis/js-apis-router.md#routerpushurl9) and [router.replaceUrl()](../reference/apis/js-apis-router.md#routerreplaceurl9). Whether the target page will replace the current page depends on the mode used. -- **router.pushUrl()**: The target page does not replace the current page. Instead, it is pushed into the [page stack](../application-models/page-mission-stack.md). In this way, the state of the current page can be retained, and users can return to the current page by pressing the back button or calling the [router.back()](../reference/apis/js-apis-router.md#routerback) API. +- **router.pushUrl()**: The target page is pushed into the [page stack](../application-models/page-mission-stack.md) and does not replace the current page. In this mode, the state of the current page is retained, and users can return to the current page by pressing the back button or calling the [router.back()](../reference/apis/js-apis-router.md#routerback) API. -- **router.replaceUrl()**: The target page replaces the current page and destroys the current page. In this way, the resources of the current page can be released, and users cannot return to the current page. +- **router.replaceUrl()**: The target page replaces and destroys the current page. In this mode, the resources of the current page can be released, and users cannot return to the current page. >**NOTE** > ->The maximum capacity of a page stack is 32 pages. If this limit is exceeded, the [router.clear()](../reference/apis/js-apis-router.md#routerclear) API can be called to clear the historical page stack and free the memory. +>- When creating a page, configure the route to this page by following instructions in [Building the Second Page](../quick-start/start-with-ets-stage.md). +> +> +>- The maximum capacity of a page stack is 32 pages. If this limit is exceeded, the [router.clear()](../reference/apis/js-apis-router.md#routerclear) API can be called to clear the historical page stack and free the memory. -The **Router** module also provides two instance modes: **Standard** and **Single**. The two modes determine whether the target URL corresponds to multiple instances. +The **Router** module also provides two instance modes: **Standard** and **Single**. Depending on the mode, the target URL is mapped to one or more instances. -- **Standard**: standard instance mode, which is the default instance mode. Each time this API is called, a target page is created and pushed to the top of the stack. +- **Standard**: multi-instance mode. It is the default instance mode. In this mode, the target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack. -- **Single**: singleton mode. If the URL of the target page already exists in the page stack, the page with the same URL closest to the top of the stack is moved to the top of the stack and reloaded. If the URL of the target page does not exist in the page stack, the page is redirected in standard mode. +- **Single**: singleton mode. In this mode, if the URL of the target page already exists in the page stack, the page closest to the top of the stack with the same URL is moved to the top of the stack and becomes the new page. If the URL of the target page does not exist in the page stack, the page is redirected in standard mode. -Before using the **Router** module, you need to import it to the code. +Before using the **Router** module, import it first. ```ts @@ -54,7 +57,7 @@ import router from '@ohos.router'; >**NOTE** > - >In **Standard** instance mode, the **router.RouterMode.Standard** parameter can be omitted. + >In standard (multi-instance) mode, the **router.RouterMode.Standard** parameter can be omitted. - Scenario 2: There is a login page (**Login**) and a personal center page (**Profile**). After a user successfully logs in from the **Login** page, the **Profile** page is displayed. At the same time, the **Login** page is destroyed, and the application exits when the back button is pressed. In this scenario, you can use the **replaceUrl()** API and use the Standard instance mode (which can also be omitted). @@ -76,7 +79,7 @@ import router from '@ohos.router'; >**NOTE** > - >In **Standard** instance mode, the **router.RouterMode.Standard** parameter can be omitted. + >In standard (multi-instance) mode, the **router.RouterMode.Standard** parameter can be omitted. - Scenario 3: There is a setting page (**Setting**) and a theme switching page (**Theme**). You want to click a theme option on the **Setting** page to go to the **Theme** page. In addition, you want to ensure that only one **Theme** page exists in the page stack at a time. When the back button is clicked on the **Theme** page, the **Setting** page is displayed. In this scenario, you can use the **pushUrl()** API and use the **Single** instance mode. @@ -115,7 +118,7 @@ import router from '@ohos.router'; The preceding scenarios do not involve parameter transfer. -If you need to transfer some data to the target page during redirection, you can add a **params** attribute and specify an object as a parameter when invoking an API of the **Router** module. Example: +If you need to transfer data to the target page during redirection, you can add a **params** attribute and specify an object as a parameter when invoking an API of the **Router** module. Example: ```ts @@ -150,11 +153,11 @@ function onJumpClick(): void { } ``` -On the target page, you can call the [getParams()](../reference/apis/js-apis-router.md#routergetparams) API of the **Router** module to obtain the transferred parameters. Example: +On the target page, you can call the [getParams()](../reference/apis/js-apis-router.md#routergetparams) API of the **Router** module to obtain the passed parameters. Example: ```ts -const params = router.getParams(); // Obtain the transferred parameter object. +const params = router.getParams(); // Obtain the passed parameters. const id = params['id']; // Obtain the value of the id attribute. const age = params['info'].age; // Obtain the value of the age attribute. ``` @@ -162,13 +165,13 @@ const age = params['info'].age; // Obtain the value of the age attribute. ## Page Return -After a user completes an operation on a page, the user usually needs to return to the previous page or a specified page. In this case, the page return function is required. During the return process, the data may need to be transferred to the target page, which requires the data transfer function. +Implement the page return feature so that users can return to the previous page or a specified page. You can pass parameters to the target page during the return process. **Figure 2** Page return ![router-back-to-home](figures/router-back-to-home.gif) -Before using the **Router** module, you need to import it to the code. +Before using the **Router** module, import it first. ```ts @@ -195,7 +198,7 @@ You can use any of the following methods to return to a page: }); ``` - This method allows you to return to a specified page. You need to specify the path of the target page. For this method to work, the target page must it exist in the page stack. + This method allows uesrs to return to a page with the specified path. For this method to work, the target page must exist in the page stack. - Method 3: Return to the specified page and transfer custom parameter information. @@ -209,14 +212,14 @@ You can use any of the following methods to return to a page: }); ``` - This method not only allows you to return to the specified page, but also transfer custom parameter information when returning. The parameter information can be obtained and parsed by invoking the **router.getParams()** API on the target page. + This method not only allows you to return to the specified page, but also pass in custom parameter information during the return process. The parameter information can be obtained and parsed by invoking the **router.getParams()** API on the target page. On the target page, call the **router.getParams()** API at the position where parameters need to be obtained, for example, in the **onPageShow()** lifecycle callback: ```ts onPageShow() { - const params = router.getParams(); // Obtain the transferred parameter object. + const params = router.getParams(); // Obtain the passed parameters. const info = params['info']; // Obtain the value of the info attribute. } ``` @@ -243,7 +246,7 @@ Such a dialog box can be in the [default style](#default-confirmation-dialog-box To implement this function, you can use the [router.showAlertBeforeBackPage()](../reference/apis/js-apis-router.md#routershowalertbeforebackpage9) and [router.back()](../reference/apis/js-apis-router.md#routerback) APIs provided by the **Router** module. -Before using the **Router** module, you need to import it to the code. +Before using the **Router** module, import it first. ```ts @@ -272,17 +275,16 @@ function onBackClick(): void { The **router.showAlertBeforeBackPage()** API receives an object as a parameter. The object contains the following attributes: -- **message**: content of the dialog box. The value is of the string type. - If the API is successfully called, the confirmation dialog box is displayed on the target page. Otherwise, an exception is thrown and the error code and error information is obtained through **err.code** and **err.message**. - - When the user clicks the back button, a confirmation dialog box is displayed, prompting the user to confirm their operation. If the user selects Cancel, the application stays on the current page. If the user selects OK, the **router.back()** API is triggered and the redirection is performed based on the parameters. +**message**: content of the dialog box. The value is of the string type. +If the API is successfully called, the confirmation dialog box is displayed on the target page. Otherwise, an exception is thrown and the error code and error information is obtained through **err.code** and **err.message**. +When the user clicks the back button, a confirmation dialog box is displayed, prompting the user to confirm their operation. If the user selects Cancel, the application stays on the current page. If the user selects OK, the **router.back()** API is triggered and the redirection is performed based on the parameters. ### Custom Confirmation Dialog Box To implement a custom confirmation dialog box, use APIs in the [PromptAction](../reference/apis/js-apis-promptAction.md#promptactionshowdialog) module or customize a popup window. This topic uses the APIs in the **PromptAction** module an example to describe how to implement a custom confirmation dialog box. -Before using the **Router** module, you need to import it to the code. +Before using the **Router** module, import it first. ```ts @@ -324,3 +326,63 @@ function onBackClick() { ``` When the user clicks the back button, the custom confirmation dialog box is displayed, prompting the user to confirm their operation. If the user selects Cancel, the application stays on the current page. If the user selects OK, the **router.back()** API is triggered and the redirection is performed based on the parameters. + +## Named Route + +To redirect to a [page in a shared package](../quick-start/shared-guide.md), you can use [router.pushNamedRoute()](../reference/apis/js-apis-router.md#routerpushnamedroute10). + +Before using the **Router** module, import it first. + + +```ts +import router from '@ohos.router'; +``` + +In the target page in the [shared package](../quick-start/shared-guide.md), name the [@Entry decorated custom component](../quick-start/arkts-create-custom-components.md#entryoptions10). + +```ts +// library/src/main/ets/pages/Index.ets +@Entry({ routeName : 'myPage' }) +@Component +struct MyComponent { +} +``` + +When the configuration is successful, import the named route page to the page from which you want to redirect. + +```ts +// entry/src/main/ets/pages/Index.ets +import router from '@ohos.router'; +import 'library/src/main/ets/Index.ets' // Import the named route page from the shared package library. + +@Entry +@Component +struct Index { + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('Hello World') + .fontSize(50) + .fontWeight(FontWeight.Bold) + .margin({ top: 20 }) + .backgroundColor('#ccc') + .onClick(() => { // Click to go to a page in another shared package. + try { + router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } + } + }) + } catch (err) { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); + } + }) + } + .width('100%') + .height('100%') + } +} +``` diff --git a/en/device-dev/subsystems/subsys-dfx-hisysevent-listening.md b/en/device-dev/subsystems/subsys-dfx-hisysevent-listening.md index 613c624e1a155a1a97e6e042eb9b4a906947ee76..95bdd78be0231342ffac333ca4f15c43654cd5e2 100644 --- a/en/device-dev/subsystems/subsys-dfx-hisysevent-listening.md +++ b/en/device-dev/subsystems/subsys-dfx-hisysevent-listening.md @@ -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<HiSysEventListener> listener, std::vector<ListenerRule>& rules) | Registers a listener for system events. You can listen for certain events by specifying rules.
Input arguments:
- **listener**: callback object for system events.
- **rules**: rules for event listening.
Return value:
- **0**: Registration is successful.
- A negative value: Registration has failed.| -| int32_t HiSysEventManager::RemoveListener(std::shared_ptr<HiSysEventListener> listener) | Removes the listener for system events.
Input arguments:
- **listener**: callback object for system events.
Return value:
- **0**: Canceling registration is successful.
- 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& tag, RuleType ruleType = RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event tag.
Input arguments:
- **tag**: event tag for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, lowercase letters, and digits.
- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.| -| ListenerRule(const std::string& domain, const std::string& eventName, RuleType ruleType = RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event domain and event name.
Input arguments:
- **domain**: event domain for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, digits, and underscores.
- **eventName**: event name for the **ListenerRule** object. The value is a string of 1 to 32 characters, including uppercase letters, digits, and underscores.
- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.| -| ListenerRule(const std::string& domain, const std::string& eventName, const std::string& tag, RuleType ruleType = RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event domain, event name, and event tag.
Input arguments:
- **tag**: event tag for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, lowercase letters, and digits.
- **domain**: event domain for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, digits, and underscores.
- **eventName**: event name for the **ListenerRule** object. The value is a string of 1 to 32 characters, including uppercase letters, digits, and underscores.
- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.| +| int32_t HiSysEventManager::AddListener(std::shared_ptr<HiSysEventListener> listener,
 std::vector<ListenerRule>& rules) | Adds a listener to listen for system events based on the specified rules.
Input arguments:
- **listener**: listener for system events.
- **rules**: event listening rules.
Return value:
- **0**: The listener is added successfully.
- A negative value: The listener fails to be added.| +| int32_t HiSysEventManager::RemoveListener(std::shared_ptr<HiSysEventListener> listener) | Removes the listener for system events.
Input arguments:
- **listener**: listener for system events.
Return value:
- **0**: The listener is removed successfully.
- 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 std::string& tag,
 RuleType ruleType = RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event tag.
Input arguments:
- **tag**: event tag for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, lowercase letters, and digits.
- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.| +| ListenerRule(const std::string& domain,
 const std::string& eventName,
 RuleType ruleType = RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event domain and event name.
Input arguments:
- **domain**: event domain for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, digits, and underscores.
- **eventName**: event name for the **ListenerRule** object. The value is a string of 1 to 32 characters, including uppercase letters, digits, and underscores.
- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.| +| ListenerRule(const std::string& domain,
 const std::string& eventName,
 const std::string& tag,
 RuleType ruleType = RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event domain, event name, and event tag.
Input arguments:
- **tag**: event tag for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, lowercase letters, and digits.
- **domain**: event domain for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, digits, and underscores.
- **eventName**: event name for the **ListenerRule** object. The value is a string of 1 to 32 characters, including uppercase letters, digits, and underscores.
- **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<HiSysEventRecord> sysEvent) | Callback object for system events.
Input arguments:
- **sysEvent**: real-time system events.
Return value:
None.| -| void HiSysEventListener::OnServiceDied() | Callback object for service exceptions.
Input arguments:
None.
Return value:
None.| +| void HiSysEventListener::OnEvent(std::shared_ptr<HiSysEventRecord> sysEvent) | Callback object for system events.
Input arguments:
- **sysEvent**: real-time system event.
Return value:
None.| +| void HiSysEventListener::OnServiceDied() | Callback object for service exceptions.
Input arguments:
None.
Return value:
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.
Input arguments:
None.
Return value:
Content of the system event.| -|std::string HiSysEventRecord::GetDomain()|Obtains the domain name of a system event.
Input arguments:
None.
Return value:
Domain name of the system event.| -|std::string HiSysEventRecord::GetEventName()|Obtains the name of a system event.
Input arguments:
None.
Return value:
Name of the system event.| -|HiSysEvent::EventType HiSysEventRecord::GetEventType()|Obtains the type of a system event.
Input arguments:
None.
Return value:
Type of the system event.| -|std::string HiSysEventRecord::GetLevel()|Obtains the level of a system event.
Input arguments:
None.
Return value:
Level of the system event.| -|std::string HiSysEventRecord::GetTag()|Obtains the tag of a system event.
Input arguments:
None.
Return value:
Tag of the system event.| -|std::string HiSysEventRecord::GetTimeZone()|Obtains the time zone of a system event.
Input arguments:
None.
Return value:
Time zone, in the format of **+0800**.| -|int HiSysEventRecord::GetTraceFlag()|Obtains the distributed call chain tracing flag of a system event.
Input arguments:
None.
Return value:
Distributed call chain tracing flag.| -|int64_t HiSysEventRecord::GetPid()|Obtains the ID of the process that flushes a system event to the disk.
Input arguments:
None.
Return value:
Process ID.| -|int64_t HiSysEventRecord::GetTid()|Obtains the thread ID of the process that flushes a system event to the disk.
Input arguments:
None.
Return value:
Thread ID.| -|int64_t HiSysEventRecord::GetUid()|Obtains the user ID of the process that flushes a system event to the disk.
Input arguments:
None.
Return value:
User ID.| -|uint64_t HiSysEventRecord::GetPspanId()|Obtains the parent span ID of the distributed call chain tracing task.
Input arguments:
None.
Return value:
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.
Input arguments:
None.
Return value:
Span ID of the distributed call chain tracing task.| -|uint64_t HiSysEventRecord::GetTime()|Obtains the timestamp of a system event.
Input arguments:
None.
Return value:
Timestamp of the system event.| -|uint64_t HiSysEventRecord::GetTraceId()|Obtains the ID of the distributed call chain tracing task.
Input arguments:
None.
Return value:
ID of the distributed call chain tracing task.| -|void HiSysEventRecord::GetParamNames(std::vector<std::string>& params)|Obtains all key names of a system event.
Input arguments:
- **params**: key name array reference.
Return value:
None.| -|int HiSysEventRecord::GetParamValue(const std::string& param, int64_t& value)|Parses the value of the **param** key in a system event into an int64\_t value.
Input arguments:
- **param**: key name.
- **value**: int64\_t reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.| -|int HiSysEventRecord::GetParamValue(const std::string& param, uint64_t& value)|Parses the value of the **param** key in a system event into a uint64\_t value.
Input arguments:
- **param**: key name.
- **value**: uint64\_t reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.| -|int HiSysEventRecord::GetParamValue(const std::string& param, double& value)|Parses the value of the **param** key in a system event into a double value.
Input arguments:
- **param**: key name.
- **value**: double reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.| -|int HiSysEventRecord::GetParamValue(const std::string& param, std::string& value)|Parses the value of the **param** key in a system event into a string value.
Input arguments:
- **param**: key name.
- **value**: std::string reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.| -|int HiSysEventRecord::GetParamValue(const std::string& param, std::vector<int64_t>& value)|Parses the value of the **param** key in a system event into an int64\_t array.
Input arguments:
- **param**: key name.
- **value**: int64\_t array reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.| -|int HiSysEventRecord::GetParamValue(const std::string& param, std::vector<uint64_t>& value)|Parses the value of the **param** key in a system event into a uint64\_t array.
Input arguments:
- **param**: key name.
- **value**: uint64\_t array reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.| -|int HiSysEventRecord::GetParamValue(const std::string& param, std::vector<double>& value)|Parses the value of the **param** key in a system event into a double array.
Input arguments:
- **param**: key name.
- **value**: double array reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.| -|int HiSysEventRecord::GetParamValue(const std::string& param, std::vector<std::string>& value)|Parses the value of the **param** key in a system event into a string array.
Input arguments:
- **param**: key name.
- **value**: std::string array reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.| - - -## How to Develop - - -### **C++** - -The following provides an example of how to use C++ APIs of **HiSysEvent**. - -1. Develop the source code. - Import the **DemoListener.h** header file, which contains the **DemoListener** class for implementing the custom event callback. - - ``` - #ifndef DEMO_LISTENER_H - #define DEMO_LISTENER_H - - #include "hisysevent_listener.h" - - #include - - class DemoListener : public OHOS::HiviewDFX::HiSysEventListener { - public: - explicit DemoListener() : HiSysEventListener() {} - virtual ~DemoListener() {} - - public: - void OnEvent(std::shared_ptr sysEvent); - void OnServiceDied(); - }; - - #endif // DEMO_LISTENER_H - ``` - - Create the **DemoListener.cpp** file, and add the implementation logic of the custom event callback API in the **DemoListener** class. - - ``` - #include "demo_listener.h" - - #include - - void DemoListener::OnEvent(std::shared_ptr sysEvent) - { - if (sysEvent == nullptr) { - return; +|std::string HiSysEventRecord::AsJson()|Obtains the content of a system event.
Input arguments:
None.
Return value:
Content of the system event.| +|std::string HiSysEventRecord::GetDomain()|Obtains the domain name of a system event.
Input arguments:
None.
Return value:
Domain name of the system event.| +|std::string HiSysEventRecord::GetEventName()|Obtains the name of a system event.
Input arguments:
None.
Return value:
Name of the system event.| +|HiSysEvent::EventType HiSysEventRecord::GetEventType()|Obtains the type of a system event.
Input arguments:
None.
Return value:
Type of the system event.| +|std::string HiSysEventRecord::GetLevel()|Obtains the level of a system event.
Input arguments:
None.
Return value:
Level of the system event.| +|std::string HiSysEventRecord::GetTag()|Obtains the tag of a system event.
Input arguments:
None.
Return value:
Tag of the system event.| +|std::string HiSysEventRecord::GetTimeZone()|Obtains the time zone of a system event.
Input arguments:
None.
Return value:
Time zone, in the format of **+0800**.| +|int HiSysEventRecord::GetTraceFlag()|Obtains the distributed call chain tracing flag of a system event.
Input arguments:
None.
Return value:
Distributed call chain tracing flag.| +|int64_t HiSysEventRecord::GetPid()|Obtains the ID of the process that flushes a system event to the disk.
Input arguments:
None.
Return value:
Process ID.| +|int64_t HiSysEventRecord::GetTid()|Obtains the thread ID of the process that flushes a system event to the disk.
Input arguments:
None.
Return value:
Thread ID.| +|int64_t HiSysEventRecord::GetUid()|Obtains the user ID of the process that flushes a system event to the disk.
Input arguments:
None.
Return value:
User ID.| +|uint64_t HiSysEventRecord::GetPspanId()|Obtains the parent span ID of the distributed call chain tracing task.
Input arguments:
None.
Return value:
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.
Input arguments:
None.
Return value:
Span ID of the distributed call chain tracing task.| +|uint64_t HiSysEventRecord::GetTime()|Obtains the timestamp of a system event.
Input arguments:
None.
Return value:
Timestamp.| +|uint64_t HiSysEventRecord::GetTraceId()|Obtains the ID of the distributed call chain tracing task.
Input arguments:
None.
Return value:
ID of the distributed call chain tracing task.| +|void HiSysEventRecord::GetParamNames(std::vector<std::string>& params)|Obtains all key names of a system event.
Input arguments:
- **params**: key name array reference.
Return value:
None.| +|int HiSysEventRecord::GetParamValue(const std::string& param, int64_t& value)|Parses the value of the **param** key in a system event into an int64\_t value.
Input arguments:
- **param**: key name.
- **value**: int64\_t reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.| +|int HiSysEventRecord::GetParamValue(const std::string& param, uint64_t& value)|Parses the value of the **param** key in a system event into a uint64\_t value.
Input arguments:
- **param**: key name.
- **value**: uint64\_t reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.| +|int HiSysEventRecord::GetParamValue(const std::string& param, double& value)|Parses the value of the **param** key in a system event into a double value.
Input arguments:
- **param**: key name.
- **value**: double reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.| +|int HiSysEventRecord::GetParamValue(const std::string& param, std::string& value)|Parses the value of the **param** key in a system event into a string value.
Input arguments:
- **param**: key name.
- **value**: std::string reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.| +|int HiSysEventRecord::GetParamValue(const std::string& param, std::vector<int64_t>& value)|Parses the value of the **param** key in a system event into an int64\_t array.
Input arguments:
- **param**: key name.
- **value**: int64\_t array reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.| +|int HiSysEventRecord::GetParamValue(const std::string& param, std::vector<uint64_t>& value)|Parses the value of the **param** key in a system event into a uint64\_t array.
Input arguments:
- **param**: key name.
- **value**: uint64\_t array reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.| +|int HiSysEventRecord::GetParamValue(const std::string& param, std::vector<double>& value)|Parses the value of the **param** key in a system event into a double array.
Input arguments:
- **param**: key name.
- **value**: double array reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.| +|int HiSysEventRecord::GetParamValue(const std::string& param, std::vector<std::string>& value)|Parses the value of the **param** key in a system event into a string array.
Input arguments:
- **param**: key name.
- **value**: std::string array reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-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,
HiSysEventWatchRule rules[],
size_t ruleSize); | Adds a listener to listen for system events based on the specified rules.
Input arguments:
- **watcher**: watcher for system events.
- **rules**: array of event listening rules.
- **ruleSize**: length of the array of event listening rules.
Return value:
- **0**: The listener is added successfully.
- A negative value: The listener fails to be added.| +| int OH_HiSysEvent_Remove_Watcher(HiSysEventWatcher* watcher); | Remove the watcher for system events.
Input arguments:
- **watcher**: watcher for system events.
Return value:
- **0**: The watcher is removed successfully.
- 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.
Input arguments:
- **record**: real-time system event.
Return value:
None.| +| OnServiceDied | void (*)(); | Callback object for service exceptions.
Input arguments:
None.
Return value:
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. + + ```c++ + class TestListener : public OHOS::HiviewDFX::HiSysEventListener { + public: + void OnEvent(std::shared_ptr 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++ + auto testListener = std::make_shared(); + // 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 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); + } + ``` + +#### C HiSysEvent Listening + +1. Import the corresponding header file. + + ```c++ + #include "hisysevent_manager_c.h" + ``` + +2. Implement the callback API for the service domain. + + ```c++ + void OnEventTest(HiSysEventRecord record) + { + printf("OnEventTest: event=%s", record.jsonStr); + } + + void OnServiceDiedTest() + { + printf("OnServiceDied"); + } + ``` + +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); + } + ``` + +### 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", + ] + ``` + +2. Call the listening API in the **TestEventListening()** function. When the service ends, disable event listening. + + ```c++ + #include + + #include "hisysevent_manager.h" + + using namespace OHOS::HiviewDFX; + + class TestListener : public HiSysEventQueryCallback { + public: + void OnEvent(std::shared_ptr record) + { + if (record == nullptr) { + return; + } + std::cout << record->AsJson() << std::endl; + } + + void OnServiceDied() + { + std::cout << std::string("service disconnect, exit") << std::endl; + exit(0); + } + }; + + void TestEventListening() + { + auto testListener = std::make_shared(); + ListenerRule domainNameRule("HIVIEWDFX", "PLUGIN_LOAD", RuleType::WHOLE_WORD); + std::vector sysRules; + sysRules.push_back(domainNameRule); + auto ret = HiSysEventManager::AddEventListener(testListener, sysRules); + if (ret == 0) { + HiSysEventManager::RemoveListener(testListener); + } + } + ``` + +#### 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" ] + ``` + +2. Call the listening API in the **TestEventListening()** function. When the service ends, disable event listening. + + ```c++ + #include + + #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); } - std::cout << sysEvent.AsJson() << std::endl; - } - - void DemoListener::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(); - // 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 sysRules; - sysRules.push_back(tagRule); - sysRules.push_back(regRule); - sysRules.push_back(domainNameRule); - HiSysEventManager::AddEventListener(demoListener, sysRules); - ``` - -2. Configure the **BUILD.gn** file. - In the **BUILD.gn** file, add the **libhisysevent** and **libhisyseventmanager** libraries that depend on the **hisysevent** component. - - ``` - external_deps = [ - "hisysevent:libhisysevent", - "hisysevent:libhisyseventmanager", - ] - ``` + } + ``` diff --git a/en/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md b/en/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md index 940b8188945ffdc01c6b35a44a27019339a69768..0e50997085deb3c75f917cfeaac8af51711d1eb1 100644 --- a/en/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md +++ b/en/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md @@ -33,10 +33,11 @@ Constraints on the event domain, event name, and parameter | Field| Description| | -------- | -------- | - | type | Event type. This field is mandatory.
Value:
- FAULT: fault
- STATISTIC: statistics
- SECURITY: security
- BEHAVIOR: user behavior| + | type | Event type. This field is mandatory.
Value:
- **FAULT**: fault
- STATISTIC: statistics
- **SECURITY**: security
- **BEHAVIOR**: behavior| | level | Event level. This field is mandatory.
Value:
- CRITICAL: critical
- MINOR: minor| | tag | Event tag. This field is mandatory.
Rule:
- You can define a maximum of five tags, separated with a space.
- 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.
Rule:
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.
Rule:
- 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**.
Value:
- **true**: Events need to be logged in the event file.
- **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.
Value:
- BOOL
- INT8
- UINT8
- INT16
- UINT16
- INT32
- UINT32
- INT64
- UINT64
- FLOAT
- DOUBLE
- STRING | | arrsize | Length of the parameter of the array type. This field is optional.
Value:
1-100| - | desc | Parameter description. This field is mandatory.
Rule:
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.
Rule:
- A string of 3 to 128 characters.| ## How to Develop diff --git a/en/device-dev/subsystems/subsys-dfx-hisysevent-query.md b/en/device-dev/subsystems/subsys-dfx-hisysevent-query.md index 88fd95fd4aafaa5d4d27d0da7649cceb7836d577..fe4151d04c5a38dd9edac2defa06648b7a849e49 100644 --- a/en/device-dev/subsystems/subsys-dfx-hisysevent-query.md +++ b/en/device-dev/subsystems/subsys-dfx-hisysevent-query.md @@ -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 QueryArg& arg,
std::vector<QueryRule>& rules,
std::shared_ptr<HiSysEventQueryCallback> callback) | Queries system events by search criteria such as the time segment, event domain, and event name.
Input arguments:
- **arg**: event query parameter.
- **rules**: rules for event filtering.
- **callback**: callback object for event query.
Return value:
- **0**: Query is successful.
- A negative value: Query has failed.| +| int32_t Query(struct QueryArg& arg,
std::vector<QueryRule>& rules,
std::shared_ptr<HiSysEventQueryCallback> callback) | Queries system events by search criteria such as the time segment, event domain, and event name.
Input arguments:
- **arg**: event query parameter.
- **rules**: event filtering rules.
- **callback**: callback object for event query.
Return value:
- **0**: Query is successful.
- 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 std::string& domain,
const std::vector<std::string>& eventList) | Constructor used to create a **QueryRule** object.
Input arguments:
- **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.
**eventList**: event name list, in the **std::vector<std::string>** format. By default, an empty string indicates that the event names on the list are successfully matched.| +| QueryRule(const std::string& domain,
const std::vector<std::string>& eventList,
RuleType ruleType,
uint32_t eventType,
const std::string& cond) | Constructor used to create a **QueryRule** object.
Input arguments:
- **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.
**eventList**: event name list, in the **std::vector<std::string>** format. By default, an empty string indicates that the event names on the list are successfully matched.
- **ruleType**: rule type. For details, see Table 4.
- **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.
- **cond**: query criteria. The value is of the string type.| + +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 4** Description of HiSysEventQueryCallback objects -| API| Description| + + + +**Table 6** Description of HiSysEventQueryCallback objects + +| Name| Description| | -------- | -------- | | void HiSysEventQueryCallback::OnQuery(std::shared_ptr<std::vector<HiSysEventRecord>> sysEvents) | Callback object for event query.
Input arguments:
- **sysEvents**: event list.| | void HiSysEventQueryCallback::OnComplete(int32_t reason, int32_t total) | Callback object for completion of event query.
Input arguments:
- **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.
- **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.
Input arguments:
- **arg**: event query parameter.
- **rules**: rules for event filtering.
- **ruleSize**: number of event filtering rules.
- **callback**: callback object for event query.
Return value:
- **0**: Query is successful.
- 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.
Input arguments:
- **arg**: event query parameter.
- **rules**: event filtering rules.
- **ruleSize**: number of event filtering rules.
- **callback**: callback object for event query.
Return value:
- **0**: Query is successful.
- 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 8** Description of the HiSysEventQueryCallback structure + **Table 10** Description of the HiSysEventQueryCallback structure -| Attribute | Type | Description | +| Field | Type | Description | | ---------- | -------------------------------------------------- | ------------------------------------------------------------ | | OnQuery | void (*)(HiSysEventRecord records[], size_t size); | Callback object for event query.
Input arguments:
- **records**: event list.
- **size**: size of the event list.| | OnComplete | void (*)(int32_t reason, int32_t total); | Callback object for completion of event query.
Input arguments:
- **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.
- **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.
Input arguments:
- **record**: event structure.
- **params**: parameter name array.
- **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**.
Input arguments:
- **record**: event structure.
- **name**: parameter name.
- **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**.
Input arguments:
- **record**: event structure.
- **name**: parameter name.
- **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**.
Input arguments:
- **record**: event structure.
- **name**: parameter name.
- **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**.
Input arguments:
- **record**: event structure.
- **name**: parameter name.
- **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.
Input arguments:
- **record**: event structure.
- **name**: parameter name.
- **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.
Input arguments:
- **record**: event structure.
- **name**: parameter name.
- **value**: int64_t\* reference.
- **len**: array size.| @@ -143,240 +163,226 @@ The return values of the HiSysEventRecord APIs are described as follows: ### How to Develop -#### C++ HiSysEvent Query API - -1. Import the corresponding header file: - - ```c++ - #include "hisysevent_manager.h" - ``` - -2. Implement the callback API. - - ```c++ - class TestQueryCallback : public HiSysEventQueryCallback { - public: - void OnQuery(std::shared_ptr> sysEvents) override - { - if (sysEvents == nullptr) { - return; - } - for_each((*sysEvents).cbegin(), (*sysEvents).cend(), [](const HiSysEventRecord& event) { - std::cout << event.AsJson() << std::endl; - }); - } - - void OnComplete(int32_t reason, int32_t total) override - { - std::cout << "Query completed" << std::endl; - return; - } - }; - ``` - -3. Call the query API while passing in the query parameter, rule, and callback object. - - ```c++ - // Create a query parameter 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. - QueryRule rule("HIVIEWDFX", { "PLUGIN_LOAD" }); - std::vector queryRules = { rule }; - - // Create a query callback object. - auto queryCallback = std::make_shared(); - - // Call the query API. - HiSysEventManager::Query(arg, queryRules, queryCallback); - ``` - -#### C HiSysEvent Query API - -1. Import the corresponding header file: - - ```c++ - #include "hisysevent_manager_c.h" - ``` - -2. Implement the callback API. - - ```c++ - void OnQueryTest(HiSysEventRecord records[], size_t size) - { - for (size_t i = 0; i < size; i++) { - printf("OnQuery: event=%s", records[i].jsonStr); - } - } - - void OnCompleteTest(int32_t reason, int32_t total) - { - printf("OnCompleted, res=%d, total=%d\n", reason, total); - } - ``` - -3. Call the query API while passing in the query parameter, rule, and callback object. - - ```c++ - // Create a query parameter object. - HiSysEventQueryArg arg; - arg.beginTime = 0; - arg.endTime = 1668245644000; //2022-11-12 09:34:04 - arg.maxEvents = 10; - - // Create a query rule object. - constexpr char TEST_DOMAIN[] = "HIVIEWDFX"; - constexpr char TEST_NAME[] = "PLUGIN_LOAD"; - HiSysEventQueryRule rule; - (void)strcpy_s(rule.domain, strlen(TEST_DOMAIN) + 1, TEST_DOMAIN); - (void)strcpy_s(rule.eventList[0], strlen(TEST_NAME) + 1, TEST_NAME); - 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. - OH_HiSysEvent_Query(arg, rules, sizeof(rules) / sizeof(HiSysEventQueryRule), callback); - ``` - -### Development Example +#### C++ HiSysEvent Query + +1. Import the corresponding header file. + + ```c++ + #include "hisysevent_manager.h" + ``` + +2. Implement the callback API for the service domain. + + ```c++ + class TestQueryCallback : public HiSysEventQueryCallback { + public: + void OnQuery(std::shared_ptr> sysEvents) override + { + if (sysEvents == nullptr) { + return; + } + for_each((*sysEvents).cbegin(), (*sysEvents).cend(), [](const HiSysEventRecord& event) { + std::cout << event.AsJson() << std::endl; + }); + } + + void OnComplete(int32_t reason, int32_t total) override + { + std::cout << "Query completed" << std::endl; + return; + } + }; + ``` + +3. Call the query API while passing in **QueryArg**, **QueryRule**, and **QueryCallback**. + + ```c++ + // 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 QueryRule object. + QueryRule rule("HIVIEWDFX", { "PLUGIN_LOAD" }); + std::vector queryRules = { rule }; + + // Create a QueryCallback object. + auto queryCallback = std::make_shared(); + + // Call the query API. + HiSysEventManager::Query(arg, queryRules, queryCallback); + ``` + +#### C HiSysEvent Query + +1. Import the corresponding header file. + + ```c++ + #include "hisysevent_manager_c.h" + ``` + +2. Implement the callback API for the service domain. + + ```c++ + void OnQueryTest(HiSysEventRecord records[], size_t size) + { + for (size_t i = 0; i < size; i++) { + printf("OnQuery: event=%s", records[i].jsonStr); + } + } + + void OnCompleteTest(int32_t reason, int32_t total) + { + printf("OnCompleted, res=%d, total=%d\n", reason, total); + } + ``` + +3. Call the query API while passing in **HiSysEventQueryArg**, **HiSysEventQueryRule**, and **HiSysEventQueryCallback**. + + ```c++ + // Create a HiSysEventQueryArg object. + HiSysEventQueryArg arg; + arg.beginTime = 0; + arg.endTime = 1668245644000; //2022-11-12 09:34:04 + arg.maxEvents = 10; + + // Create a HiSysEventQueryRule object. + constexpr char TEST_DOMAIN[] = "HIVIEWDFX"; + constexpr char TEST_NAME[] = "PLUGIN_LOAD"; + HiSysEventQueryRule rule; + (void)strcpy_s(rule.domain, strlen(TEST_DOMAIN) + 1, TEST_DOMAIN); + (void)strcpy_s(rule.eventList[0], strlen(TEST_NAME) + 1, TEST_NAME); + rule.eventListSize = 1; + rule.condition = nullptr; + HiSysEventQueryRule rules[] = { rule }; + + // Create a HiSysEventQueryCallback object. + HiSysEventQueryCallback callback; + callback.OnQuery = OnQueryTest; + callback.OnComplete = OnCompleteTest; + + // Call the query API. + OH_HiSysEvent_Query(arg, rules, sizeof(rules) / sizeof(HiSysEventQueryRule), callback); + ``` + +### 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 = [ - "hisysevent:libhisysevent", - "hisysevent:libhisyseventmanager", - ] - ``` + ```c++ + external_deps = [ + "hisysevent:libhisysevent", + "hisysevent:libhisyseventmanager", + ] + ``` 2. Call the query API in the **TestQuery()** function of the service module. - - ```c++ - #include "hisysevent_manager.h" - #include - #include - - using namespace OHOS::HiviewDFX; - - class TestQueryCallback : public HiSysEventQueryCallback { - public: - void OnQuery(std::shared_ptr> sysEvents) override - { - if (sysEvents == nullptr) { - return; - } - for_each((*sysEvents).cbegin(), (*sysEvents).cend(), [](const HiSysEventRecord& event) { - std::cout << event.AsJson() << std::endl; - }); - } - - void OnComplete(int32_t reason, int32_t total) override - { - std::cout << "Query completed" << std::endl; - return; - } - }; - - int64_t GetMilliseconds() - { - auto now = std::chrono::system_clock::now(); - auto millisecs = std::chrono::duration_cast(now.time_since_epoch()); - return millisecs.count(); - } - - 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 queryRules = { rule }; - - // Create a query callback object. - auto queryCallback = std::make_shared(); - - // Call the query API. - int ret = HiSysEventManager::Query(arg, queryRules, queryCallback); - } - ``` + + ```c++ + #include "hisysevent_manager.h" + #include + #include + + using namespace OHOS::HiviewDFX; + + class TestQueryCallback : public HiSysEventQueryCallback { + public: + void OnQuery(std::shared_ptr> sysEvents) override + { + if (sysEvents == nullptr) { + return; + } + for_each((*sysEvents).cbegin(), (*sysEvents).cend(), [](const HiSysEventRecord& event) { + std::cout << event.AsJson() << std::endl; + }); + } + + void OnComplete(int32_t reason, int32_t total) override + { + std::cout << "Query completed" << std::endl; + return; + } + }; + + int64_t GetMilliseconds() + { + auto now = std::chrono::system_clock::now(); + auto millisecs = std::chrono::duration_cast(now.time_since_epoch()); + return millisecs.count(); + } + + void TestQuery() + { + long long startTime = 0; + long long endTime = GetMilliseconds(); + int maxEvents = 100; + QueryArg arg(startTime, endTime, maxEvents); + QueryRule rule("HIVIEWDFX", { "PLUGIN_LOAD" }); + std::vector queryRules = { rule }; + auto queryCallback = std::make_shared(); + 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++ - external_deps = [ "hisysevent:libhisyseventmanager" ] - - // for strcpy_s - deps = [ "//third_party/bounds_checking_function:libsec_shared" ] - ``` +```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. - ```c++ - #include "hisysevent_manager_c.h" - #include - #include + ```c++ + #include "hisysevent_manager_c.h" + #include + #include - void OnQueryTest(HiSysEventRecord records[], size_t size) - { - for (size_t i = 0; i < size; i++) { - printf("OnQuery: event=%s", records[i].jsonStr); - } - } - - void OnCompleteTest(int32_t reason, int32_t total) - { - printf("OnCompleted, res=%d, total=%d\n", reason, total); - } - - int64_t GetMilliseconds() - { - return time(NULL); - } - - 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; - (void)strcpy_s(rule.domain, strlen(TEST_DOMAIN) + 1, TEST_DOMAIN); - (void)strcpy_s(rule.eventList[0], strlen(TEST_NAME) + 1, TEST_NAME); - 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); - } - ``` + void OnQueryTest(HiSysEventRecord records[], size_t size) + { + for (size_t i = 0; i < size; i++) { + printf("OnQuery: event=%s", records[i].jsonStr); + } + } + + void OnCompleteTest(int32_t reason, int32_t total) + { + printf("OnCompleted, res=%d, total=%d\n", reason, total); + } + + int64_t GetMilliseconds() + { + return time(NULL); + } + + void TestQuery() + { + HiSysEventQueryArg arg; + arg.beginTime = 0; + arg.endTime = GetMilliseconds(); + arg.maxEvents = 100; + constexpr char TEST_DOMAIN[] = "HIVIEWDFX"; + constexpr char TEST_NAME[] = "PLUGIN_LOAD"; + HiSysEventQueryRule rule; + (void)strcpy_s(rule.domain, strlen(TEST_DOMAIN) + 1, TEST_DOMAIN); + (void)strcpy_s(rule.eventList[0], strlen(TEST_NAME) + 1, TEST_NAME); + rule.eventListSize = 1; + rule.condition = nullptr; + HiSysEventQueryRule rules[] = { rule }; + HiSysEventQueryCallback callback; + callback.OnQuery = OnQueryTest; + callback.OnComplete = OnCompleteTest; + int ret = OH_HiSysEvent_Query(arg, rules, sizeof(rules) / sizeof(HiSysEventQueryRule), callback); + } + ``` diff --git a/en/release-notes/OpenHarmony-v4.0-beta2.md b/en/release-notes/OpenHarmony-v4.0-beta2.md index 892d95e83883ddd30781465bd87481d9897f8bbc..56acfca9e0916441a7ca86aee7adcb19da88747c 100644 --- a/en/release-notes/OpenHarmony-v4.0-beta2.md +++ b/en/release-notes/OpenHarmony-v4.0-beta2.md @@ -40,7 +40,7 @@ The standard system capabilities of OpenHarmony 4.0 are continuously improved. A - RDB store NDK interfaces are provided. These interfaces are used for transaction addition, deletion, modification, and query, data encryption, hierarchical data protection, and backup and restore. -- The system can automatically selects a Bluetooth or Wi-Fi P2P channel for synchronization of key-value and distributed data objects based on the data volume. +- The system can automatically select a Bluetooth or Wi-Fi P2P channel for synchronization of key-value and distributed data objects based on the data volume. ### DSoftBus @@ -391,7 +391,7 @@ This version has the following updates to OpenHarmony 4.0 Beta1. ### API -For details about the API changes over OpenHarmony 4.0 Beta1, see [API Differences](/api-diff/v4.0-beta2/Readme-EN.md). A few API changes may affect applications developed using API version 9 or earlier. For details about the change impact and adaptation guide, see [Changelogs](changelogs/v4.0-beta2/Readme-EN.md). +For details about the API changes over OpenHarmony 4.0 Beta1, see [API Differences](https://gitee.com/openharmony/docs/blob/OpenHarmony-4.0-Beta2/en/release-notes/api-diff/v4.0-beta2/Readme-EN.md). A few API changes may affect applications developed using API version 9 or earlier. For details about the change impact and adaptation guide, see [Changelogs](https://gitee.com/openharmony/docs/blob/OpenHarmony-4.0-Beta2/en/release-notes/changelogs/v4.0-beta2/Readme-EN.md). ### Feature Updates diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.10.2/changelogs-netstack.md b/en/release-notes/changelogs/OpenHarmony_4.0.10.2/changelogs-netstack.md new file mode 100644 index 0000000000000000000000000000000000000000..4f431b96993df02786377279b2e3fc839f911f1b --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.10.2/changelogs-netstack.md @@ -0,0 +1,43 @@ +# 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): void; + - request2(url: string, options: HttpRequestOptions, callback: AsyncCallback): void; + - request2(url: string, options?: HttpRequestOptions): Promise; + - 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): void; + - requestInStream(url: string, options: HttpRequestOptions, callback: AsyncCallback): void; + - requestInStream(url: string, options?: HttpRequestOptions): Promise; + - 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. diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.10.3/changelogs-dfx.md b/en/release-notes/changelogs/OpenHarmony_4.0.10.3/changelogs-dfx.md new file mode 100644 index 0000000000000000000000000000000000000000..06f477d67eeb1c536d6e4a7d68219d82a2d2eddc --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.10.3/changelogs-dfx.md @@ -0,0 +1,22 @@ +# 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. diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.11.1/changelogs-file-management.md b/en/release-notes/changelogs/OpenHarmony_4.0.11.1/changelogs-file-management.md new file mode 100644 index 0000000000000000000000000000000000000000..382fef8b2a763a62643c594cfb4df16e6e25e5a8 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.11.1/changelogs-file-management.md @@ -0,0 +1,115 @@ +# File Subsystem Changelog + +## cl.file.1 Change of the userFileManager FileAsset Attribute + +Changed the [userFileManager.FileAsset](../../../application-dev/reference/apis/js-apis-userFileManager.md#fileasset) attribute. + +URI format before the change: + +'file://media/\/\/?networkid=xxx' + +URI format after the change: + +'file://media/Photo/\/IMG_datetime_0001/displayName.jpg' + +**Change Impact** + +For applications developed based on earlier versions, check whether the applications depend on or parse the media library URIs. If yes, make adaptation as required. The value of **file_id** is not unique. Do not parse the file ID. Use the URI instead. + +**Key API/Component Changes** + +| Module | Method/Attribute/Enum/Constant | Change Type| +| ------------------------- | ------------------------------------------------------------ | -------- | +| userFileManager | **interface** FileAsset | Attribute changed | + +**Adaptation Guide** + +In API version 10, the URI format of user files is changed so that basic file information (such as the file name) can be obtained based on the URI. If the new format is used, the URI parsing may yield unexpected result. For example, before the change, the ID obtained from the URI **'file://media/image/8'** is 8. If the new URI format is used, the file **displayName** is obtained. You are advised to use the URI to obtain file information. + +**Example**: + +```js +import userFileManager from '@ohos.filemanagement.userFileManager'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + let context = getContext(this); + let mgr = userFileManager.getUserFileMgr(context); + let predicates = new dataSharePredicates.DataSharePredicates(); + let uri = 'file://media/Photo/1/IMG_datetime_0001/displayName.jpg' // The URI must exist. + predicates.equalTo('uri', uri); + let fetchOptions = { + fetchColumns: ['uri'], + predicates: predicates + }; + + mgr.getPhotoAssets(fetchOptions, async (err, fetchResult) => { + if (fetchResult != undefined) { + console.info('fetchResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info('fileAsset.displayName : ' + fileAsset.displayName); + } + } else { + console.error('fetchResult fail' + err); + } + }); +} +``` + +## cl.file.2 Change of the photoAccessHelper PhotoAsset Attribute + +Changed the [photoAccessHelper.PhotoAsset](../../../application-dev/reference/apis/js-apis-photoAccessHelper.md#photoasset) attribute. + +URI format before the change: + +'file://media/\/\/?networkid=xxx' + +URI format after the change: + +'file://media/Photo/\/IMG_datetime_0001/displayName.jpg' + +**Change Impact** + +For applications developed based on earlier versions, check whether the applications depend on or parse the media library URIs. If yes, make adaptation as required. The value of **file_id** is not unique. Do not parse the file ID. Use the URI instead. + +**Key API/Component Changes** + +| Module | Method/Attribute/Enum/Constant | Change Type| +| ------------------------- | ------------------------------------------------------------ | -------- | +| photoAccessHelper | **interface** PhotoAsset | Attribute changed | + +**Adaptation Guide** + +In API version 10, the URI format of user files is changed so that basic file information (such as the file name) can be obtained based on the URI. If the new format is used, the URI parsing may yield unexpected result. For example, before the change, the ID obtained from the URI **'file://media/image/8'** is 8. If the new URI format is used, the file **displayName** is obtained. You are advised to use the URI to obtain file information. + +**Example**: + +```js +import photoAccessHelper from '@ohos.file.photoAccessHelper'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + let context = getContext(this); + let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); + let predicates = new dataSharePredicates.DataSharePredicates(); + let uri = 'file://media/Photo/1/IMG_datetime_0001/displayName.jpg' // The URI must exist. + predicates.equalTo('uri', uri); + let fetchOptions = { + fetchColumns: ['uri'], + predicates: predicates + }; + + phAccessHelper.getAssets(fetchOptions, async (err, fetchResult) => { + if (fetchResult != undefined) { + console.info('fetchResult success'); + let photoAsset = await fetchResult.getFirstObject(); + if (photoAsset != undefined) { + console.info('photoAsset.displayName : ' + photoAsset.displayName); + } + } else { + console.error('fetchResult fail' + err); + } + }); +} +``` diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.7.2/changelogs-telephoy.md b/en/release-notes/changelogs/OpenHarmony_4.0.7.2/changelogs-telephoy.md new file mode 100644 index 0000000000000000000000000000000000000000..91b9d4fa88ee004cf2e7f55d92e5265d599652df --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.7.2/changelogs-telephoy.md @@ -0,0 +1,122 @@ +# 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; + +/** + * @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; + +/** + * 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): void; +function setVoNRState(slotId: number, state: VoNRState): Promise; + +``` + +After change: + +```js +function setVoNRState(slotId: number, state: VoNRState, callback: AsyncCallback): void; +function setVoNRState(slotId: number, state: VoNRState): Promise; +``` + +**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)}`); +}); +``` diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.8.1/changelogs-arkcompiler.md b/en/release-notes/changelogs/OpenHarmony_4.0.8.1/changelogs-arkcompiler.md index a0d37340a474ee713030ae1177a4b9af4bc47a63..fa2c1a8f208e4a107201ccb4e6eb69a79d10f154 100644 --- a/en/release-notes/changelogs/OpenHarmony_4.0.8.1/changelogs-arkcompiler.md +++ b/en/release-notes/changelogs/OpenHarmony_4.0.8.1/changelogs-arkcompiler.md @@ -1,23 +1,30 @@ # ArkCompiler Subsystem Changelog -## cl.ArkCompiler.1 type compileMode uses es2abc by default +## cl.ArkCompiler.1 Change of Default Compiler to es2abc in Type Compilation -The composition of ArkCompiler in sdk has ts2abc compiler and es2abc compiler, supporting compilation of ets/ts/js files.
-Compilation Mode Introduction:
-​ Non-type compilation: convert ets/ts sourceCode into js sourceCode, and use ArkCompiler compiler es2abc to generate bytecode.
-​ type compilation: convert ets/ts sourceCode into ts sourceCode, and use ArkCompiler compiler ts2abc (previous version)/es2abc (enabled in this version) to generate bytecode.
-Application Project hvigor version:
-​ hvigorVersion field and @ohos/hvigor-ohos-plugin field in dependencies of hvigor-config.json5 file in the hvigor directory of the application project.
-Enable type compilation:
-​ When the hvigor version is greater than or equal to 2.6.0-rc.9.s, the type compilation mode is used by default, or in the build-profile.json5 file of the same level directory as the application sourceCode (src directory), configure the "aotCompileMode": "type" option under the buildOption tag
+In the SDK, ArkCompiler has two compilers that support ets/ts/js compilation: ts2abc compiler and es2abc compiler. -When type compilation is enabled and this version of the SDK is used, the ArkCompiler compiler es2abc will be used by default to compile the ts sourceCode to generate bytecode, and it is not recommended to use the old version SDK with ts2abc enabled for type compilation.
+Introduction to compilation modes: -**Change Impact**
-With DevEco Studio development, after the type compilation mode is enabled and the new version of the SDK is used, due to the change of the compilation mode and the change of the ArkCompiler compiler, application compilation failures and runtime crashes may occur.
+- Non-type compilation: converts ArkTS/TS source code into JS source code, and uses the ArkCompiler compiler es2abc to generate bytecode. -**Key API/Component Changes**
-type compileMode uses arkcompiler frontend compiler es2abc by default
+- Type compilation: converts ArkTS/TS source code into TS source code, and uses the ArkCompiler compiler ts2abc (in earlier versions)/es2abc (enabled in this version) to generate bytecode. + +You can check the hvigor version of the application project in the following fields: +​**hvigorVersion** field and **@ohos/hvigor-ohos-plugin** field under **dependencies** in the **hvigor-config.json5** file in the **hvigor** directory of the application project + +Enable type compilation: + +If the hvigor version is 2.6.0-rc.9.s or later, the type compilation mode is enabled by default. You can also manually enable this mode by setting **aotCompileMode** to **type** under the **buildOption** tag in the **build-profile.json5** file at the same level directory as the application source code (**src** directory). + +When type compilation is enabled and the SDK of this version is used, the ArkCompiler compiler es2abc is used by default. The earlier version SDK with ts2abc enabled is not recommended for type compilation. + +**Change Impact** +In DevEco Studio, when the type compilation mode is enabled and the SDK of this version is used, the change in the compilation mode and ArkCompiler compiler may result in application compilation failures and runtime crashes. + +**Key API/Component Changes** +In type compilation mode, the ArkCompiler compiler es2abc is used by default. **Adaptation Guide** -1. When the hvigor version is greater than or equal to 2.6.0-rc.9.s, the developer needs to configure "aotCompileMode": "" in the build-profile.json5 file to switch to the original compilation mode (not type). + +If the hvigor version is 2.6.0-rc.9.s or later, to switch to the original compilation mode (non-type), you need to set **aotCompileMode** in the **build-profile.json5** file. \ No newline at end of file diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.9.5/changelogs-formfwk.md b/en/release-notes/changelogs/OpenHarmony_4.0.9.5/changelogs-formfwk.md new file mode 100644 index 0000000000000000000000000000000000000000..e5ed4eecd2e0d4e6c1f176d6bfa808c136a3889b --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.9.5/changelogs-formfwk.md @@ -0,0 +1,146 @@ +# formfwk Subsystem Changelog + +## cl.formfwk.1 Some APIs Moved from @ohos.app.form.formHost.d.ts and Their Permission Changed + +1. APIs used for listening for and obtaining dynamic widget information are moved from **@ohos.app.form.formHost.d.ts** to **@ohos.app.form.formObserver.d.ts**. + +2. The permission for these APIs is changed from **ohos.permission.REQUIRE_FORM** to **ohos.permission.OBSERVE_FORM_RUNNING**. + +**Change Impact** + +Applications that use the involved APIs may have compatibility issues. + +**Key API/Component Changes** + +| API | Home .d.ts File Before Modification| Home .d.ts File After Modification| Permission Required Before Modification| Permission Required After Modification| +| -------- | -------- | -------- | -------- | -------- | +| on('formAdd') | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM|ohos.permission.OBSERVE_FORM_RUNNING| +| off('formAdd')| @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM|ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | +| on('formRemove') | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | +| off('formRemove') | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | +| on('notifyVisible') | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | +| off('notifyVisible') | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | +| on('notifyInvisible') | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | +| off('notifyInvisible') | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | +| getRunningFormInfos | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | +| getRunningFormInfosByFilter | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | +| getRunningFormInfoById | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | + +**Adaptation Guide** + +Adapt your application code accordingly. To use these APIs in OpenHarmony 4.0.9.5 and later versions, import **@ohos.app.form.formObserver.d.ts** and request the **ohos.permission.OBSERVE_FORM_RUNNING** permission. + +**Example** + +```js +import formObserver from @ohos.app.form.formObserver.d.ts; + +try { + formObserver.getRunningFormInfos((error, data) => { + if (error) { + console.error(`error, code: ${error.code}, message: ${error.message}`); + } else { + console.log('formHost getRunningFormInfos, data: ${JSON.stringify(data)}'); + } + }, 'com.example.ohos.formjsdemo'); +} catch(error) { + console.error(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + + +## cl.formfwk.2 Adjusted the Parameter Sequence of Event Subscription and Unsubscription APIs (on/off) + +The **callback** parameter is moved as the last parameter in the event subscription and unsubscription APIs (**on**/**off**). + +**Change Impact** + +Applications that use the involved APIs may have compatibility issues. + +**Key API/Component Changes** + +Before change: + +```js +function on(type: 'formAdd', observerCallback: Callback, bundleName?: string): void; +function off(type: 'formAdd', observerCallback?: Callback, bundleName?: string): void; + +function on(type: 'formRemove', observerCallback: Callback, bundleName?: string): void; +function off(type: 'formRemove', observerCallback?: Callback, bundleName?: string): void; + +function on( + type: 'notifyVisible', + observerCallback: Callback>, + hostBundleName?: string + ): void; +function off( + type: 'notifyVisible', + observerCallback?: Callback>, + hostBundleName?: string + ): void; + +function on( + type: 'notifyInvisible', + observerCallback: Callback>, + hostBundleName?: string + ): void; +function off( + type: 'notifyInvisible', + observerCallback?: Callback>, + hostBundleName?: string + ): void; +``` + +After change: + +```js +function on(type: 'formAdd', observerCallback: Callback): void; +function on(type: 'formAdd', hostBundleName: string, observerCallback: Callback): void; +function off(type: 'formAdd', hostBundleName?: string, observerCallback?: Callback): void; + +function on(type: 'formRemove', observerCallback: Callback): void; +function on(type: 'formRemove', hostBundleName: string, observerCallback: Callback): void; +function off(type: 'formRemove', hostBundleName?: string, observerCallback?: Callback): void; + +function on(type: 'notifyVisible', observerCallback: Callback>): void; +function on( + type: 'notifyVisible', + hostBundleName: string, + observerCallback: Callback> + ): void; +function off( + type: 'notifyVisible', + hostBundleName?: string, + observerCallback?: Callback> + ): void; + +function on(type: 'notifyInvisible', observerCallback: Callback>): void; +function on( + type: 'notifyInvisible', + hostBundleName: string, + observerCallback: Callback>, + ): void; +function off( + type: 'notifyInvisible', + hostBundleName?: string, + observerCallback?: Callback> + ): void; +``` + +**Adaptation Guide** + +Adapt your application code accordingly. In OpenHarmony 4.0.9.5 and later versions, pass in **callback** as the last parameter when calling these APIs. + +**Example** + +```js +import formObserver from @ohos.app.form.formObserver.d.ts; + +let bundleName = 'ohos.samples.FormApplication'; +let callback = function(data) { + console.log('a new form added, data: ${JSON.stringify(data)'); +} + +formHost.on('formAdd', callback); +formHost.on('formAdd', bundleName, callback); +``` diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-page-animation.md b/zh-cn/application-dev/application-models/arkts-ui-widget-page-animation.md index 1cecd3aae69381ce4de7ed37411a177b83db899d..c8321d7165e9324aca8eb87b69085070f82fec53 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-page-animation.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-page-animation.md @@ -21,22 +21,24 @@ ArkTS卡片开放了使用动画效果的能力,支持[显式动画](../refere ```ts @Entry @Component -struct AttrAnimationExample { +struct AnimationCard { @State rotateAngle: number = 0; build() { - Column() { + Row() { Button('change rotate angle') + .height('20%') + .width('90%') + .margin('5%') .onClick(() => { - this.rotateAngle = 90; + this.rotateAngle = (this.rotateAngle === 0 ? 90 : 0); }) - .margin(50) .rotate({ angle: this.rotateAngle }) .animation({ curve: Curve.EaseOut, - playMode: PlayMode.AlternateReverse + playMode: PlayMode.Normal, }) - }.width('100%').margin({ top: 20 }) + }.height('100%').alignItems(VerticalAlign.Center) } } ``` diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-page-custom-drawing.md b/zh-cn/application-dev/application-models/arkts-ui-widget-page-custom-drawing.md index b759f612959fe896f2dc1f8e25b74d13203ec24c..e69150e7ea9ad9d61a1a382ed1386d9e70ce2e5f 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-page-custom-drawing.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-page-custom-drawing.md @@ -6,7 +6,7 @@ ArkTS卡片开放了自定义绘制的能力,在卡片上可以通过[Canvas]( ```ts @Entry @Component -struct WidgetCard { +struct CanvasCard { private canvasWidth: number = 0; private canvasHeight: number = 0; // 初始化CanvasRenderingContext2D和RenderingContextSettings diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration1.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration1.png new file mode 100644 index 0000000000000000000000000000000000000000..952218badc407b8bc2470fc1622ae0e607c4bcfb Binary files /dev/null and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration1.png differ diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration2.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration2.png new file mode 100644 index 0000000000000000000000000000000000000000..a81cb2ab08506f4e368c6002be18d6931a056218 Binary files /dev/null and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration2.png differ diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration3.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration3.png new file mode 100644 index 0000000000000000000000000000000000000000..86158bc2bcd54b83e8dc73aec204788aab0b95a3 Binary files /dev/null and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration3.png differ diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration4.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration4.png new file mode 100644 index 0000000000000000000000000000000000000000..c743b3d10f8f1fa0a8be76cf10fff219c52d0ebf Binary files /dev/null and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration4.png differ diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration5.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration5.png new file mode 100644 index 0000000000000000000000000000000000000000..854af7b632121a52c9e0364efb407b209dfb63bf Binary files /dev/null and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration5.png differ diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration6.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration6.png new file mode 100644 index 0000000000000000000000000000000000000000..2d38c00bbb5d268b8072dac4b8bf22238bbe869b Binary files /dev/null and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration6.png differ diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration7.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration7.png new file mode 100644 index 0000000000000000000000000000000000000000..e789d748fe97d3c08bfaa6d22cf151bee31eccc9 Binary files /dev/null and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration7.png differ diff --git a/zh-cn/application-dev/application-models/hop-cross-device-migration.md b/zh-cn/application-dev/application-models/hop-cross-device-migration.md index fcc35ec4d4f36088ae25911afac9a23f89760862..84a034344f058c2ca415a028b817b1bd830525dc 100644 --- a/zh-cn/application-dev/application-models/hop-cross-device-migration.md +++ b/zh-cn/application-dev/application-models/hop-cross-device-migration.md @@ -1,21 +1,15 @@ # 跨端迁移 - ## 功能描述 跨端迁移的主要工作是实现将应用当前任务(包括页面控件状态变量等)迁移到目标设备,能在目标设备上接续。主要功能包括: - 支持用户自定义数据存储及恢复。 - - 支持页面路由信息和页面控件状态数据的存储及恢复。 - - 支持应用兼容性检测。 - -- 支持应用根据实际使用场景动态设置迁移状态(默认迁移状态为ACTIVE激活状态)。如编辑类应用在编辑文本的页面下才需要迁移,其他页面不需要迁移,则可以通过[setMissionContinueState](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10)进行控制。 - +- 支持应用根据实际使用场景动态设置迁移状态(默认迁移状态为 **ACTIVE** 激活状态)。如编辑类应用在编辑文本的页面下才需要迁移,其他页面不需要迁移,则可以通过[setMissionContinueState](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10)进行控制。 - 支持应用动态选择是否进行页面栈恢复(默认进行页面栈信息恢复)。如应用希望自定义迁移到其他设备后显示的页面,则可以通过[SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)进行控制。 - -- 支持应用动态选择流转成功后是否退出迁移发起端应用(默认流转成功后退出迁移发起端应用)。则可以通过[SUPPORT_CONTINUE_SOURCE_EXIT_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)进行控制。 +- 支持应用动态选择迁移成功后是否退出迁移发起端应用(默认迁移成功后退出迁移发起端应用)。则可以通过[SUPPORT_CONTINUE_SOURCE_EXIT_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)进行控制。 ## 跨端迁移流程 @@ -28,14 +22,9 @@ ## 约束限制 -- 由于“跨端迁移任务管理”能力尚未具备,开发者当前只能开发具备跨端迁移能力的应用,但不能发起迁移。 - +- 应用迁移的发起依赖系统应用控制,系统应用开发者可以参考[验证指导中的demo示例](#验证指导)实现相关的控制能力。 - 跨端迁移要求在同UIAbility之间进行,也就是需要相同的bundleName、abilityName和签名。 - - -## 最佳实践 - -为了获得最佳体验,使用wantParam传输的数据建议在100KB以下。 +- 为了获得最佳体验,使用wantParam传输的数据建议在100KB以下。 ## 接口说明 @@ -46,22 +35,26 @@ | **接口名** | **描述** | | -------- | -------- | -| onContinue(wantParam : {[key: string]: Object}): OnContinueResult | 迁移发起端在该回调中保存迁移所需要的数据,同时返回是否同意迁移:
- AGREE:表示同意。
- REJECT:表示拒绝:如应用在onContinue中异常可以直接REJECT。
- MISMATCH:表示版本不匹配:迁移发起端应用可以在onContinue中获取到迁移接收端应用的版本号,进行协商后,如果版本不匹配导致无法迁移,可以返回该错误。 | -| onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void; | 应用迁移接收端为冷启动或多实例应用热启动时,在该回调中完成数据恢复,并触发页面恢复。详见[应用组件启动模式](uiability-launch-type.md) | -| onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void; | 迁移接收端为单实例应用热启动时,在该回调中完成数据恢复,并触发页面恢复。详见[应用组件启动模式](uiability-launch-type.md) | +| onContinue(wantParam : {[key: string]: Object}): OnContinueResult | 迁移发起端在该回调中保存迁移所需要的数据,同时返回是否同意迁移:
- AGREE:表示同意。
- REJECT:表示拒绝:如应用在onContinue中异常会导致钱以后数据恢复时显示异常,则可以建议REJECT。
- MISMATCH:表示版本不匹配:迁移发起端应用可以在onContinue中获取到迁移目标端应用的版本号,进行协商后,如果版本不匹配导致无法迁移,可以返回该错误。 | +| onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void; | 应用迁移目标端为冷启动或多实例应用热启动时,在该回调中完成数据恢复,并触发页面恢复。详见[应用组件启动模式](uiability-launch-type.md) | +| onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void; | 迁移目标端为单实例应用热启动时,在该回调中完成数据恢复,并触发页面恢复。详见[应用组件启动模式](uiability-launch-type.md) | ## 开发步骤 -1. 需要申请`ohos.permission.DISTRIBUTED_DATASYNC`权限,配置方式请参见[配置文件权限声明](../security/accesstoken-guidelines.md#配置文件权限声明)。 +1.需要申请`ohos.permission.DISTRIBUTED_DATASYNC`权限 -2. 同时需要在应用首次启动时弹窗向用户申请授权,使用方式请参见[向用户申请授权](../security/accesstoken-guidelines.md#向用户申请授权)。 +配置方式请参见[配置文件权限声明](../security/accesstoken-guidelines.md#配置文件权限声明)。 -3. 在配置文件中配置跨端迁移相关标签字段。 +2.同时需要在应用首次启动时弹窗向用户申请授权 - 配置应用支持迁移 - 在module.json5中配置continuable标签:true表示支持迁移,false表示不支持,默认为false。配置为false的UIAbility将被系统识别为无法迁移。 +使用方式请参见[向用户申请授权](../security/accesstoken-guidelines.md#向用户申请授权)。 + +3.在配置文件中配置跨端迁移相关标签字段。 + +配置应用支持迁移 +在module.json5中配置continuable标签:true表示支持迁移,false表示不支持,默认为false。配置为false的UIAbility将被系统识别为无法迁移。 ```json @@ -80,131 +73,274 @@ 根据需要配置应用启动模式类型,配置详情请参照[UIAbility组件启动模式](uiability-launch-type.md)。 -4. 在发起端UIAbility中实现[onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue)接口。 - 当应用触发迁移时,[onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue)接口在发起端被调用,开发者可以在该接口中保存迁移数据,实现应用兼容性检测,决定是否支持此次迁移。 - - 保存迁移数据:开发者可以将要迁移的数据通过键值对的方式保存在wantParam中。 +4.在发起端UIAbility中实现[onContinue](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue)接口。 + +当应用触发迁移时,[onContinue](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue)接口在发起端被调用,开发者可以在该接口中保存迁移数据,实现应用兼容性检测,决定是否支持此次迁移。 + +- 保存迁移数据:开发者可以将要迁移的数据通过键值对的方式保存在wantParam中。 + +- 应用兼容性检测:开发者可以通过从wantParam中获取目标应用的版本号与本应用版本号做兼容性校验。开发者可以在触发迁移时从`onContinue`接口中`wantParam.version`获取到迁移目标端应用的版本号与迁移发起端应用版本号做兼容校验。 + +- 迁移决策:开发者可以通过onContinue接口的返回值决定是否支持此次迁移,返回值信息见[接口说明](#接口说明)。 + + 示例如下: + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + +onContinue(wantParam : {[key: string]: Object}) { + console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) //准备迁移数据 + let continueInput = '迁移的数据'; + // 将要迁移的数据保存在wantParam的自定义字段(如:data)中; + wantParam["data"] = continueInput + console.info(`onContinue input = ${wantParam["input"]}`); + return AbilityConstant.OnContinueResult.AGREE +} +``` + +5.在Stage模型中,应用在不同启动模式下将调用不同的接口,以恢复数据、加载界面。 + +不同情况下的函数调用如下图所示: + +![hop-cross-device-migration](figures/hop-cross-device-migration1.png) + +在目标端设备UIAbility中实现onCreate与onNewWant接口,恢复迁移数据。 + +- onCreate实现示例 + - 目标端设备上,在onCreate中根据launchReason判断该次启动是否为迁移LaunchReason.CONTINUATION。 + - 开发者可以从want中获取保存的迁移数据。 + - 完成数据恢复后,开发者需要调用restoreWindowStage来触发页面恢复:包括页面栈信息。 + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + + export default class EntryAbility extends UIAbility { + storage : LocalStorage; + onCreate(want, launchParam) { + console.info(`EntryAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) + if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { + // 将上述的保存的数据取出恢复 + let continueInput = want.parameters.data + console.info(`continue input ${continueInput}`) + // 将数据显示当前页面 + this.storage = new LocalStorage(); + this.context.restoreWindowStage(this.storage); + } + } + } + ``` +- 如果是单实例应用,需要额外实现onNewWant接口,实现方式与onCreate的实现相同。 + - 在onNewWant中判断迁移场景,恢复数据,并触发页面恢复 + + ```ts + export default class EntryAbility extends UIAbility { + storage : LocalStorage; + onNewWant(want, launchParam) { + console.info(`EntryAbility onNewWant ${AbilityConstant.LaunchReason.CONTINUATION}`) + if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { + // get user data from want params + let continueInput = want.parameters.data + console.info(`continue input ${continueInput}`) + this.storage = new LocalStorage(); + this.context.restoreWindowStage(this.storage); + } + } + } + ``` + + + +## 迁移功能可选配置 + +### 1.动态配置迁移能力 + +从API 10 起,提供了支持动态配置迁移能力的功能。即应用可以根据实际使用场景,在需要迁移功能时,设置开启应用迁移能力;在业务不需要迁移时,则可以关闭迁移能力。开发者可以通过调用[setMissionContinueState](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10)接口对迁移能力进行设置。默认状态下,可迁移应用的迁移能力为**ACTIVE**状态,即迁移能力开启,可以迁移。 + +| 接口状态值 | 含义 | +| :------------------------------------- | ---------------------- | +| AbilityConstant.ContinueState.ACTIVE | 应用当前可迁移能力开启 | +| AbilityConstant.ContinueState.INACTIVE | 应用当前可迁移能力关闭 | + +**设置迁移能力的时机** + +迁移能力的改变可以根据实际业务需求和代码实现,发生在应用生命周期的绝大多数时机。本文介绍常用的几种配置方式。 + +在ability的onCreate函数中调用接口,可以在应用创建时设置应用的迁移状态。 + +```ts +// EntryAbility.ets +onCreate(want, launchParam) { + ... + this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { + console.info('setMissionContinueState ACTIVE result: ', JSON.stringify(result)); + }; + ... +} +``` + +在页面的onPageShow函数中调用接口,可以设置单个页面出现时应用的迁移状态。 + +```ts +// PageName.ets +struct PageName { + Build() { + ... + } + ... + onPageShow(){ + // 进入该页面时,将应用设置为可迁移状态 + this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { + console.info('setMissionContinueState ACTIVE result: ', JSON.stringify(result)); + }; + } +} +``` + +在某个组件的触发事件中设置应用迁移能力。如下例中,使用 **Button** 组件的 **onClick** 事件,触发迁移能力的改变。 + +```ts +// xxx.ets +Button(){ + ... +} +.onClick(()=>{ + //点击该按钮时,将应用设置为可迁移状态 + this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { + console.info('setMissionContinueState ACTIVE result: ', JSON.stringify(result)); + }; +}) +``` + +**保证迁移连续性** + +由于迁移加载时,目标端拉起的应用可能执行过自己的迁移状态设置命令(如:冷启动时目标端在onCreate中设置了 **INACTIVE** ;热启动时对端已打开了不可迁移的页面,迁移状态为 **INACTIVE** 等情况)。为了保证迁移过后的应用依然具有可以迁移回发起端的能力,应在 onCreate和onNewWant的迁移调用判断中,将迁移状态设置为 **ACTIVE** 。 + +```ts +// EntryAbility.ets +onCreate(want, launchparam) { + ... + // 调用原因为迁移时,设置状态为可迁移,应对冷启动情况 + if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { + this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { + console.info('setMissionContinueState ACTIVE result: ', JSON.stringify(result)); + }; + } +} - - 应用兼容性检测:开发者可以通过从wantParam中获取目标应用的版本号与本应用版本号做兼容性校验。开发者可以在触发迁移时从`onContinue`接口中`wantParam.version`获取到迁移接收端应用的版本号与迁移发起端应用版本号做兼容校验。 +onNewWant(want, launchparam) { + ... + // 调用原因为迁移时,设置状态为可迁移,应对热启动情况 + if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { + this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { + console.info('setMissionContinueState ACTIVE result: ', JSON.stringify(result)); + }; + } +} +``` - - 迁移决策:开发者可以通过onContinue接口的返回值决定是否支持此次迁移,返回值信息见[接口说明](#接口说明)。 - 示例如下: - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import AbilityConstant from '@ohos.app.ability.AbilityConstant'; +### 2.按需迁移页面栈 - onContinue(wantParam : {[key: string]: any}) { - console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) - let workInput = AppStorage.Get('ContinueWork'); - // set user input data into want params - wantParam["work"] = workInput // set user input data into want params - console.info(`onContinue input = ${wantParam["input"]}`); - return AbilityConstant.OnContinueResult.AGREE - } - ``` +支持应用动态选择是否进行页面栈恢复(默认进行页面栈信息恢复)。如果应用不想使用系统默认恢复的页面栈,则可以设置不进行页面栈迁移,而需要在`onWindowStageRestore`设置迁移后进入的页面,参数定义见[SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)。 -5. 在目标端设备UIAbility中实现onCreate()与onNewWant()接口,恢复迁移数据。 - - onCreate实现示例 - - 目标端设备上,在onCreate中根据launchReason判断该次启动是否为迁移LaunchReason.CONTINUATION。 - - 开发者可以从want中获取保存的迁移数据。 - - 完成数据恢复后,开发者需要调用restoreWindowStage来触发页面恢复:包括页面栈信息。 - - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import AbilityConstant from '@ohos.app.ability.AbilityConstant'; - import distributedObject from '@ohos.data.distributedDataObject'; - - export default class EntryAbility extends UIAbility { - storage : LocalStorage; - onCreate(want, launchParam) { - console.info(`EntryAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) - if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { - // get user data from want params - let workInput = want.parameters.work - console.info(`work input ${workInput}`) - AppStorage.SetOrCreate('ContinueWork', workInput) - this.storage = new LocalStorage(); - this.context.restoreWindowStage(this.storage); - } - } - } - ``` - - 如果是单实例应用,需要额外实现onNewWant()接口,实现方式与onCreate()的实现相同。 - - 在onNewWant()中判断迁移场景,恢复数据,并触发页面恢复 - - ```ts - export default class EntryAbility extends UIAbility { - storage : LocalStorage; - onNewWant(want, launchParam) { - console.info(`EntryAbility onNewWant ${AbilityConstant.LaunchReason.CONTINUATION}`) - if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { - // get user data from want params - let workInput = want.parameters.work - console.info(`work input ${workInput}`) - AppStorage.SetOrCreate('ContinueWork', workInput) - this.storage = new LocalStorage(); - this.context.restoreWindowStage(this.storage); - } - } - } +应用在发起端的页面栈中存在Index和Second路由,而在目标端恢复时不需要按照发起端页面栈进行恢复,需要恢复到指定页面。 + +- 示例:应用迁移不需要自动迁移页面栈信息 + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import wantConstant from '@ohos.app.ability.wantConstant'; + + onContinue(wantParam : {[key: string]: Object}) { + console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) + wantParam[wantConstant.Params.SUPPORT_CONTINUE_PAGE_STACK_KEY] = false; + return AbilityConstant.OnContinueResult.AGREE; + } + + onWindowStageRestore(windowStage) { + // 若不需要自动迁移页面栈信息,则需要在此处设置应用迁移后进入的页面 + windowStage.setUIContent(this.contex, "pages/index", null); + } + ``` + +### 3.按需退出 + +支持应用动态选择迁移成功后是否退出迁移发起端应用(默认迁移成功后退出迁移发起端应用)。如果应用不想让系统自动退出迁移发起端应用,则可以设置不退出,参数定义见[SUPPORT_CONTINUE_SOURCE_EXIT_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)。 + +- 示例:应用迁移设置不需要迁移成功后退出迁移发起端应用 + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import wantConstant from '@ohos.app.ability.wantConstant'; + + onContinue(wantParam : {[key: string]: Object}) { + console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) + wantParam[wantConstant.Params.SUPPORT_CONTINUE_SOURCE_EXIT_KEY] = false; + return AbilityConstant.OnContinueResult.AGREE; + } + ``` + +## 验证指导 + +为方便开发者验证已开发的可迁移应用,当前OpenHarmony提供了一个全局任务中心demo作为迁移的入口。下面介绍通过安装全局任务中心来验证迁移的方式。 + +### 1. 编译安装全局任务中心 + +#### **配置环境** + +public-SDK不支持开发者使用所有的系统API,例如:全局任务中心使用的[**@ohos.distributedDeviceManager**](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-distributedDeviceManager.md)不包括在public_SDK中。因此为了正确编译安装全局任务中心,开发者需要替换full-SDK,具体操作可参见[替换指南](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/faqs/full-sdk-switch-guide.md)。 + +**说明**:本文中的截图仅为参考,具体的显示界面请以实际使用的DevEco Studio和SDK的版本为准。 + +#### **下载MissionCenter_Demo[示例代码](https://gitee.com/openharmony/ability_dmsfwk/tree/master/services/dtbschedmgr/test/missionCenterDemo/dmsDemo/entry/src/main)** + +#### **编译工程文件** + +**新建OpenHarmony 空的工程,找到对应的文件夹替换下载文件** + +![hop-cross-device-migration](figures/hop-cross-device-migration2.png) + +**自动签名,编译安装。** + +​ DevEco的自动签名模板默认签名权限为normal级。而本应用设计到ohos.permission.MANAGE_MISSIONS权限为system_core级别。自动生成的签名无法获得足够的权限,所以需要将权限升级为system_core级别,然后签名。 + +**系统权限设置**(以api10目录为例): 将Sdk目录下的openharmony\api版本(如:10)\toolchains\lib\UnsgnedReleasedProfileTemplate.json文件中的"apl":"normal_core"改为"apl":"system_core"。 + +①点击file->Project Structrue + +![hop-cross-device-migration](figures/hop-cross-device-migration3.png) + +②点击Signing Configs 点击OK -6. **可选配置:** 在应用支持迁移特性时,默认开启应用迁移状态开关,根据应用当前任务获取焦点/失去焦点通知周边的可信设备当前任务可流转/取消流转。若应用需要在特定场景下才通知周边设备可流转,则需要在应用打开时设置迁移状态为INACTIVE,在后续的业务流程中需要迁移时再设置迁移状态为ACTIVE。接口见[setMissionContinueState](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10)。 +![hop-cross-device-migration](figures/hop-cross-device-migration4.png) - - 示例:应用启动不需要流转 +③连接开发板运行生成demo。 - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import AbilityConstant from '@ohos.app.ability.AbilityConstant'; +### 2.设备组网 - onCreate(want, launchParam) { - this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result) => { - console.info(`setMissionContinueState: ${JSON.stringify(result)}`); - }); - } - ``` - - 示例:应用在后续的业务流程中需要流转了 +①打开A,B两设备的计算器 - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import AbilityConstant from '@ohos.app.ability.AbilityConstant'; +②点击右上角箭头选择B设备 - this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { - console.info(`setMissionContinueState: ${JSON.stringify(result)}`); - }); - ``` +③在B设备选择信任设备,弹出PIN码 -7. **可选配置:** 支持应用动态选择是否进行页面栈恢复(默认进行页面栈信息恢复)。如果应用不想使用系统默认恢复的页面栈,则可以设置不进行页面栈迁移,而需要在`onWindowStageRestore`设置流转后进入的页面,参数定义见[SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)。 +④在A设备输入PIN码 - - 示例:应用迁移不需要自动流转页面栈信息 +⑤已组网成功,验证方法:在A设备输入数字,B设备同步出现则证明组网成功 - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import wantConstant from '@ohos.app.ability.wantConstant.d.ts'; +### 3.发起迁移 - onContinue(wantParam : {[key: string]: any}) { - console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) - wantParam[wantConstant.Params.SUPPORT_CONTINUE_PAGE_STACK_KEY] = false; - return AbilityConstant.OnContinueResult.AGREE; - } +1.在B设备打开多设备协同权限的应用,A设备打开全局任务中心demo,A设备出现A设备名称(即:本机:OpenHarmony 3.2)和B设备名称(OpenHarmony 3.2)。 - onWindowStageRestore(windowStage) { - // 若不需要自动流转页面栈信息,则需要在此处设置应用流转后进入的页面 - windowStage.setUIContent(this.contex, "pages/index", null); - } - ``` +![hop-cross-device-migration](figures/hop-cross-device-migration5.png) -8. **可选配置:** 支持应用动态选择迁移成功后是否退出迁移发起端应用(默认流转成功后退出迁移发起端应用)。如果应用不想让系统自动退出迁移发起端应用,则可以设置不退出,参数定义见参数定义见[SUPPORT_CONTINUE_SOURCE_EXIT_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)。 +2.点击B设备名称,然后出现B设备的应用。 - - 示例:应用迁移设置不需要迁移成功后退出迁移发起端应用 +![hop-cross-device-migration](figures/hop-cross-device-migration6.png) - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import wantConstant from '@ohos.app.ability.wantConstant.d.ts'; +3.最后将应用拖拽到A设备名称处,A设备应用被拉起,B设备应用退出。 - onContinue(wantParam : {[key: string]: any}) { - console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) - wantParam[wantConstant.Params.SUPPORT_CONTINUE_SOURCE_EXIT_KEY] = false; - return AbilityConstant.OnContinueResult.AGREE; - } - ``` \ No newline at end of file +![hop-cross-device-migration](figures/hop-cross-device-migration7.png) diff --git a/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md b/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md index cf099d3fcbd12db99b15ec9c2786ace76863d651..29146ab27c0535591cb1c368e818725e7afb0001 100644 --- a/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md +++ b/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md @@ -1,4 +1,4 @@ -# 多端协同(仅对系统应用开放) +# 多端协同 ## 功能描述 @@ -56,29 +56,31 @@ 3. 获取目标设备的设备ID。 ```ts - import deviceManager from '@ohos.distributedHardware.deviceManager'; + import deviceManager from '@ohos.distributedDeviceManager'; - let dmClass; + let dmClass: deviceManager.DeviceManager; function initDmClass() { // 其中createDeviceManager接口为系统API - deviceManager.createDeviceManager('ohos.samples.demo', (err, dm) => { - if (err) { - ... - return - } - dmClass = dm - }) + try{ + dmClass = deviceManager.createDeviceManager('ohos.samples.demo'); + } catch(err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); + } } function getRemoteDeviceId() { if (typeof dmClass === 'object' && dmClass !== null) { - let list = dmClass.getTrustedDeviceListSync() + let list = dmClass.getAvailableDeviceListSync(); if (typeof (list) === 'undefined' || typeof (list.length) === 'undefined') { - console.info('EntryAbility onButtonClick getRemoteDeviceId err: list is null') + console.info('getRemoteDeviceId err: list is null'); + return; + } + if (list.length === 0) { + console.info("getRemoteDeviceId err: list is empty"); return; } - return list[0].deviceId + return list[0].networkId; } else { - console.info('EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null') + console.info('getRemoteDeviceId err: dmClass is null'); } } ``` @@ -89,8 +91,8 @@ let want = { deviceId: getRemoteDeviceId(), bundleName: 'com.example.myapplication', - abilityName: 'FuncAbility', - moduleName: 'module1', // moduleName非必选 + abilityName: 'EntryAbility', + moduleName: 'entry', // moduleName非必选 } // context为发起端UIAbility的AbilityContext this.context.startAbility(want).then(() => { @@ -100,7 +102,7 @@ }) ``` -5. 当设备A发起端应用不需要设备B上的ServiceExtensionAbility时,可调用stopServiceExtensionAbility(../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstopserviceextensionability)接口退出。(该接口不支持UIAbility的退出,UIAbility由用户手动通过任务管理退出) +5. 当设备A发起端应用不需要设备B上的ServiceExtensionAbility时,可调用[stopServiceExtensionAbility](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstopserviceextensionability)接口退出。(该接口不支持UIAbility的退出,UIAbility由用户手动通过任务管理退出) ```ts let want = { @@ -216,7 +218,7 @@ 2. 同时需要在应用首次启动时弹窗向用户申请授权,使用方式请参见[向用户申请授权](../security/accesstoken-guidelines.md#向用户申请授权)。 -3. 如果已有后台服务,请直接进入下一步;如果没有,则[实现一个后台服务](serviceextensionability.md#实现一个后台服务仅对系统应用开放)。 +3. 如果已有后台服务,请直接进入下一步;如果没有,则[实现一个后台服务](serviceextensionability.md#实现一个后台服务(仅对系统应用开放))。 4. 连接一个后台服务。 - 实现IAbilityConnection接口。IAbilityConnection提供了以下方法供开发者实现:onConnect()是用来处理连接Service成功的回调,onDisconnect()是用来处理Service异常终止的回调,onFailed()是用来处理连接Service失败的回调。 @@ -471,8 +473,8 @@ ```ts const MSG_SEND_METHOD: string = 'CallSendMsg'; - originMsg: string = ''; - backMsg: string = ''; + let originMsg: string = ''; + let backMsg: string = ''; async onButtonCallWithResult(originMsg, backMsg) { try { let msg = new MyParcelable(1, originMsg); diff --git a/zh-cn/application-dev/application-models/inter-device-interaction-hop-overview.md b/zh-cn/application-dev/application-models/inter-device-interaction-hop-overview.md index 94f2d55e2a39282e55ec353192854301107c02ad..e98c34bbb7523ebfdeee168607a29c9298a902b1 100644 --- a/zh-cn/application-dev/application-models/inter-device-interaction-hop-overview.md +++ b/zh-cn/application-dev/application-models/inter-device-interaction-hop-overview.md @@ -12,7 +12,7 @@ - **流转** - 在OpenHarmony中泛指跨多设备的分布式操作。流转能力打破设备界限,多设备联动,使用户应用程序可分可合、可流转,实现如邮件跨设备编辑、多设备协同健身、多屏游戏等分布式业务。流转为开发者提供更广的使用场景和更新的产品视角,强化产品优势,实现体验升级。流转按照使用场景可分为**跨端迁移**和**多端协同**。 + 在OpenHarmony中泛指跨多设备的分布式操作。流转能力打破设备界限,多设备联动,使用户应用程序可分可合、可流转,实现如跨设备编辑邮件、多设备协同健身、多屏游戏等分布式业务。流转为开发者提供更广的使用场景和更新的产品视角,强化产品优势,实现体验升级。流转按照使用场景可分为**跨端迁移**和**多端协同**。 - **跨端迁移** @@ -20,12 +20,15 @@ - **多端协同** - 用户拥有的多个设备,可以作为一个整体,为用户提供比单设备更加高效、沉浸的体验,这就是多端协同场景。常见的多端协同场景实例:场景一:两台设备A和B打开备忘录同一篇笔记进行双端协同编辑,在设备A上可以使用本地图库中的图片资源插入编辑,设备B上进行文字内容编辑。场景二:设备A上正在和客户进行聊天,客户需要的资料在设备B上,可以通过聊天软件打开设备B上的文档应用选择到想要的资料回传到设备A上,然后通过聊天软件发送给客户。在应用开发层面,多端协同指多端上的不同UIAbility/ServiceExtensionAbility同时运行、或者交替运行实现完整的业务;或者多端上的相同UIAbility/ServiceExtensionAbility同时运行实现完整的业务。 + 用户拥有的多个设备,可以作为一个整体,为用户提供比单设备更加高效、沉浸的体验,这就是多端协同场景。常见的多端协同场景实例: + + - 场景一:两台设备A和B打开备忘录同一篇笔记进行双端协同编辑,在设备A上可以使用本地图库中的图片资源插入编辑,设备B上进行文字内容编辑。 + - 场景二:设备A上正在和客户进行聊天,客户需要的资料在设备B上,可以通过聊天软件打开设备B上的文档应用选择到想要的资料回传到设备A上,然后通过聊天软件发送给客户。在应用开发层面,多端协同指多端上的不同UIAbility/ServiceExtensionAbility同时运行、或者交替运行实现完整的业务;或者多端上的相同UIAbility/ServiceExtensionAbility同时运行实现完整的业务。 ## 流转架构 -OpenHarmony流转提供了一组API库,可让用户应用程序更轻松、快捷地完成流转体验。OpenHarmony流转架构有如下优势: +OpenHarmony流转提供了可以流转的能力,可让用户应用程序更轻松、快捷地完成流转体验。OpenHarmony流转架构有如下优势: - 支持远程服务调用等能力,可轻松设计业务。 @@ -39,9 +42,9 @@ OpenHarmony流转提供了一组API库,可让用户应用程序更轻松、快 ![hop-structure](figures/hop-structure.png) -- 跨端迁移任务管理:在迁移发起端,接受用户迁移的意图,提供迁移流转入口,迁移结果显示等能力。(该能力尚未构建。) +- 跨端迁移任务管理:在迁移发起端,接受用户迁移的意图,提供迁移流转入口,迁移结果显示等能力。 -- 多端协同任务管理:在协同发起端,接受用户应用程序注册,提供协同入口、状态显示、退出流转等管理能力。(该能力尚未构建。) +- 多端协同任务管理:在协同发起端,接受用户应用程序注册,提供协同入口、状态显示、退出流转等管理能力。 - 分布式组件管理服务:提供远程服务启动、远程服务连接、远程迁移等能力,并通过不同能力组合,支撑用户应用程序完成跨端迁移或多端协同的业务体验。 diff --git a/zh-cn/application-dev/application-models/service-widget-overview.md b/zh-cn/application-dev/application-models/service-widget-overview.md index f6c0368123f7994fe5205e875ddae6bd21da0192..943569f9b56cfbf5a459d5abe69af04cfd874754 100644 --- a/zh-cn/application-dev/application-models/service-widget-overview.md +++ b/zh-cn/application-dev/application-models/service-widget-overview.md @@ -58,6 +58,10 @@ ArkTS卡片与JS卡片具备不同的实现原理及特征,在场景能力上 ## 相关实例 +此文档中示例代码均有完整示例工程对应,具体对应关系如下: + +- [ArkTS卡片开发指导 - 开发卡片页面](https://gitee.com/openharmony/applications_app_samples/tree/master/code/DocsSample/Form/ArkTSCardDocsSample) + 针对Stage模型卡片提供方的开发,有以下相关实例可供参考: - [ArkTS音乐卡片(ArkTS)(Full SDK)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/Widget/ArkTSCard/MusicControl) @@ -69,3 +73,4 @@ ArkTS卡片与JS卡片具备不同的实现原理及特征,在场景能力上 - [ArkTS卡片Canvas小游戏(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/Widget/ArkTSCard/CanvasGame) - [ArkTS卡片计算器(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/Widget/ArkTSCard/Calculator) + diff --git a/zh-cn/application-dev/application-test/arkxtest-guidelines.md b/zh-cn/application-dev/application-test/arkxtest-guidelines.md index 29e2464dba9a5d09793be810c45b576aa1ca7699..d5aedd5640d18520cab208be7402a1a581e24c0f 100644 --- a/zh-cn/application-dev/application-test/arkxtest-guidelines.md +++ b/zh-cn/application-dev/application-test/arkxtest-guidelines.md @@ -71,33 +71,34 @@ DevEco Studio可参考其官网介绍进行[下载](https://developer.harmonyos. 如下示例代码实现的场景是:启动测试页面,检查设备当前显示的页面是否为预期页面。 -```TS -import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; +```js +import { describe, it, expect } from '@ohos/hypium'; import abilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import { BusinessError } from '@ohos.base'; +import UIAbility from '@ohos.app.ability.UIAbility'; const delegator = abilityDelegatorRegistry.getAbilityDelegator() +function sleep(time: number) { + return new Promise((resolve: Function) => setTimeout(resolve, time)); +} export default function abilityTest() { - describe('ActsAbilityTest', function () { - it('testUiExample',0, async function (done) { + describe('ActsAbilityTest', () =>{ + it('testUiExample',0, async (done: Function) => { console.info("uitest: TestUiExample begin"); //start tested ability - await delegator.executeShellCommand('aa start -b com.ohos.uitest -a EntryAbility').then(result =>{ + await delegator.executeShellCommand('aa start -b com.ohos.uitest -a EntryAbility').then((result: abilityDelegatorRegistry.ShellCmdResult) =>{ console.info('Uitest, start ability finished:' + result) - }).catch(err => { + }).catch((err: BusinessError) => { console.info('Uitest, start ability failed: ' + err) }) await sleep(1000); //check top display ability - await delegator.getCurrentTopAbility().then((Ability)=>{ + await delegator.getCurrentTopAbility().then((Ability: UIAbility)=>{ console.info("get top ability"); expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility'); }) done(); }) - - function sleep(time) { - return new Promise((resolve) => setTimeout(resolve, time)); - } }) } ``` @@ -109,34 +110,44 @@ export default function abilityTest() { 1.增加依赖导包。 ```js -import {Driver,ON,Component,MatchPattern} from '@ohos.uitest' +import { Driver, ON } from '@ohos.UiTest' ``` 2.编写具体测试代码。 ```js +import { describe, it, expect } from '@ohos/hypium'; +import abilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import { Driver, ON } from '@ohos.UiTest' +import { BusinessError } from '@ohos.base'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +const delegator: abilityDelegatorRegistry.AbilityDelegator = abilityDelegatorRegistry.getAbilityDelegator() +function sleep(time: number) { + return new Promise((resolve: Function) => setTimeout(resolve, time)); +} export default function abilityTest() { - describe('ActsAbilityTest', function () { - it('testUiExample',0, async function (done) { + describe('ActsAbilityTest', () => { + it('testUiExample',0, async (done: Function) => { console.info("uitest: TestUiExample begin"); //start tested ability - await delegator.executeShellCommand('aa start -b com.ohos.uitest -a EntryAbility').then(result =>{ + await delegator.executeShellCommand('aa start -b com.ohos.uitest -a EntryAbility').then((result: abilityDelegatorRegistry.ShellCmdResult) =>{ console.info('Uitest, start ability finished:' + result) - }).catch(err => { + }).catch((err: BusinessError) => { console.info('Uitest, start ability failed: ' + err) }) await sleep(1000); //check top display ability - await delegator.getCurrentTopAbility().then((Ability)=>{ + await delegator.getCurrentTopAbility().then((Ability: UIAbility)=>{ console.info("get top ability"); expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility'); }) //ui test code //init driver - var driver = await Driver.create(); + let driver = await Driver.create(); await driver.delayMs(1000); //find button on text 'Next' - var button = await driver.findComponent(ON.text('Next')); + let button = await driver.findComponent(ON.text('Next')); //click button await button.click(); await driver.delayMs(1000); @@ -145,10 +156,6 @@ export default function abilityTest() { await driver.pressBack(); done(); }) - - function sleep(time) { - return new Promise((resolve) => setTimeout(resolve, time)); - } }) } ``` diff --git a/zh-cn/application-dev/database/data-sync-of-rdb-store.md b/zh-cn/application-dev/database/data-sync-of-rdb-store.md index 9f8030ff400296a9551cd000f41894c644d89787..6a9a67714174a2ffecd4927fcd09bcdfeb1e4363 100644 --- a/zh-cn/application-dev/database/data-sync-of-rdb-store.md +++ b/zh-cn/application-dev/database/data-sync-of-rdb-store.md @@ -44,8 +44,6 @@ - 单个数据库最多支持注册8个订阅数据变化的回调。 -- 不支持非系统应用调用需要指定设备的分布式能力接口。 - ## 接口说明 @@ -142,34 +140,35 @@ > **说明:** > - > deviceIds通过调用[devManager.getTrustedDeviceListSync](../reference/apis/js-apis-device-manager.md#gettrusteddevicelistsync)方法得到,deviceManager模块的接口均为系统接口,仅系统应用可用。 + > deviceIds通过调用[deviceManager.getAvailableDeviceListSync](../reference/apis/js-apis-distributedDeviceManager.md#getavailabledevicelistsync)方法得到。 ```js // 获取deviceIds - import deviceManager from '@ohos.distributedHardware.deviceManager'; - - deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.info(`Failed to create device manager. Code:${err.code},message:${err.message}`); - return; - } - let devices = manager.getTrustedDeviceListSync(); - let deviceId = devices[0].deviceId; - - // 构造用于查询分布式表的谓词对象 - let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); - // 调用跨设备查询接口,并返回查询结果 - store.remoteQuery(deviceId, 'EMPLOYEE', predicates, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES'], - function (err, resultSet) { - if (err) { - console.error(`Failed to remoteQuery data. Code:${err.code},message:${err.message}`); - return; - } - console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); + import deviceManager from '@ohos.distributedDeviceManager'; + let dmInstance = null; + let deviceId = null; + + try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + deviceId = devices[0].networkId; + + // 构造用于查询分布式表的谓词对象 + let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); + // 调用跨设备查询接口,并返回查询结果 + store.remoteQuery(deviceId, 'EMPLOYEE', predicates, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES'], + function (err, resultSet) { + if (err) { + console.error(`Failed to remoteQuery data. Code:${err.code},message:${err.message}`); + return; } - ) - }) + console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); + } + ) + } catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); + } ``` ## 相关实例 diff --git a/zh-cn/application-dev/database/share-data-by-datashareextensionability.md b/zh-cn/application-dev/database/share-data-by-datashareextensionability.md index 831902663ef160655c5bb85b804fde2b62e0e77e..bda623ca8a2e402873f7727414d82128817b22e8 100644 --- a/zh-cn/application-dev/database/share-data-by-datashareextensionability.md +++ b/zh-cn/application-dev/database/share-data-by-datashareextensionability.md @@ -64,6 +64,8 @@ import Extension from '@ohos.application.DataShareExtensionAbility'; import rdb from '@ohos.data.relationalStore'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; + import relationalStore from '@ohos.data.relationalStore'; + import Want from '@ohos.app.ability.Want'; ``` 4. 数据提供方的业务实现由开发者自定义。例如可以通过数据库、读写文件或访问网络等各方式实现数据提供方的数据存储。 @@ -75,20 +77,20 @@ + TBL_NAME + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)'; - let rdbStore; - let result; + let rdbStore: relationalStore.RdbStore; + let result: string; export default class DataShareExtAbility extends Extension { - private rdbStore_; + private rdbStore_: relationalStore.RdbStore; // 重写onCreate接口 - onCreate(want, callback) { + onCreate(want: Want, callback: Function) { result = this.context.cacheDir + '/datashare.txt'; // 业务实现使用RDB rdb.getRdbStore(this.context, { name: DB_NAME, securityLevel: rdb.SecurityLevel.S1 - }, function (err, data) { + }, (err, data) => { rdbStore = data; rdbStore.executeSql(DDL_TBL_CREATE, [], (err) => { console.info(`DataShareExtAbility onCreate, executeSql done err:${err}`); @@ -100,7 +102,7 @@ } // 重写query接口 - query(uri, predicates, columns, callback) { + query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array, callback: Function) { if (predicates === null || predicates === undefined) { console.info('invalid predicates'); } @@ -188,6 +190,8 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import dataShare from '@ohos.data.dataShare'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; + import { ValuesBucket } from '@ohos.data.ValuesBucket' + import window from '@ohos.window'; ``` 2. 定义与数据提供方通信的URI字符串。 @@ -200,11 +204,11 @@ 3. 创建工具接口类对象。 ```js - let dsHelper; - let abilityContext; + let dsHelper: dataShare.DataShareHelper; + let abilityContext: Context; export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { abilityContext = this.context; dataShare.createDataShareHelper(abilityContext, dseUri, (err, data) => { dsHelper = data; @@ -217,8 +221,19 @@ ```js // 构建一条数据 - let valuesBucket = { 'name': 'ZhangSan', 'age': 21, 'isStudent': false, 'Binary': new Uint8Array([1, 2, 3]) }; - let updateBucket = { 'name': 'LiSi', 'age': 18, 'isStudent': true, 'Binary': new Uint8Array([1, 2, 3]) }; + let key1 = 'name'; + let key2 = 'age'; + let key3 = 'isStudent'; + let key4 = 'Binary'; + let valueName1 = 'ZhangSan'; + let valueName2 = 'LiSi'; + let valueAge1 = 21; + let valueAge2 = 18; + let valueIsStudent1 = false; + let valueIsStudent2 = true; + let valueBinary = new Uint8Array([1, 2, 3]); + let valuesBucket: ValuesBucket = { key1: valueName1, key2: valueAge1, key3: valueIsStudent1, key4: valueBinary }; + let updateBucket: ValuesBucket = { key1: valueName2, key2: valueAge2, key3: valueIsStudent2, key4: valueBinary }; let predicates = new dataSharePredicates.DataSharePredicates(); let valArray = ['*']; // 插入一条数据 diff --git a/zh-cn/application-dev/database/unified-data-channels.md b/zh-cn/application-dev/database/unified-data-channels.md index a8877b4abeb2857af04e57527d76b5aa2f0f9cec..3d4b0574e6cb0e274683ee5a50fb7356f5d8807b 100644 --- a/zh-cn/application-dev/database/unified-data-channels.md +++ b/zh-cn/application-dev/database/unified-data-channels.md @@ -29,7 +29,7 @@ UDMF针对多对多跨应用数据共享的不同业务场景提供了标准化 ## 接口说明 -以下是UDMF标准化数据通路的相关接口,均为异步接口。异步接口均有callback和Promise两种返回形式,下表均以callback形式为例,更多接口及使用方式请见[统一数据管理框架](../reference/apis/js-apis-data-udmf.md)。 +以下是UDMF标准化数据通路的相关接口,均为异步接口。异步接口均有callback和Promise两种返回形式,下表均以callback形式为例,更多接口及使用方式请见[标准化数据通路](../reference/apis/js-apis-data-unifiedDataChannel.md)和[标准化数据定义与描述](../reference/apis/js-apis-data-uniformTypeDescriptor.md)。 | 接口名称 | 描述 | |-----------------------------------------------------------------------------------------|---------------------------------------------| @@ -45,24 +45,25 @@ UDMF针对多对多跨应用数据共享的不同业务场景提供了标准化 ### 数据提供方 -1. 导入`@ohos.data.UDMF`模块。 +1. 导入`@ohos.data.unifiedDataChannel`和`@ohos.data.uniformTypeDescriptor`模块。 ```ts - import UDMF from '@ohos.data.UDMF'; + import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; + import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; ``` 2. 创建一个统一数据对象并插入到UDMF的公共数据通路中。 ```ts - let plainText = new UDMF.PlainText(); + let plainText = new unifiedDataChannel.PlainText(); plainText.textContent = 'hello world!'; - let unifiedData = new UDMF.UnifiedData(plainText); + let unifiedData = new unifiedDataChannel.UnifiedData(plainText); // 指定要插入数据的数据通路枚举类型 let options = { - intention: UDMF.Intention.DATA_HUB + intention: unifiedDataChannel.Intention.DATA_HUB } try { - UDMF.insertData(options, unifiedData, (err, data) => { + unifiedDataChannel.insertData(options, unifiedData, (err, data) => { if (err === undefined) { console.info(`Succeeded in inserting data. key = ${data}`); } else { @@ -76,9 +77,9 @@ UDMF针对多对多跨应用数据共享的不同业务场景提供了标准化 3. 更新上一步骤插入的统一数据对象。 ```ts - let plainText = new UDMF.PlainText(); + let plainText = new unifiedDataChannel.PlainText(); plainText.textContent = 'How are you!'; - let unifiedData = new UDMF.UnifiedData(plainText); + let unifiedData = new unifiedDataChannel.UnifiedData(plainText); // 指定要更新的统一数据对象的URI let options = { @@ -86,7 +87,7 @@ UDMF针对多对多跨应用数据共享的不同业务场景提供了标准化 }; try { - UDMF.updateData(options, unifiedData, (err) => { + unifiedDataChannel.updateData(options, unifiedData, (err) => { if (err === undefined) { console.info('Succeeded in updating data.'); } else { @@ -102,18 +103,18 @@ UDMF针对多对多跨应用数据共享的不同业务场景提供了标准化 ```ts // 指定要删除数据的数据通路枚举类型 let options = { - intention: UDMF.Intention.DATA_HUB + intention: unifiedDataChannel.Intention.DATA_HUB }; try { - UDMF.deleteData(options, (err, data) => { + unifiedDataChannel.deleteData(options, (err, data) => { if (err === undefined) { console.info(`Succeeded in deleting data. size = ${data.length}`); for (let i = 0; i < data.length; i++) { let records = data[i].getRecords(); for (let j = 0; j < records.length; j++) { - if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) { - let text = (records[j]); + if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let text = (records[j]); console.info(`${i + 1}.${text.textContent}`); } } @@ -129,28 +130,29 @@ UDMF针对多对多跨应用数据共享的不同业务场景提供了标准化 ### 数据访问方 -1. 导入`@ohos.data.UDMF`模块。 +1. 导入`@ohos.data.unifiedDataChannel`和`@ohos.data.uniformTypeDescriptor`模块。 ```ts - import UDMF from '@ohos.data.UDMF'; + import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; + import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; ``` 2. 查询存储在UDMF公共数据通路中的统一数据对象。 ```ts // 指定要查询数据的数据通路枚举类型 let options = { - intention: UDMF.Intention.DATA_HUB + intention: unifiedDataChannel.Intention.DATA_HUB }; try { - UDMF.queryData(options, (err, data) => { + unifiedDataChannel.queryData(options, (err, data) => { if (err === undefined) { console.info(`Succeeded in querying data. size = ${data.length}`); for (let i = 0; i < data.length; i++) { let records = data[i].getRecords(); for (let j = 0; j < records.length; j++) { - if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) { - let text = (records[j]); + if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let text = (records[j]); console.info(`${i + 1}.${text.textContent}`); } } diff --git a/zh-cn/application-dev/database/unified-data-definition.md b/zh-cn/application-dev/database/unified-data-definition.md index 154982e55bf74fda7cdfe889de58c78cea3b0352..8db772d70c636d25d01a12e80d13af377cac9d77 100644 --- a/zh-cn/application-dev/database/unified-data-definition.md +++ b/zh-cn/application-dev/database/unified-data-definition.md @@ -5,6 +5,7 @@ 为了构建OpenHarmony数据跨应用交互的标准定义,降低应用/业务数据交互成本,促进数据生态建设,UDMF提供了标准化的数据定义,统一定义了多种常用的数据类型。应用可以使用统一数据管理框架提供的接口创建和使用这些标准化数据类型。 +例如跨应用拖拽场景,拖出方应用可以按照标准化数据定义将拖拽数据写入[拖拽事件](../reference/arkui-ts/ts-universal-events-drag-drop.md#dragevent说明),拖入方应用从拖拽事件中读取拖拽数据并按照标准化数据定义进行数据的解析。这使得不同应用间的数据交互遵从相同的标准定义,避免了穷举式的数据类型适配,有效减少了跨应用数据交互的开发工作量。 ## 标准化数据类型 @@ -39,9 +40,9 @@ UDMF提供的标准化数据类型主要包括以下几类: ## 接口说明 -UDMF提供了统一数据对象UnifiedData,用于封装一组数据记录UnifiedRecord。数据记录UnifiedRecord则是对UDMF支持的数据内容的抽象定义,例如一条文本记录、一条图片记录等。数据记录中的数据内容类型对应为各数据类型UnifiedDataType。 +UDMF提供了统一数据对象UnifiedData,用于封装一组数据记录UnifiedRecord。数据记录UnifiedRecord则是对UDMF支持的数据内容的抽象定义,例如一条文本记录、一条图片记录等。数据记录中的数据内容类型对应为各数据类型UniformDataType。 -以下是常见的UDMF的接口说明,更多接口和具体说明,请见[统一数据管理框架](../reference/apis/js-apis-data-udmf.md)。 +以下是常见的UDMF的接口说明,更多接口和具体说明,请见[标准化数据通路](../reference/apis/js-apis-data-unifiedDataChannel.md)和[标准化数据定义与描述](../reference/apis/js-apis-data-uniformTypeDescriptor.md)。 | 类名称 | 接口名称 | 描述 | |---------------|-------------------|-----------------------------------------------------------------------------------------------| @@ -55,17 +56,18 @@ UDMF提供了统一数据对象UnifiedData,用于封装一组数据记录Unifi 以一次创建统一数据对象(包含图片、纯文本两条数据记录)为例,说明开发步骤。 -1. 导入`@ohos.data.UDMF`模块。 +1. 导入`@ohos.data.unifiedDataChannel`和`@ohos.data.uniformTypeDescriptor`模块。 ```ts - import UDMF from '@ohos.data.UDMF'; + import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; + import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; ``` 2. 创建图片数据记录,并初始化得到带有该数据记录的UnifiedData对象。 (1)创建图片数据记录。 ```ts - let image = new UDMF.Image(); + let image = new unifiedDataChannel.Image(); ``` (2)修改对象属性。 @@ -84,12 +86,12 @@ UDMF提供了统一数据对象UnifiedData,用于封装一组数据记录Unifi (4)创建一个统一数据对象实例。 ```ts - let unifiedData = new UDMF.UnifiedData(image); + let unifiedData = new unifiedDataChannel.UnifiedData(image); ``` 3. 创建纯文本数据类型记录,将其添加到刚才创建的UnifiedData对象。 ```ts - let plainText = new UDMF.PlainText(); + let plainText = new unifiedDataChannel.PlainText(); plainText.textContent = 'this is textContent of plainText'; plainText.abstract = 'abstract of plainText'; plainText.details = { @@ -110,13 +112,13 @@ UDMF提供了统一数据对象UnifiedData,用于封装一组数据记录Unifi // 读取该数据记录的类型 let type = records[i].getType(); switch (type) { - case UDMF.UnifiedDataType.IMAGE: + case uniformTypeDescriptor.UniformDataType.IMAGE: // 转换得到原图片数据记录 - let image = (records[i]); + let image = (records[i]); break; - case UDMF.UnifiedDataType.PLAIN_TEXT: + case uniformTypeDescriptor.UniformDataType.PLAIN_TEXT: // 转换得到原文本数据记录 - let plainText = (records[i]); + let plainText = (records[i]); break; default: break; diff --git a/zh-cn/application-dev/file-management/save-user-file.md b/zh-cn/application-dev/file-management/save-user-file.md index 9818de82be9377a747e8ab2c063a01ba456ca0dc..ff52752af54a91a429b72449d96abacd912a472c 100644 --- a/zh-cn/application-dev/file-management/save-user-file.md +++ b/zh-cn/application-dev/file-management/save-user-file.md @@ -58,7 +58,7 @@ save接口会将文件保存在文件管理器,而不是图库。 save返回的uri权限是读写权限,可以根据结果集里面的uri进行文件读写等操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。 ```ts - let uri:string; + let uris = null; async photoViewPickerSave() { try { const photoSaveOptions = new picker.PhotoSaveOptions(); // 创建文件管理器保存选项实例 @@ -68,9 +68,8 @@ save接口会将文件保存在文件管理器,而不是图库。 try { let photoSaveResult = await photoViewPicker.save(photoSaveOptions); if (photoSaveResult != undefined) { - console.info("[picker] photoViewPickerSave photoSaveResult = " + JSON.stringify(photoSaveResult)); - this.uri = photoSaveResult[0]; - console.info('photoViewPicker.save to file succeed and uri is:' + photoSaveResult[0]); + uris = photoSaveResult; + console.info('photoViewPicker.save to file succeed and uris are:' + uris); } } catch (err) { console.error(`[picker] Invoke photoViewPicker.save failed, code is ${err.code}, message is ${err.message}`); @@ -112,6 +111,7 @@ save接口会将文件保存在文件管理器,而不是图库。 ```ts const documentSaveOptions = new picker.DocumentSaveOptions(); // 创建文件管理器选项实例 documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; // 保存文件名(可选) + documentSaveOptions.fileSuffixChoices = ['.png', '.txt', '.mp4']; // 保存文件类型(可选) ``` 3. 创建文档选择器实例。调用[save()](../reference/apis/js-apis-file-picker.md#save-3)接口拉起FilePicker界面进行文件保存。用户选择目标文件夹,用户选择与文件类型相对应的文件夹,即可完成文件保存操作。保存成功后,返回保存文档的uri。 @@ -119,11 +119,11 @@ save接口会将文件保存在文件管理器,而不是图库。
save返回的uri权限是读写权限,可以根据结果集中uri进行文件读写等操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。 ```ts - let uri = null; + let uris = null; const documentViewPicker = new picker.DocumentViewPicker(); // 创建文件选择器实例 documentViewPicker.save(documentSaveOptions).then((documentSaveResult) => { - uri = documentSaveResult[0]; - console.info('documentViewPicker.save to file succeed and uri is:' + uri); + uris = documentSaveResult; + console.info('documentViewPicker.save to file succeed and uris are:' + uris); }).catch((err) => { console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`); }) diff --git a/zh-cn/application-dev/file-management/select-user-file.md b/zh-cn/application-dev/file-management/select-user-file.md index 7a850a82466a3fcb517ca9caf7fa2a04ab9876fb..8d8689edb49c72746e21c68b04d1970a244f46a2 100644 --- a/zh-cn/application-dev/file-management/select-user-file.md +++ b/zh-cn/application-dev/file-management/select-user-file.md @@ -38,11 +38,11 @@
select返回的uri权限是只读权限,可以根据结果集中uri进行读取文件数据操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。 ```ts - let uri = null; + let uris = null; const photoViewPicker = new picker.PhotoViewPicker(); photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => { - uri = photoSelectResult.photoUris[0]; - console.info('photoViewPicker.select to file succeed and uri is:' + uri); + uris = photoSelectResult.photoUris; + console.info('photoViewPicker.select to file succeed and uris are:' + uris); }).catch((err) => { console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`); }) @@ -77,6 +77,9 @@ ```ts const documentSelectOptions = new picker.DocumentSelectOptions(); + documentSelectOptions.maxSelectNumber = 5; // 选择文档的最大数目(可选) + documentSelectOptions.defaultFilePathUri = "file://docs/storage/Users/currentUser/test"; // 指定选择的文件或者目录路径(可选) + documentSelectOptions.fileSuffixFilters = ['.png', '.txt', '.mp4']; // 选择文件的后缀类型(可选) ``` 3. 创建文档选择器实例。调用[select()](../reference/apis/js-apis-file-picker.md#select-3)接口拉起FilePicker界面进行文件选择。文件选择成功后,返回被选中文档的uri结果集。 @@ -85,16 +88,12 @@
例如通过[文件管理接口](../reference/apis/js-apis-file-fs.md)根据uri获取部分文件属性信息,比如文件大小、访问时间、修改时间等。如有获取文件名称需求,请暂时使用[startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md)获取。 - > **说明:** - > - > 目前DocumentSelectOptions不支持参数配置,默认可以选择所有类型的用户文件。 - ```ts - let uri = null; + let uris = null; const documentViewPicker = new picker.DocumentViewPicker(); // 创建文件选择器实例 documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => { - uri = documentSelectResult[0]; - console.info('documentViewPicker.select to file succeed and uri is:' + uri); + uris = documentSelectResult; + console.info('documentViewPicker.select to file succeed and uris are:' + uris); }).catch((err) => { console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`); }) @@ -172,7 +171,7 @@ let uri = null; const audioViewPicker = new picker.AudioViewPicker(); audioViewPicker.select(audioSelectOptions).then(audioSelectResult => { - uri = audioSelectOptions[0]; + uri = audioSelectResult[0]; console.info('audioViewPicker.select to file succeed and uri is:' + uri); }).catch((err) => { console.error(`Invoke audioViewPicker.select failed, code is ${err.code}, message is ${err.message}`); diff --git a/zh-cn/application-dev/media/using-avrecorder-for-recording.md b/zh-cn/application-dev/media/using-avrecorder-for-recording.md index 98c9c4633eb25462ed4d8a6f09ab78a7b9883b4e..927c9e41f1add7583d63f14e0e41de41cfc135dc 100644 --- a/zh-cn/application-dev/media/using-avrecorder-for-recording.md +++ b/zh-cn/application-dev/media/using-avrecorder-for-recording.md @@ -20,11 +20,11 @@ ```ts import media from '@ohos.multimedia.media'; - let avRecorder = undefined; - media.createAVRecorder().then((recorder) => { + let avRecorder: media.AVRecorder; + media.createAVRecorder().then((recorder: media.AVRecorder) => { avRecorder = recorder; - }, (err) => { - console.error(`Invoke createAVRecorder failed, code is ${err.code}, message is ${err.message}`); + }, (error: Error) => { + console.error(`createAVRecorder failed`); }) ``` @@ -37,13 +37,13 @@ ```ts // 状态上报回调函数 - avRecorder.on('stateChange', (state, reason) => { + avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => { console.log(`current state is ${state}`); // 用户可以在此补充状态发生切换后想要进行的动作 }) // 错误上报回调函数 - avRecorder.on('error', (err) => { + avRecorder.on('error', (err: BusinessError) => { console.error(`avRecorder failed, code is ${err.code}, message is ${err.message}`); }) ``` @@ -61,21 +61,21 @@ ```ts - let avProfile = { + let avProfile: media.AVRecorderProfile = { audioBitrate: 100000, // 音频比特率 audioChannels: 2, // 音频声道数 audioCodec: media.CodecMimeType.AUDIO_AAC, // 音频编码格式,当前只支持aac audioSampleRate: 48000, // 音频采样率 fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // 封装格式,当前只支持m4a } - let avConfig = { + let avConfig: media.AVRecorderConfig = { audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // 音频输入源,这里设置为麦克风 profile: avProfile, url: 'fd://35', // 参考应用文件访问与管理中的开发示例获取创建的音频文件fd填入此处 } avRecorder.prepare(avConfig).then(() => { console.log('Invoke prepare succeeded.'); - }, (err) => { + }, (err: BusinessError) => { console.error(`Invoke prepare failed, code is ${err.code}, message is ${err.message}`); }) ``` @@ -99,17 +99,18 @@ ```ts import media from '@ohos.multimedia.media'; +import { BusinessError } from '@ohos.base'; export class AudioRecorderDemo { - private avRecorder; - private avProfile = { + private avRecorder: media.AVRecorder; + private avProfile: media.AVRecorderProfile = { audioBitrate: 100000, // 音频比特率 audioChannels: 2, // 音频声道数 audioCodec: media.CodecMimeType.AUDIO_AAC, // 音频编码格式,当前只支持aac audioSampleRate: 48000, // 音频采样率 fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // 封装格式,当前只支持m4a }; - private avConfig = { + private avConfig: media.AVRecorderConfig = { audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // 音频输入源,这里设置为麦克风 profile: this.avProfile, url: 'fd://35', // 参考应用文件访问与管理开发示例新建并读写一个文件 @@ -118,11 +119,11 @@ export class AudioRecorderDemo { // 注册audioRecorder回调函数 setAudioRecorderCallback() { // 状态机变化回调函数 - this.avRecorder.on('stateChange', (state, reason) => { + this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => { console.log(`AudioRecorder current state is ${state}`); }) // 错误上报回调函数 - this.avRecorder.on('error', (err) => { + this.avRecorder.on('error', (err: BusinessError) => { console.error(`AudioRecorder failed, code is ${err.code}, message is ${err.message}`); }) } diff --git a/zh-cn/application-dev/media/video-recording.md b/zh-cn/application-dev/media/video-recording.md index 7cdf749e64ad558962d06fe7d15de88ab0f77b36..49bea13d413b18b100975e43a2cab41af8661d60 100644 --- a/zh-cn/application-dev/media/video-recording.md +++ b/zh-cn/application-dev/media/video-recording.md @@ -24,10 +24,10 @@ AVRecorder详细的API说明请参考[AVRecorder API参考](../reference/apis/js ```ts import media from '@ohos.multimedia.media' - let avRecorder - media.createAVRecorder().then((recorder) => { + let avRecorder: media.AVRecorder; + media.createAVRecorder().then((recorder: media.AVRecorder) => { avRecorder = recorder - }, (error) => { + }, (error: Error) => { console.error('createAVRecorder failed') }) ``` @@ -40,11 +40,11 @@ AVRecorder详细的API说明请参考[AVRecorder API参考](../reference/apis/js ```ts // 状态上报回调函数 - avRecorder.on('stateChange', (state, reason) => { + avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => { console.info('current state is: ' + state); }) // 错误上报回调函数 - avRecorder.on('error', (err) => { + avRecorder.on('error', (err: BusinessError) => { console.error('error happened, error message is ' + err); }) ``` @@ -62,7 +62,7 @@ AVRecorder详细的API说明请参考[AVRecorder API参考](../reference/apis/js > - 录制输出的url地址(即示例里avConfig中的url),形式为fd://xx (fd number)。需要调用基础文件操作接口([ohos.file.fs](../reference/apis/js-apis-file-fs.md))实现应用文件访问能力,获取方式参考[应用文件访问与管理](../file-management/app-file-access.md)。 ```ts - let avProfile = { + let avProfile: media.AVRecorderProfile = { fileFormat : media.ContainerFormatType.CFT_MPEG_4, // 视频文件封装格式,只支持MP4 videoBitrate : 200000, // 视频比特率 videoCodec : media.CodecMimeType.VIDEO_AVC, // 视频文件编码格式,支持mpeg4和avc两种格式 @@ -70,15 +70,15 @@ AVRecorder详细的API说明请参考[AVRecorder API参考](../reference/apis/js videoFrameHeight : 480, // 视频分辨率的高 videoFrameRate : 30 // 视频帧率 } - let avConfig = { + let avConfig: media.AVRecorderConfig = { videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // 视频源类型,支持YUV和ES两种格式 - profile : this.avProfile, + profile : avProfile, url : 'fd://35', // 参考应用文件访问与管理开发示例新建并读写一个文件 rotation : 0, // 视频旋转角度,默认为0不旋转,支持的值为0、90、180、270 } avRecorder.prepare(avConfig).then(() => { console.info('avRecorder prepare success') - }, (error) => { + }, (error: Error) => { console.error('avRecorder prepare failed') }) ``` @@ -89,9 +89,9 @@ AVRecorder详细的API说明请参考[AVRecorder API参考](../reference/apis/js 输入源模块通过SurfaceID可以获取到Surface,通过Surface可以将视频数据流传递给AVRecorder,由AVRecorder再进行视频数据的处理。 ```ts - avRecorder.getInputSurface().then((surfaceId) => { + avRecorder.getInputSurface().then((surfaceId: string) => { console.info('avRecorder getInputSurface success') - }, (error) => { + }, (error: Error) => { console.error('avRecorder getInputSurface failed') }) ``` @@ -118,11 +118,12 @@ AVRecorder详细的API说明请参考[AVRecorder API参考](../reference/apis/js ```ts import media from '@ohos.multimedia.media' +import { BusinessError } from '@ohos.base'; const TAG = 'VideoRecorderDemo:' export class VideoRecorderDemo { - private avRecorder; - private videoOutSurfaceId; - private avProfile = { + private avRecorder: media.AVRecorder; + private videoOutSurfaceId: string; + private avProfile: media.AVRecorderProfile = { fileFormat : media.ContainerFormatType.CFT_MPEG_4, // 视频文件封装格式,只支持MP4 videoBitrate : 100000, // 视频比特率 videoCodec : media.CodecMimeType.VIDEO_AVC, // 视频文件编码格式,支持mpeg4和avc两种格式 @@ -130,7 +131,7 @@ export class VideoRecorderDemo { videoFrameHeight : 480, // 视频分辨率的高 videoFrameRate : 30 // 视频帧率 } - private avConfig = { + private avConfig: media.AVRecorderConfig = { videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // 视频源类型,支持YUV和ES两种格式 profile : this.avProfile, url : 'fd://35', // 参考应用文件访问与管理开发示例新建并读写一个文件 @@ -140,11 +141,11 @@ export class VideoRecorderDemo { // 注册avRecorder回调函数 setAvRecorderCallback() { // 状态机变化回调函数 - this.avRecorder.on('stateChange', (state, reason) => { + this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => { console.info(TAG + 'current state is: ' + state); }) // 错误上报回调函数 - this.avRecorder.on('error', (err) => { + this.avRecorder.on('error', (err: BusinessError) => { console.error(TAG + 'error ocConstantSourceNode, error message is ' + err); }) } @@ -183,7 +184,7 @@ export class VideoRecorderDemo { // 5.启动相机出流 await this.startCameraOutput(); // 6. 启动录制 - await this.videoRecorder.start(); + await this.avRecorder.start(); } // 暂停录制对应的流程 diff --git a/zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md b/zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md index 7df90501a582c02e796a5eb61a73013dc14335ee..d63149dcb8418d6d5bf6028dcbeb074f1b1ff1fa 100644 --- a/zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md +++ b/zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md @@ -35,7 +35,7 @@ | ----------------- | ---------------------------------------- | | 装饰器参数 | 无 | | 同步类型 | 不与父组件中的任何类型同步变量。 | -| 允许装饰的变量类型 | 必须为被\@Observed装饰的class实例,必须指定类型。
不支持简单类型,可以使用[\@Prop](arkts-prop.md)。
\@ObjectLink的属性是可以改变的,但是变量的分配是不允许的,也就是说这个装饰器装饰变量是只读的,不能被改变。 | +| 允许装饰的变量类型 | 必须为被\@Observed装饰的class实例,必须指定类型。
不支持简单类型,可以使用[\@Prop](arkts-prop.md)。
支持继承Date或者Array的class实例,示例见[观察变化](#观察变化)。
\@ObjectLink的属性是可以改变的,但是变量的分配是不允许的,也就是说这个装饰器装饰变量是只读的,不能被改变。 | | 被装饰变量的初始值 | 不允许。 | \@ObjectLink装饰的数据为可读示例。 @@ -75,7 +75,7 @@ this.objLink= ... ## 观察变化和行为表现 -### 观察的变化 +### 观察变化 \@Observed装饰的类,如果其属性为非简单类型,比如class、Object或者数组,也需要被\@Observed装饰,否则将观察不到其属性的变化。 @@ -121,6 +121,67 @@ this.b.a.c = 5 - 如果数据源是数组,则可以观察到数组item的替换,如果数据源是class,可观察到class的属性的变化,示例请参考[对象数组](#对象数组)。 +继承Date的class时,可以观察到Date整体的赋值,同时可通过调用Date的接口`setFullYear`, `setMonth`, `setDate`, `setHours`, `setMinutes`, `setSeconds`, `setMilliseconds`, `setTime`, `setUTCFullYear`, `setUTCMonth`, `setUTCDate`, `setUTCHours`, `setUTCMinutes`, `setUTCSeconds`, `setUTCMilliseconds` 更新Date的属性。 + +```ts +@Observed +class DateClass extends Date { + constructor(args: any) { + super(args) + } +} + +@Observed +class ClassB { + public a: DateClass; + + constructor(a: DateClass) { + this.a = a; + } +} + +@Component +struct ViewA { + label: string = 'date'; + @ObjectLink a: DateClass; + + build() { + Column() { + Button(`child increase the day by 1`) + .onClick(() => { + this.a.setDate(this.a.getDate() + 1); + }) + DatePicker({ + start: new Date('1970-1-1'), + end: new Date('2100-1-1'), + selected: this.a + }) + } + } +} + +@Entry +@Component +struct ViewB { + @State b: ClassB = new ClassB(new DateClass('2023-1-1')); + + build() { + Column() { + ViewA({ label: 'date', a: this.b.a }) + + Button(`parent update the new date`) + .onClick(() => { + this.b.a = new DateClass('2023-07-07'); + }) + Button(`ViewB: this.b = new ClassB(new DateClass('2023-08-20'))`) + .onClick(() => { + this.b = new ClassB(new DateClass('2023-08-20')); + }) + } + } +} +``` + ### 框架行为 diff --git a/zh-cn/application-dev/quick-start/module-configuration-file.md b/zh-cn/application-dev/quick-start/module-configuration-file.md index 5e4386be6f46b3990fadaaa080681d0736c4c48d..085ef79b42632f790059ce8da80322055b85af94 100644 --- a/zh-cn/application-dev/quick-start/module-configuration-file.md +++ b/zh-cn/application-dev/quick-start/module-configuration-file.md @@ -97,6 +97,7 @@ module.json5配置文件包含以下标签。 | isolationMode | 标识当前Module的多进程配置项。类型有4种,分别:
- nonisolationFirst:优先在非独立进程中运行。
- isolationFirst:优先在独立进程中运行。
- isolationOnly:只在独立进程中运行。
- nonisolationOnly:只在非独立进程中运行。 |字符串|该标签可缺省, 缺省值为nonisolationFirst。| | generateBuildHash |标识当前HAP/HSP是否由打包工具生成哈希值。如果存在,则在系统OTA升级但应用的versionCode保持不变时,可根据哈希值判断应用是否需要升级。
该字段仅在[app.json5文件](./app-configuration-file.md)中的generateBuildHash字段为false时使能。**
注:该字段仅对预置应用生效。**|布尔值|该标签可缺省, 缺省值为false。| | compressNativeLibs | 标识libs库是否以压缩存储的方式打包到HAP。
- true:libs库以压缩方式存储。
- false:libs库以不压缩方式存储,HAP在安装时无需解压libs,运行时会直接从HAP内加载libs库。 | 布尔值 | 可缺省,缺省值为true。 | +| libIsolation | 用于区分同应用不同hap下的so文件,以防止so冲突。
- true:当前hap的so会储存在libs目录中以Module名命名的路径下。
- false:当前hap的so会直接储存在libs目录中。 | 布尔值 | 该标签可缺省, 缺省值为false。 | ## deviceTypes标签 diff --git a/zh-cn/application-dev/quick-start/module-structure.md b/zh-cn/application-dev/quick-start/module-structure.md index 58e1254a06a0ec69494b52a5a74f1770b772e6dc..afc0c0451ae6a5a1aeecea3ff91b65d8b4457829 100644 --- a/zh-cn/application-dev/quick-start/module-structure.md +++ b/zh-cn/application-dev/quick-start/module-structure.md @@ -25,6 +25,7 @@ module对象包含HAP的配置信息。 | entryTheme | 此标签标识OpenHarmony内部主题的关键字。将标记值设置为名称的资源索引。 | 字符串 | 可缺省,缺省值为空。 | |testRunner | 此标签用于支持对测试框架的配置。 | 对象 | 可缺省,缺省值为空。 | |generateBuildHash |标识当前HAP/HSP是否由打包工具生成哈希值。如果存在,则在系统OTA升级但应用的[version下的code](./app-structure.md#version对象内部结构)保持不变时,可根据哈希值判断应用是否需要升级。**
注:该字段仅对预置应用生效。**|布尔值|该标签可缺省, 缺省值为false。| +|libIsolation |用于区分同应用不同hap下的so文件,以防止so冲突。
- true:当前hap的so会储存在libs目录中以Module名命名的路径下。
- false:当前hap的so会直接储存在libs目录中。|布尔值|该标签可缺省, 缺省值为false。| module示例: diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md b/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md index 648a68b075820e6959991f119c481be24c1ff8da..ac6dfc795a1f34ed7bf4a47d4e86754910d4c548 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md @@ -15,7 +15,14 @@ import ability from '@ohos.ability.ability'; ## 属性 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase +**系统能力**: +DataAbilityHelper:SystemCapability.Ability.AbilityRuntime.FAModel +PacMap:SystemCapability.Ability.AbilityRuntime.FAModel +DataAbilityOperation:SystemCapability.Ability.AbilityRuntime.FAModel +DataAbilityResult:SystemCapability.Ability.AbilityRuntime.FAModel +AbilityResult:SystemCapability.Ability.AbilityBase +ConnectOptions:SystemCapability.Ability.AbilityRuntime.Core +StartAbilityParameter:SystemCapability.Ability.AbilityRuntime.FAModel | 名称 | 类型 | 描述 | | ----------- | -------------------- | ------------------------------------------------------------ | diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-actionExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-actionExtensionAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..714835a8486aedc304100c4584ab270b179b85ae --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-actionExtensionAbility.md @@ -0,0 +1,165 @@ +# @ohos.app.ability.ActionExtensionAbility (自定义服务扩展能力) + +ActionExtensionAbility是为开发者提供的自定义操作业务模板,继承自[UIExtensionAbility](js-apis-app-ability-uiExtensionAbility.md)。ActionExtension主要用于查看宿主应用中的内容以及对其进行对应处理。例如,添加一个书签、将选中的文本翻译成其他语言、在当前页面编辑图像等。 + +> **说明:** +> +> 本模块首批接口从API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 本模块接口仅可在Stage模型下使用。 + +## 场景介绍 + +以翻译文本为例。首先需要创建请求发起方,再创建出ActionExtension,请求发起方需要将翻译的文本发送给ActionExtension,ActionExtension接收到文本后,需要将接收的文本进行翻译,翻译后的文本再发送给请求发起方。 + +## 导入模块 + +```ts +import ActionExtensionAbility from '@ohos.app.ability.ActionExtensionAbility'; +``` + +## 属性 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| context | [UIExtensionContext](js-apis-inner-application-uiExtensionContext.md) | 是 | 否 | 上下文。 | + +## ActionExtensionAbility.onCreate + +onCreate(): void + +ActionExtensionAbility创建时回调,执行初始化业务逻辑操作。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +## ActionExtensionAbility.onSessionCreate + +onSessionCreate(want: Want, session: UIExtensionContentSession): void + +当ActionExtensionAbility界面内容对象创建后调用。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md) | 是 | 当前ActionExtensionAbility的Want类型信息,包括ability名称、bundle名称等。 | +| session | [UIExtensionContentSession](js-apis-app-ability-uiExtensionContentSession.md) | 是 | ActionExtensionAbility界面内容相关信息。 | + +## ActionExtensionAbility.onSessionDestroy + +onSessionDestroy(session: UIExtensionContentSession): void + +当ActionExtensionAbility界面内容对象销毁后调用。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| session | [UIExtensionContentSession](js-apis-app-ability-uiExtensionContentSession.md) | 是 | ActionExtensionAbility界面内容相关信息。 | + +## ActionExtensionAbility.onForeground + +onForeground(): void; + +ActionExtensionAbility生命周期回调,当ActionExtensionAbility从后台转到前台时触发。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +## ActionExtensionAbility.onBackground + +onBackground(): void; + +ActionExtensionAbility生命周期回调,当ActionExtensionAbility从前台转到后台时触发。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +## ActionExtensionAbility.onDestroy + +onDestroy(): void | Promise<void>; + +ActionExtensionAbility生命周期回调,在销毁时回调,执行资源清理等操作。 +在执行完onDestroy生命周期回调后,应用可能会退出,从而可能导致onDestroy中的异步函数未能正确执行,比如异步写入数据库。可以使用异步生命周期,以确保异步onDestroy完成后再继续后续的生命周期。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +## 创建ActionExtensionAbility + +在DevEco Studio工程中手动新建一个ActionExtensionAbility,具体步骤如下: + +1. 在工程Module对应的ets目录下,右键选择“New > Directory”,新建一个目录并命名为ActionExtAbility。 + +2. 在ActionExtAbility目录,右键选择“New > TypeScript File”,新建一个TypeScript文件并命名为ActionExtAbility.ts。 + + ``` + ├── ets + │ ├── ActionExtAbility + │ │ ├── ActionExtAbility.ts + └ + ``` + +3. ActionExtAbility.ts文件中,增加导入ActionExtensionAbility的依赖包,自定义类继承ActionExtensionAbility并实现生命周期回调。 + + ```ts + import ActionExtensionAbility from '@ohos.app.ability.ActionExtensionAbility'; + const TAG: string = "[ActionExtAbility]"; + + export default class ActionExtAbility extends ActionExtensionAbility { + storage: LocalStorage; + message: string; + onCreate() { + console.info(TAG, `onCreate`); + } + + onForeground() { + console.info(TAG, `ononForeground`); + } + + onBackground() { + console.info(TAG, `onBackground`); + } + + onSessionCreate(want, session) { + console.info(TAG, `onSessionCreate, want: ${want.abilityName}`); + this.message = want.parameters.shareMessages; + this.storage = new LocalStorage( + { + 'session': session, + 'messages': this.message + }); + session.loadContent('pages/Index', this.storage); + } + + onSessionDestroy(session) { + console.info(TAG, `onSessionDestroy`); + } + + onDestroy() { + console.info(TAG, `onDestroy`); + } + } + ``` + +4. 在工程Module对应的[module.json5配置文件](../../quick-start/module-configuration-file.md)中注册ActionExtensionAbility,type标签需要设置为“action”,srcEntry标签表示当前ExtensionAbility组件所对应的代码路径。 + + ```json + { + "module": { + ... + "extensionAbilities": [ + { + "name": "ActionExtAbility", + "icon": "$media:icon", + "description": "action", + "type": "action", + "exported": true, + "srcEntry": "./ets/ActionExtAbility/ActionExtAbility.ts" + } + ] + } + } + ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md index 5a2f72d2684e110b1d351e14f32f4a2cbce6f40f..880d3e02b81c105c2cdeec1bb74f3e61da5eb7c7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md @@ -16,6 +16,8 @@ import common from '@ohos.app.ability.common'; **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core +**系统API**:该接口为系统接口,三方应用不支持调用。 + | 名称 | 类型 | 说明 | | ----------- | -------------------- | ------------------------------------------------------------ | | UIAbilityContext | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | UIAbilityContext二级模块。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md index 7b01e5e25d1e8938c40cc268a9c671fc44ee30f1..05be616d309b30dc17842f01ae51e98c51d3c3ff 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md @@ -309,12 +309,6 @@ revokeQuickFix(bundleName: string): Promise\; 在撤销补丁过程中发生的错误,其错误码及错误信息通过公共事件[COMMON_EVENT_QUICK_FIX_REVOKE_RESULT](./common_event/commonEvent-ability.md#common_event_quick_fix_revoke_result10)的参数返回给应用开发者。这部分错误码及错误信息如下: -| 错误码ID | 错误信息 | -| ------- | -------- | -| 18500004 | Switch hqf failed. | -| 18500005 | Delete hqf failed. | -| 18500007 | Unload patch failed. | - **示例:** ```ts diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-shareExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-shareExtensionAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..fdeddbadb84b2d5f99b393c26178c35de9a12ec4 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-shareExtensionAbility.md @@ -0,0 +1,163 @@ +# @ohos.app.ability.ShareExtensionAbility (分享模板服务扩展能力) + +ShareExtensionAbility是为开发者提供分享操作业务模板,继承自[UIExtensionAbility](js-apis-app-ability-uiExtensionAbility.md)。ShareExtension为人们提供了一种通过应用程序、社交媒体帐户和其他服务共享当前上下文信息的便捷方式。 + +> **说明:** +> +> 本模块首批接口从API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 本模块接口仅可在Stage模型下使用。 + +## 场景介绍 + +以分享文本为例。用户选择一段文本,拉起要分享应用,此时被分享拉起的应用会根据分享信息将分享模板拉起,并将数据按分享模板内容显示。 + +## 导入模块 + +```ts +import ShareExtensionAbility from '@ohos.app.ability.ShareExtensionAbility'; +``` + +## 属性 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| context | [UIExtensionContext](js-apis-inner-application-uiExtensionContext.md) | 是 | 否 | 上下文。 | + +## ShareExtensionAbility.onCreate + +onCreate(): void + +ShareExtensionAbility创建时回调,执行初始化业务逻辑操作。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +## ShareExtensionAbility.onSessionCreate + +onSessionCreate(want: Want, session: UIExtensionContentSession): void + +当ShareExtensionAbility界面内容对象创建后调用。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md) | 是 | 当前ShareExtensionAbility的Want类型信息,包括ability名称、bundle名称等。 | +| session | [UIExtensionContentSession](js-apis-app-ability-uiExtensionContentSession.md) | 是 | ShareExtensionAbility界面内容相关信息。 | + +## ShareExtensionAbility.onSessionDestroy + +onSessionDestroy(session: UIExtensionContentSession): void + +当ShareExtensionAbility界面内容对象销毁后调用。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| session | [UIExtensionContentSession](js-apis-app-ability-uiExtensionContentSession.md) | 是 | ShareExtensionAbility界面内容相关信息。 | + +## ShareExtensionAbility.onForeground + +onForeground(): void; + +ShareExtensionAbility生命周期回调,当ShareExtensionAbility从后台转到前台时触发。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +## ShareExtensionAbility.onBackground + +onBackground(): void; + +ShareExtensionAbility生命周期回调,当ShareExtensionAbility从前台转到后台时触发。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +## ShareExtensionAbility.onDestroy + +onDestroy(): void | Promise<void>; + +ShareExtensionAbility生命周期回调,在销毁时回调,执行资源清理等操作。 +在执行完onDestroy生命周期回调后,应用可能会退出,从而可能导致onDestroy中的异步函数未能正确执行,比如异步写入数据库。可以使用异步生命周期,以确保异步onDestroy完成后再继续后续的生命周期。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +## 创建ShareExtensionAbility + +在DevEco Studio工程中手动新建一个ShareExtensionAbility,具体步骤如下: + +1. 在工程Module对应的ets目录下,右键选择“New > Directory”,新建一个目录并命名为ShareExtAbility。 + +2. 在ShareExtAbility目录,右键选择“New > TypeScript File”,新建一个TypeScript文件并命名为ShareExtAbility.ts。 + + ``` + ├── ets + │ ├── ShareExtAbility + │ │ ├── ShareExtAbility.ts + └ + ``` + +3. ShareExtAbility.ts文件中,增加导入ShareExtensionAbility的依赖包,自定义类继承ShareExtensionAbility并实现生命周期回调。 + + ```ts + import ShareExtensionAbility from '@ohos.app.ability.ShareExtensionAbility'; + const TAG: string = "[ShareExtAbility]"; + + export default class ShareExtAbility extends ShareExtensionAbility { + onCreate() { + console.info(TAG, `onCreate`); + } + + onForeground() { + console.info(TAG, `ononForeground`); + } + + onBackground() { + console.info(TAG, `onBackground`); + } + + onSessionCreate(want, session) { + console.info(TAG, `onSessionCreate, want: ${want.abilityName}`); + this.message = want.parameters.shareMessages; + this.storage = new LocalStorage( + { + 'session': session, + 'messages': this.message + }); + session.loadContent('pages/Index', this.storage); + } + + onSessionDestroy(session) { + console.info(TAG, `onSessionDestroy`); + } + + onDestroy() { + console.info(TAG, `onDestroy`); + } + } + ``` + +4. 在工程Module对应的[module.json5配置文件](../../quick-start/module-configuration-file.md)中注册ShareExtensionAbility,type标签需要设置为“share”,srcEntry标签表示当前ExtensionAbility组件所对应的代码路径。 + + ```json + { + "module": { + ... + "extensionAbilities": [ + { + "name": "ShareExtAbility", + "icon": "$media:icon", + "description": "share", + "type": "share", + "exported": true, + "srcEntry": "./ets/ShareExtAbility/ShareExtAbility.ts" + } + ] + } + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formObserver.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formObserver.md index 7a3ed1f4cd871af1563f3c97d046cd1ad8d49f10..68d25e0d80fc0997eadadad73642a07ef382587d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formObserver.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formObserver.md @@ -43,7 +43,7 @@ formObserver.on('formAdd', callback); ## on('formAdd') - on(type: 'formAdd', bundleName: string, observerCallback: Callback<formInfo.RunningFormInfo>): void + on(type: 'formAdd', hostBundleName: string, observerCallback: Callback<formInfo.RunningFormInfo>): void 订阅卡片新增事件。使用callback异步回调,返回指定卡片使用方应用新增卡片的[RunningFormInfo](js-apis-app-form-formInfo.md)。 @@ -74,7 +74,7 @@ formObserver.on('formAdd', bundleName, callback); ## off('formAdd') - off(type: "formAdd", bundleName?: string, observerCallback?: Callback<formInfo.RunningFormInfo>): void + off(type: "formAdd", hostBundleName?: string, observerCallback?: Callback<formInfo.RunningFormInfo>): void 取消订阅卡片新增事件。使用callback异步回调,返回当前新增卡片的[RunningFormInfo](js-apis-app-form-formInfo.md)。 @@ -138,7 +138,7 @@ formObserver.on('formRemove', callback); ## on('formRemove') - on(type: 'formRemove', bundleName: string, observerCallback: Callback<formInfo.RunningFormInfo>): void + on(type: 'formRemove', hostBundleName: string, observerCallback: Callback<formInfo.RunningFormInfo>): void 订阅卡片删除事件。使用callback异步回调,返回指定卡片使用方应用被删除卡片的[RunningFormInfo](js-apis-app-form-formInfo.md)。 @@ -169,7 +169,7 @@ formObserver.on('formRemove', bundleName, callback); ## off('formRemove') -off(type: "formRemove", bundleName?: string, observerCallback?: Callback<formInfo.RunningFormInfo>): void +off(type: "formRemove", hostBundleName?: string, observerCallback?: Callback<formInfo.RunningFormInfo>): void 取消订阅卡片删除事件。使用callback异步回调,返回当前删除卡片的[RunningFormInfo](js-apis-app-form-formInfo.md)。 @@ -234,7 +234,7 @@ formObserver.on('notifyVisible', callback); ## on('notifyVisible') - on(type: 'notifyVisible', bundleName: string, observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void + on(type: 'notifyVisible', hostBundleName: string, observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void 订阅通知卡片可见的事件。 @@ -267,7 +267,7 @@ formObserver.on('notifyVisible', bundleName, callback); ## off('notifyVisible') - off(type: "notifyVisible", bundleName?: string, observerCallback?: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void + off(type: "notifyVisible", hostBundleName?: string, observerCallback?: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void 取消订阅通知卡片可见的事件。 @@ -335,7 +335,7 @@ formObserver.on('notifyInvisible', callback); ## on('notifyInvisible') - on(type: 'notifyInvisible', bundleName: string, observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void + on(type: 'notifyInvisible', hostBundleName: string, observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void 订阅通知卡片不可见的事件。 @@ -367,7 +367,7 @@ formObserver.on('notifyInvisible', bundleName, callback); ## off('notifyInvisible') - off(type: "notifyInvisible", bundleName?: string, observerCallback?: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void + off(type: "notifyInvisible", hostBundleName?: string, observerCallback?: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void 取消订阅通知卡片不可见事件。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-appAccount.md b/zh-cn/application-dev/reference/apis/js-apis-appAccount.md index 60225153f733d87d8d485c0b86513b686ce034e4..aa6381e87eb13d41de8d53e19afd1663d67e0e8f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-appAccount.md +++ b/zh-cn/application-dev/reference/apis/js-apis-appAccount.md @@ -64,8 +64,10 @@ createAccount(name: string, callback: AsyncCallback<void>): void; **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.createAccount('WangWu', (err) => { + appAccountManager.createAccount('WangWu', (err: BusinessError) => { console.log('createAccount err: ' + JSON.stringify(err)); }); } catch (err) { @@ -101,13 +103,15 @@ createAccount(name: string, options: CreateAccountOptions, callback: AsyncCallba **示例:** ```js + import { BusinessError } from '@ohos.base'; + let options = { customData: { 'age': '10' } } try { - appAccountManager.createAccount('LiSi', options, (err) => { + appAccountManager.createAccount('LiSi', options, (err: BusinessError) => { if (err) { console.log('createAccount failed, error: ' + JSON.stringify(err)); } else { @@ -152,6 +156,8 @@ createAccount(name: string, options?: CreateAccountOptions): Promise<void> **示例:** ```js + import { BusinessError } from '@ohos.base'; + let options = { customData: { 'age': '10' @@ -160,7 +166,7 @@ createAccount(name: string, options?: CreateAccountOptions): Promise<void> try { appAccountManager.createAccount('LiSi', options).then(() => { console.log('createAccount successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('createAccount failed, error: ' + JSON.stringify(err)); }); } catch(err) { @@ -197,12 +203,15 @@ createAccountImplicitly(owner: string, callback: AuthCallback): void **示例:** ```js - function onResultCallback(code, result) { + import { BusinessError } from '@ohos.base'; + import Want from '@ohos.app.ability.Want'; + + function onResultCallback(code: number, result: account_appAccount.AuthResult) { console.log('resultCode: ' + code); console.log('result: ' + JSON.stringify(result)); } - function onRequestRedirectedCallback(request) { + function onRequestRedirectedCallback(request: Want) { let wantInfo = { deviceId: '', bundleName: 'com.example.accountjsdemo', @@ -211,7 +220,7 @@ createAccountImplicitly(owner: string, callback: AuthCallback): void } this.context.startAbility(wantInfo).then(() => { console.log('startAbility successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('startAbility err: ' + JSON.stringify(err)); }) } @@ -256,12 +265,15 @@ createAccountImplicitly(owner: string, options: CreateAccountImplicitlyOptions, **示例:** ```js - function onResultCallback(code, result) { + import { BusinessError } from '@ohos.base'; + import Want from '@ohos.app.ability.Want'; + + function onResultCallback(code: number, result: account_appAccount.AuthResult) { console.log('resultCode: ' + code); console.log('result: ' + JSON.stringify(result)); } - function onRequestRedirectedCallback(request) { + function onRequestRedirectedCallback(request: Want) { let wantInfo = { deviceId: '', bundleName: 'com.example.accountjsdemo', @@ -270,7 +282,7 @@ createAccountImplicitly(owner: string, options: CreateAccountImplicitlyOptions, } this.context.startAbility(wantInfo).then(() => { console.log('startAbility successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('startAbility err: ' + JSON.stringify(err)); }) } @@ -315,8 +327,10 @@ removeAccount(name: string, callback: AsyncCallback<void>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.removeAccount('ZhaoLiu', (err) => { + appAccountManager.removeAccount('ZhaoLiu', (err: BusinessError) => { if (err) { console.log('removeAccount failed, error: ' + JSON.stringify(err)); } else { @@ -359,10 +373,12 @@ removeAccount(name: string): Promise<void> **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { appAccountManager.removeAccount('Lisi').then(() => { console.log('removeAccount successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('removeAccount failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -399,8 +415,10 @@ setAppAccess(name: string, bundleName: string, isAccessible: boolean, callback: **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.setAppAccess('ZhangSan', 'com.example.accountjsdemo', true, (err) => { + appAccountManager.setAppAccess('ZhangSan', 'com.example.accountjsdemo', true, (err: BusinessError) => { if (err) { console.log('setAppAccess failed: ' + JSON.stringify(err)); } else { @@ -446,10 +464,12 @@ setAppAccess(name: string, bundleName: string, isAccessible: boolean): Promise&l **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { appAccountManager.setAppAccess('ZhangSan', 'com.example.accountjsdemo', true).then(() => { console.log('setAppAccess successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('setAppAccess failed: ' + JSON.stringify(err)); }); } catch (err) { @@ -484,14 +504,17 @@ checkAppAccess(name: string, bundleName: string, callback: AsyncCallback<bool **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.checkAppAccess('ZhangSan', 'com.example.accountjsdemo', (err, isAccessible) => { - if (err) { - console.log('checkAppAccess failed, error: ' + JSON.stringify(err)); - } else { - console.log('checkAppAccess successfully'); - } - }); + appAccountManager.checkAppAccess('ZhangSan', 'com.example.accountjsdemo', + (err: BusinessError, isAccessible: boolean) => { + if (err) { + console.log('checkAppAccess failed, error: ' + JSON.stringify(err)); + } else { + console.log('checkAppAccess successfully'); + } + }); } catch (err) { console.log('checkAppAccess exception: ' + JSON.stringify(err)); } @@ -529,10 +552,12 @@ checkAppAccess(name: string, bundleName: string): Promise<boolean> **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.checkAppAccess('ZhangSan', 'com.example.accountjsdemo').then((isAccessible) => { + appAccountManager.checkAppAccess('ZhangSan', 'com.example.accountjsdemo').then((isAccessible: boolean) => { console.log('checkAppAccess successfully, isAccessible: ' + isAccessible); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('checkAppAccess failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -569,8 +594,10 @@ setDataSyncEnabled(name: string, isEnabled: boolean, callback: AsyncCallback< **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.setDataSyncEnabled('ZhangSan', true, (err) => { + appAccountManager.setDataSyncEnabled('ZhangSan', true, (err: BusinessError) => { console.log('setDataSyncEnabled err: ' + JSON.stringify(err)); }); } catch (err) { @@ -612,10 +639,12 @@ setDataSyncEnabled(name: string, isEnabled: boolean): Promise<void> **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { appAccountManager .setDataSyncEnabled('ZhangSan', true).then(() => { console.log('setDataSyncEnabled Success'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('setDataSyncEnabled err: ' + JSON.stringify(err)); }); } catch (err) { @@ -651,8 +680,10 @@ checkDataSyncEnabled(name: string, callback: AsyncCallback<boolean>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.checkDataSyncEnabled('ZhangSan', (err, isEnabled) => { + appAccountManager.checkDataSyncEnabled('ZhangSan', (err: BusinessError, isEnabled: boolean) => { if (err) { console.log('checkDataSyncEnabled failed, err: ' + JSON.stringify(err)); } else { @@ -697,10 +728,12 @@ checkDataSyncEnabled(name: string): Promise<boolean> **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.checkDataSyncEnabled('ZhangSan').then((isEnabled) => { + appAccountManager.checkDataSyncEnabled('ZhangSan').then((isEnabled: boolean) => { console.log('checkDataSyncEnabled successfully, isEnabled: ' + isEnabled); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('checkDataSyncEnabled failed, err: ' + JSON.stringify(err)); }); } catch (err) { @@ -736,8 +769,10 @@ setCredential(name: string, credentialType: string, credential: string,callback: **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.setCredential('ZhangSan', 'PIN_SIX', 'xxxxxx', (err) => { + appAccountManager.setCredential('ZhangSan', 'PIN_SIX', 'xxxxxx', (err: BusinessError) => { if (err) { console.log('setCredential failed, error: ' + JSON.stringify(err)); } else { @@ -782,10 +817,12 @@ setCredential(name: string, credentialType: string, credential: string): Promise **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { appAccountManager.setCredential('ZhangSan', 'PIN_SIX', 'xxxxxx').then(() => { console.log('setCredential successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('setCredential failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -821,8 +858,10 @@ getCredential(name: string, credentialType: string, callback: AsyncCallback<s **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.getCredential('ZhangSan', 'PIN_SIX', (err, result) => { + appAccountManager.getCredential('ZhangSan', 'PIN_SIX', (err: BusinessError, result: string) => { if (err) { console.log('getCredential failed, error: ' + JSON.stringify(err)); } else { @@ -867,10 +906,12 @@ getCredential(name: string, credentialType: string): Promise<string> **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.getCredential('ZhangSan', 'PIN_SIX').then((credential) => { + appAccountManager.getCredential('ZhangSan', 'PIN_SIX').then((credential: string) => { console.log('getCredential successfully, credential: ' + credential); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getCredential failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -907,8 +948,10 @@ setCustomData(name: string, key: string, value: string, callback: AsyncCallback& **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.setCustomData('ZhangSan', 'age', '12', (err) => { + appAccountManager.setCustomData('ZhangSan', 'age', '12', (err: BusinessError) => { if (err) { console.log('setCustomData failed, error: ' + JSON.stringify(err)); } else { @@ -954,10 +997,12 @@ setCustomData(name: string, key: string, value: string): Promise<void> **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { appAccountManager.setCustomData('ZhangSan', 'age', '12').then(() => { console.log('setCustomData successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('setCustomData failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -993,8 +1038,10 @@ getCustomData(name: string, key: string, callback: AsyncCallback<string>): **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.getCustomData('ZhangSan', 'age', (err, data) => { + appAccountManager.getCustomData('ZhangSan', 'age', (err: BusinessError, data: string) => { if (err) { console.log('getCustomData failed, error: ' + err); } else { @@ -1039,10 +1086,12 @@ getCustomData(name: string, key: string): Promise<string> **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.getCustomData('ZhangSan', 'age').then((data) => { + appAccountManager.getCustomData('ZhangSan', 'age').then((data: string) => { console.log('getCustomData successfully, data: ' + data); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getCustomData failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -1114,8 +1163,10 @@ getAllAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.getAllAccounts((err, data) => { + appAccountManager.getAllAccounts((err: BusinessError, data: account_appAccount.AppAccountInfo[]) => { if (err) { console.debug('getAllAccounts failed, error: ' + JSON.stringify(err)); } else { @@ -1150,10 +1201,12 @@ getAllAccounts(): Promise<Array<AppAccountInfo>> **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.getAllAccounts().then((data) => { + appAccountManager.getAllAccounts().then((data: account_appAccount.AppAccountInfo[]) => { console.debug('getAllAccounts successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.debug('getAllAccounts failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -1187,14 +1240,17 @@ getAccountsByOwner(owner: string, callback: AsyncCallback<Array<AppAccount **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.getAccountsByOwner('com.example.accountjsdemo2', (err, data) => { - if (err) { - console.debug('getAccountsByOwner failed, error:' + JSON.stringify(err)); - } else { - console.debug('getAccountsByOwner successfully, data:' + JSON.stringify(data)); - } - }); + appAccountManager.getAccountsByOwner('com.example.accountjsdemo2', + (err: BusinessError, data: account_appAccount.AppAccountInfo[]) => { + if (err) { + console.debug('getAccountsByOwner failed, error:' + JSON.stringify(err)); + } else { + console.debug('getAccountsByOwner successfully, data:' + JSON.stringify(data)); + } + }); } catch (err) { console.debug('getAccountsByOwner exception:' + JSON.stringify(err)); } @@ -1231,10 +1287,13 @@ getAccountsByOwner(owner: string): Promise<Array<AppAccountInfo>> **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.getAccountsByOwner('com.example.accountjsdemo2').then((data) => { + appAccountManager.getAccountsByOwner('com.example.accountjsdemo2').then(( + data: account_appAccount.AppAccountInfo[]) => { console.debug('getAccountsByOwner successfully, data: ' + JSON.stringify(data)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.debug('getAccountsByOwner failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -1269,7 +1328,7 @@ on(type: 'accountChange', owners: Array<string>, callback: Callback<Arr **示例:** ```js - function changeOnCallback(data){ + function changeOnCallback(data: account_appAccount.AppAccountInfo[]){ console.log('receive change data:' + JSON.stringify(data)); } try{ @@ -1304,7 +1363,7 @@ off(type: 'accountChange', callback?: Callback<Array<AppAccountInfo>> **示例:** ```js - function changeOnCallback(data) { + function changeOnCallback(data: account_appAccount.AppAccountInfo[]) { console.log('receive change data:' + JSON.stringify(data)); } try{ @@ -1351,14 +1410,15 @@ auth(name: string, owner: string, authType: string, callback: AuthCallback): voi **示例:** ```js + import { BusinessError } from '@ohos.base'; + import Want from '@ohos.app.ability.Want'; - - function onResultCallback(code, authResult) { + function onResultCallback(code: number, authResult: account_appAccount.AuthResult) { console.log('resultCode: ' + code); console.log('authResult: ' + JSON.stringify(authResult)); } - function onRequestRedirectedCallback(request) { + function onRequestRedirectedCallback(request: Want) { let wantInfo = { deviceId: '', bundleName: 'com.example.accountjsdemo', @@ -1367,7 +1427,7 @@ auth(name: string, owner: string, authType: string, callback: AuthCallback): voi } this.context.startAbility(wantInfo).then(() => { console.log('startAbility successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('startAbility err: ' + JSON.stringify(err)); }) } @@ -1414,14 +1474,15 @@ auth(name: string, owner: string, authType: string, options: {[key: string]: Obj **示例:** ```js + import { BusinessError } from '@ohos.base'; + import Want from '@ohos.app.ability.Want'; - - function onResultCallback(code, authResult) { + function onResultCallback(code: number, authResult: account_appAccount.AuthResult) { console.log('resultCode: ' + code); console.log('authResult: ' + JSON.stringify(authResult)); } - function onRequestRedirectedCallback(request) { + function onRequestRedirectedCallback(request: Want) { let wantInfo = { deviceId: '', bundleName: 'com.example.accountjsdemo', @@ -1430,7 +1491,7 @@ auth(name: string, owner: string, authType: string, options: {[key: string]: Obj } this.context.startAbility(wantInfo).then(() => { console.log('startAbility successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('startAbility err: ' + JSON.stringify(err)); }) } @@ -1477,14 +1538,17 @@ getAuthToken(name: string, owner: string, authType: string, callback: AsyncCallb **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.getAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', (err, token) => { - if (err) { - console.log('getAuthToken failed, error: ' + JSON.stringify(err)); - } else { - console.log('getAuthToken successfully, token: ' + token); - } - }); + appAccountManager.getAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', + (err: BusinessError, token: string) => { + if (err) { + console.log('getAuthToken failed, error: ' + JSON.stringify(err)); + } else { + console.log('getAuthToken successfully, token: ' + token); + } + }); } catch (err) { console.log('getAuthToken exception: ' + JSON.stringify(err)); } @@ -1524,10 +1588,12 @@ getAuthToken(name: string, owner: string, authType: string): Promise<string&g **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.getAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData').then((token) => { + appAccountManager.getAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData').then((token: string) => { console.log('getAuthToken successfully, token: ' + token); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getAuthToken failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -1564,8 +1630,10 @@ setAuthToken(name: string, authType: string, token: string, callback: AsyncCallb **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.setAuthToken('LiSi', 'getSocialData', 'xxxx', (err) => { + appAccountManager.setAuthToken('LiSi', 'getSocialData', 'xxxx', (err: BusinessError) => { if (err) { console.log('setAuthToken failed, error: ' + JSON.stringify(err)); } else { @@ -1573,7 +1641,7 @@ setAuthToken(name: string, authType: string, token: string, callback: AsyncCallb } }); } catch (err) { - console.log('setAuthToken exception: ' + JSON.stringify(err)); + console.log('setAuthToken exception: ' + JSON.stringify(err)); } ``` @@ -1611,10 +1679,12 @@ setAuthToken(name: string, authType: string, token: string): Promise<void> **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { appAccountManager.setAuthToken('LiSi', 'getSocialData', 'xxxx').then(() => { console.log('setAuthToken successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('setAuthToken failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -1652,8 +1722,11 @@ deleteAuthToken(name: string, owner: string, authType: string, token: string, ca **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.deleteAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx', (err) => { + appAccountManager.deleteAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx', + (err: BusinessError) => { if (err) { console.log('deleteAuthToken failed, error: ' + JSON.stringify(err)); } else { @@ -1661,7 +1734,7 @@ deleteAuthToken(name: string, owner: string, authType: string, token: string, ca } }); } catch (err) { - console.log('deleteAuthToken exception: ' + JSON.stringify(err)); + console.log('deleteAuthToken exception: ' + JSON.stringify(err)); } ``` @@ -1700,10 +1773,12 @@ deleteAuthToken(name: string, owner: string, authType: string, token: string): P **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { appAccountManager.deleteAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx').then(() => { console.log('deleteAuthToken successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('deleteAuthToken failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -1743,8 +1818,11 @@ setAuthTokenVisibility(name: string, authType: string, bundleName: string, isVis **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.setAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true, (err) => { + appAccountManager.setAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true, + (err: BusinessError) => { if (err) { console.log('setAuthTokenVisibility failed, error: ' + JSON.stringify(err)); } else { @@ -1793,10 +1871,12 @@ setAuthTokenVisibility(name: string, authType: string, bundleName: string, isVis **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { appAccountManager.setAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true).then(() => { console.log('setAuthTokenVisibility successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('setAuthTokenVisibility failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -1833,14 +1913,17 @@ checkAuthTokenVisibility(name: string, authType: string, bundleName: string, cal **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.checkAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', (err, isVisible) => { - if (err) { - console.log('checkAuthTokenVisibility failed, error: ' + JSON.stringify(err)); - } else { - console.log('checkAuthTokenVisibility successfully, isVisible: ' + isVisible); - } - }); + appAccountManager.checkAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', + (err: BusinessError, isVisible: boolean) => { + if (err) { + console.log('checkAuthTokenVisibility failed, error: ' + JSON.stringify(err)); + } else { + console.log('checkAuthTokenVisibility successfully, isVisible: ' + isVisible); + } + }); } catch (err) { console.log('checkAuthTokenVisibility exception: ' + JSON.stringify(err)); } @@ -1880,10 +1963,13 @@ checkAuthTokenVisibility(name: string, authType: string, bundleName: string): Pr **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.checkAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo').then((isVisible) => { + appAccountManager.checkAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo').then(( + isVisible: boolean) => { console.log('checkAuthTokenVisibility successfully, isVisible: ' + isVisible); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('checkAuthTokenVisibility failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -1918,14 +2004,17 @@ getAllAuthTokens(name: string, owner: string, callback: AsyncCallback<Array&l **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.getAllAuthTokens('LiSi', 'com.example.accountjsdemo', (err, tokenArr) => { - if (err) { - console.log('getAllAuthTokens failed, error: ' + JSON.stringify(err)); - } else { - console.log('getAllAuthTokens successfully, tokenArr: ' + tokenArr); - } - }); + appAccountManager.getAllAuthTokens('LiSi', 'com.example.accountjsdemo', + (err: BusinessError, tokenArr: account_appAccount.AuthTokenInfo[]) => { + if (err) { + console.log('getAllAuthTokens failed, error: ' + JSON.stringify(err)); + } else { + console.log('getAllAuthTokens successfully, tokenArr: ' + tokenArr); + } + }); } catch (err) { console.log('getAllAuthTokens exception: ' + JSON.stringify(err)); } @@ -1963,11 +2052,14 @@ getAllAuthTokens(name: string, owner: string): Promise<Array<AuthTokenInfo **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.getAllAuthTokens('LiSi', 'com.example.accountjsdemo').then((tokenArr) => { - console.log('getAllAuthTokens successfully, tokenArr: ' + JSON.stringify(tokenArr)); - }).catch((err) => { - console.log('getAllAuthTokens failed, error: ' + JSON.stringify(err)); + appAccountManager.getAllAuthTokens('LiSi', 'com.example.accountjsdemo').then(( + tokenArr: account_appAccount.AuthTokenInfo[]) => { + console.log('getAllAuthTokens successfully, tokenArr: ' + JSON.stringify(tokenArr)); + }).catch((err: BusinessError) => { + console.log('getAllAuthTokens failed, error: ' + JSON.stringify(err)); }); } catch (err) { console.log('getAllAuthTokens exception: ' + JSON.stringify(err)); @@ -2002,8 +2094,10 @@ getAuthList(name: string, authType: string, callback: AsyncCallback<Array< **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.getAuthList('LiSi', 'getSocialData', (err, authList) => { + appAccountManager.getAuthList('LiSi', 'getSocialData', (err: BusinessError, authList: string[]) => { if (err) { console.log('getAuthList failed, error: ' + JSON.stringify(err)); } else { @@ -2048,10 +2142,12 @@ getAuthList(name: string, authType: string): Promise<Array<string>> **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.getAuthList('LiSi', 'getSocialData').then((authList) => { + appAccountManager.getAuthList('LiSi', 'getSocialData').then((authList: string[]) => { console.log('getAuthList successfully, authList: ' + authList); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getAuthList failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -2085,18 +2181,21 @@ getAuthCallback(sessionId: string, callback: AsyncCallback<AuthCallback>): **示例:** ```js + import { BusinessError } from '@ohos.base'; import UIAbility from '@ohos.app.ability.UIAbility'; + import Want from '@ohos.app.ability.Want'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; export default class EntryAbility extends UIAbility { - onCreate(want, param) { - var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; + onCreate(want: Want, param: AbilityConstant.LaunchParam) { + let sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; try { - appAccountManager.getAuthCallback(sessionId, (err, callback) => { + appAccountManager.getAuthCallback(sessionId, (err: BusinessError, callback: account_appAccount.AuthCallback) => { if (err != null) { console.log('getAuthCallback err: ' + JSON.stringify(err)); return; } - var result = { + let result = { accountInfo: { name: 'Lisi', owner: 'com.example.accountjsdemo', @@ -2146,14 +2245,17 @@ getAuthCallback(sessionId: string): Promise<AuthCallback> **示例:** ```js + import { BusinessError } from '@ohos.base'; import UIAbility from '@ohos.app.ability.UIAbility'; + import Want from '@ohos.app.ability.Want'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; export default class EntryAbility extends UIAbility { - onCreate(want, param) { - var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; + onCreate(want: Want, param: AbilityConstant.LaunchParam) { + let sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; try { - appAccountManager.getAuthCallback(sessionId).then((callback) => { - var result = { + appAccountManager.getAuthCallback(sessionId).then((callback: account_appAccount.AuthCallback) => { + let result = { accountInfo: { name: 'Lisi', owner: 'com.example.accountjsdemo', @@ -2164,7 +2266,7 @@ getAuthCallback(sessionId: string): Promise<AuthCallback> } }; callback.onResult(0, result); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getAuthCallback err: ' + JSON.stringify(err)); }); } catch (err) { @@ -2200,14 +2302,17 @@ queryAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorIn **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.queryAuthenticatorInfo('com.example.accountjsdemo', (err, info) => { - if (err) { - console.log('queryAuthenticatorInfo failed, error: ' + JSON.stringify(err)); - } else { - console.log('queryAuthenticatorInfo successfully, info: ' + JSON.stringify(info)); - } - }); + appAccountManager.queryAuthenticatorInfo('com.example.accountjsdemo', + (err: BusinessError, info: account_appAccount.AuthenticatorInfo) => { + if (err) { + console.log('queryAuthenticatorInfo failed, error: ' + JSON.stringify(err)); + } else { + console.log('queryAuthenticatorInfo successfully, info: ' + JSON.stringify(info)); + } + }); } catch (err) { console.log('queryAuthenticatorInfo exception: ' + JSON.stringify(err)); } @@ -2244,11 +2349,14 @@ queryAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.queryAuthenticatorInfo('com.example.accountjsdemo').then((info) => { - console.log('queryAuthenticatorInfo successfully, info: ' + JSON.stringify(info)); - }).catch((err) => { - console.log('queryAuthenticatorInfo failed, error: ' + JSON.stringify(err)); + appAccountManager.queryAuthenticatorInfo('com.example.accountjsdemo').then(( + info: account_appAccount.AuthenticatorInfo) => { + console.log('queryAuthenticatorInfo successfully, info: ' + JSON.stringify(info)); + }).catch((err: BusinessError) => { + console.log('queryAuthenticatorInfo failed, error: ' + JSON.stringify(err)); }); } catch (err) { console.log('queryAuthenticatorInfo exception: ' + JSON.stringify(err)); @@ -2286,15 +2394,18 @@ checkAccountLabels(name: string, owner: string, labels: Array<string>, cal **示例:** ```js + import { BusinessError } from '@ohos.base'; + let labels = ['student']; try { - appAccountManager.checkAccountLabels('zhangsan', 'com.example.accountjsdemo', labels, (err, hasAllLabels) => { - if (err) { - console.log('checkAccountLabels failed, error: ' + JSON.stringify(err)); - } else { - console.log('checkAccountLabels successfully, hasAllLabels: ' + hasAllLabels); - } - }); + appAccountManager.checkAccountLabels('zhangsan', 'com.example.accountjsdemo', labels1, + (err: BusinessError, hasAllLabels: boolean) => { + if (err) { + console.log('checkAccountLabels failed, error: ' + JSON.stringify(err)); + } else { + console.log('checkAccountLabels successfully, hasAllLabels: ' + hasAllLabels); + } + }); } catch (err) { console.log('checkAccountLabels exception: ' + JSON.stringify(err)); } @@ -2336,11 +2447,14 @@ checkAccountLabels(name: string, owner: string, labels: Array<string>): Pr **示例:** ```js + import { BusinessError } from '@ohos.base'; + let labels = ['student']; try { - appAccountManager.checkAccountLabels('zhangsan', 'com.example.accountjsdemo', labels).then((hasAllLabels) => { + appAccountManager.checkAccountLabels('zhangsan', 'com.example.accountjsdemo', labels).then(( + hasAllLabels: boolean) => { console.log('checkAccountLabels successfully: ' + hasAllLabels); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('checkAccountLabels failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -2376,8 +2490,10 @@ deleteCredential(name: string, credentialType: string, callback: AsyncCallback&l **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { - appAccountManager.deleteCredential('zhangsan', 'PIN_SIX', (err) => { + appAccountManager.deleteCredential('zhangsan', 'PIN_SIX', (err: BusinessError) => { if (err) { console.log('deleteCredential failed, error: ' + JSON.stringify(err)); } else { @@ -2422,10 +2538,12 @@ deleteCredential(name: string, credentialType: string): Promise<void> **示例:** ```js + import { BusinessError } from '@ohos.base'; + try { appAccountManager.deleteCredential('zhangsan', 'PIN_SIX').then(() => { console.log('deleteCredential successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('deleteCredential failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -2460,18 +2578,21 @@ selectAccountsByOptions(options: SelectAccountsOptions, callback: AsyncCallback& **示例:** ```js + import { BusinessError } from '@ohos.base'; + let options = { allowedOwners: [ 'com.example.accountjsdemo' ], requiredLabels: [ 'student' ] }; try { - appAccountManager.selectAccountsByOptions(options, (err, accountArr) => { - if (err) { - console.log('selectAccountsByOptions failed, error: ' + JSON.stringify(err)); - } else { - console.log('selectAccountsByOptions successfully, accountArr: ' + JSON.stringify(accountArr)); - } - }); + appAccountManager.selectAccountsByOptions(options5, + (err: BusinessError, accountArr: account_appAccount.AppAccountInfo[]) => { + if (err) { + console.log('selectAccountsByOptions failed, error: ' + JSON.stringify(err)); + } else { + console.log('selectAccountsByOptions successfully, accountArr: ' + JSON.stringify(accountArr)); + } + }); } catch (err) { console.log('selectAccountsByOptions exception: ' + JSON.stringify(err)); } @@ -2509,13 +2630,15 @@ selectAccountsByOptions(options: SelectAccountsOptions): Promise<Array<App **示例:** ```js + import { BusinessError } from '@ohos.base'; + let options = { allowedOwners: ['com.example.accountjsdemo'] }; try { - appAccountManager.selectAccountsByOptions(options).then((accountArr) => { + appAccountManager.selectAccountsByOptions(options).then((accountArr: account_appAccount.AppAccountInfo[]) => { console.log('selectAccountsByOptions successfully, accountArr: ' + JSON.stringify(accountArr)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('selectAccountsByOptions failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -2553,13 +2676,15 @@ verifyCredential(name: string, owner: string, callback: AuthCallback): void; **示例:** ```js + import Want from '@ohos.app.ability.Want'; + try { appAccountManager.verifyCredential('zhangsan', 'com.example.accountjsdemo', { - onResult: (resultCode, result) => { + onResult: (resultCode: number, result: account_appAccount.AuthResult) => { console.log('verifyCredential onResult, resultCode: ' + JSON.stringify(resultCode)); console.log('verifyCredential onResult, result: ' + JSON.stringify(result)); }, - onRequestRedirected: (request) => { + onRequestRedirected: (request: Want) => { console.log('verifyCredential onRequestRedirected, request: ' + JSON.stringify(request)); } }); @@ -2599,17 +2724,19 @@ verifyCredential(name: string, owner: string, options: VerifyCredentialOptions, **示例:** ```js + import Want from '@ohos.app.ability.Want'; + let options = { credentialType: 'pin', credential: '123456' }; try { appAccountManager.verifyCredential('zhangsan', 'com.example.accountjsdemo', options, { - onResult: (resultCode, result) => { + onResult: (resultCode: number, result: account_appAccount.AuthResult) => { console.log('verifyCredential onResult, resultCode: ' + JSON.stringify(resultCode)); console.log('verifyCredential onResult, result: ' + JSON.stringify(result)); }, - onRequestRedirected: (request) => { + onRequestRedirected: (request: Want) => { console.log('verifyCredential onRequestRedirected, request: ' + JSON.stringify(request)); } }); @@ -2646,13 +2773,15 @@ setAuthenticatorProperties(owner: string, callback: AuthCallback): void; **示例:** ```js + import Want from '@ohos.app.ability.Want'; + try { appAccountManager.setAuthenticatorProperties('com.example.accountjsdemo', { - onResult: (resultCode, result) => { + onResult: (resultCode: number, result: account_appAccount.AuthResult) => { console.log('setAuthenticatorProperties onResult, resultCode: ' + JSON.stringify(resultCode)); console.log('setAuthenticatorProperties onResult, result: ' + JSON.stringify(result)); }, - onRequestRedirected: (request) => { + onRequestRedirected: (request: Want) => { console.log('setAuthenticatorProperties onRequestRedirected, request: ' + JSON.stringify(request)); } }); @@ -2690,16 +2819,18 @@ setAuthenticatorProperties(owner: string, options: SetPropertiesOptions, callbac **示例:** ```js + import Want from '@ohos.app.ability.Want'; + let options = { properties: {'prop1': 'value1'} }; try { appAccountManager.setAuthenticatorProperties('com.example.accountjsdemo', options, { - onResult: (resultCode, result) => { + onResult: (resultCode: number, result: account_appAccount.AuthResult) => { console.log('setAuthenticatorProperties onResult, resultCode: ' + JSON.stringify(resultCode)); console.log('setAuthenticatorProperties onResult, result: ' + JSON.stringify(result)); }, - onRequestRedirected: (request) => { + onRequestRedirected: (request: Want) => { console.log('setAuthenticatorProperties onRequestRedirected, request: ' + JSON.stringify(request)); } }); @@ -2732,7 +2863,9 @@ addAccount(name: string, callback: AsyncCallback<void>): void **示例:** ```js - appAccountManager.addAccount('WangWu', (err) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.addAccount('WangWu', (err: BusinessError) => { console.log('addAccount err: ' + JSON.stringify(err)); }); ``` @@ -2759,7 +2892,9 @@ addAccount(name: string, extraInfo: string, callback: AsyncCallback<void>) **示例:** ```js - appAccountManager.addAccount('LiSi', 'token101', (err) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.addAccount('LiSi', 'token101', (err: BusinessError) => { console.log('addAccount err: ' + JSON.stringify(err)); }); ``` @@ -2791,9 +2926,11 @@ addAccount(name: string, extraInfo?: string): Promise<void> **示例:** ```js + import { BusinessError } from '@ohos.base'; + appAccountManager.addAccount('LiSi', 'token101').then(()=> { console.log('addAccount Success'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('addAccount err: ' + JSON.stringify(err)); }); ``` @@ -2822,14 +2959,15 @@ addAccountImplicitly(owner: string, authType: string, options: {[key: string]: a **示例:** ```js + import { BusinessError } from '@ohos.base'; + import Want from '@ohos.app.ability.Want'; - - function onResultCallback(code, result) { + function onResultCallback(code: number, result: { [key: string]: any }) { console.log('resultCode: ' + code); console.log('result: ' + JSON.stringify(result)); } - function onRequestRedirectedCallback(request) { + function onRequestRedirectedCallback(request: Want) { let wantInfo = { deviceId: '', bundleName: 'com.example.accountjsdemo', @@ -2838,7 +2976,7 @@ addAccountImplicitly(owner: string, authType: string, options: {[key: string]: a } this.context.startAbility(wantInfo).then(() => { console.log('startAbility successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('startAbility err: ' + JSON.stringify(err)); }) } @@ -2871,7 +3009,9 @@ deleteAccount(name: string, callback: AsyncCallback<void>): void **示例:** ```js - appAccountManager.deleteAccount('ZhaoLiu', (err) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.deleteAccount('ZhaoLiu', (err: BusinessError) => { console.log('deleteAccount err: ' + JSON.stringify(err)); }); ``` @@ -2903,9 +3043,11 @@ deleteAccount(name: string): Promise<void> **示例:** ```js + import { BusinessError } from '@ohos.base'; + appAccountManager.deleteAccount('ZhaoLiu').then(() => { console.log('deleteAccount Success'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('deleteAccount err: ' + JSON.stringify(err)); }); ``` @@ -2932,7 +3074,9 @@ disableAppAccess(name: string, bundleName: string, callback: AsyncCallback<vo **示例:** ```js - appAccountManager.disableAppAccess('ZhangSan', 'com.example.accountjsdemo', (err) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.disableAppAccess('ZhangSan', 'com.example.accountjsdemo', (err: BusinessError) => { console.log('disableAppAccess err: ' + JSON.stringify(err)); }); ``` @@ -2965,9 +3109,11 @@ disableAppAccess(name: string, bundleName: string): Promise<void> **示例:** ```js + import { BusinessError } from '@ohos.base'; + appAccountManager.disableAppAccess('ZhangSan', 'com.example.accountjsdemo').then(() => { console.log('disableAppAccess Success'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('disableAppAccess err: ' + JSON.stringify(err)); }); ``` @@ -2995,7 +3141,9 @@ enableAppAccess(name: string, bundleName: string, callback: AsyncCallback<voi **示例:** ```js - appAccountManager.enableAppAccess('ZhangSan', 'com.example.accountjsdemo', (err) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.enableAppAccess('ZhangSan', 'com.example.accountjsdemo', (err: BusinessError) => { console.log('enableAppAccess: ' + JSON.stringify(err)); }); ``` @@ -3028,9 +3176,11 @@ enableAppAccess(name: string, bundleName: string): Promise<void> **示例:** ```js + import { BusinessError } from '@ohos.base'; + appAccountManager.enableAppAccess('ZhangSan', 'com.example.accountjsdemo').then(() => { console.log('enableAppAccess Success'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('enableAppAccess err: ' + JSON.stringify(err)); }); ``` @@ -3059,7 +3209,9 @@ checkAppAccountSyncEnable(name: string, callback: AsyncCallback<boolean>): **示例:** ```js - appAccountManager.checkAppAccountSyncEnable('ZhangSan', (err, result) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.checkAppAccountSyncEnable('ZhangSan', (err: BusinessError, result: boolean) => { console.log('checkAppAccountSyncEnable err: ' + JSON.stringify(err)); console.log('checkAppAccountSyncEnable result: ' + result); }); @@ -3094,9 +3246,11 @@ checkAppAccountSyncEnable(name: string): Promise<boolean> **示例:** ```js - appAccountManager.checkAppAccountSyncEnable('ZhangSan').then((data) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.checkAppAccountSyncEnable('ZhangSan').then((data: boolean) => { console.log('checkAppAccountSyncEnable, result: ' + data); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('checkAppAccountSyncEnable err: ' + JSON.stringify(err)); }); ``` @@ -3125,7 +3279,9 @@ setAccountCredential(name: string, credentialType: string, credential: string,ca **示例:** ```js - appAccountManager.setAccountCredential('ZhangSan', 'credentialType001', 'credential001', (err) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.setAccountCredential('ZhangSan', 'credentialType001', 'credential001', (err: BusinessError) => { console.log('setAccountCredential err: ' + JSON.stringify(err)); }); ``` @@ -3159,9 +3315,11 @@ setAccountCredential(name: string, credentialType: string, credential: string): **示例:** ```js + import { BusinessError } from '@ohos.base'; + appAccountManager.setAccountCredential('ZhangSan', 'credentialType001', 'credential001').then(() => { console.log('setAccountCredential Success'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('setAccountCredential err: ' + JSON.stringify(err)); }); ``` @@ -3190,7 +3348,9 @@ setAccountExtraInfo(name: string, extraInfo: string, callback: AsyncCallback< **示例:** ```js - appAccountManager.setAccountExtraInfo('ZhangSan', 'Tk002', (err) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.setAccountExtraInfo('ZhangSan', 'Tk002', (err: BusinessError) => { console.log('setAccountExtraInfo err: ' + JSON.stringify(err)); }); ``` @@ -3224,9 +3384,11 @@ setAccountExtraInfo(name: string, extraInfo: string): Promise<void> **示例:** ```js + import { BusinessError } from '@ohos.base'; + appAccountManager.setAccountExtraInfo('ZhangSan', 'Tk002').then(() => { console.log('setAccountExtraInfo Success'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('setAccountExtraInfo err: ' + JSON.stringify(err)); }); ``` @@ -3256,7 +3418,9 @@ setAppAccountSyncEnable(name: string, isEnable: boolean, callback: AsyncCallback **示例:** ```js - appAccountManager.setAppAccountSyncEnable('ZhangSan', true, (err) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.setAppAccountSyncEnable('ZhangSan', true, (err: BusinessError) => { console.log('setAppAccountSyncEnable err: ' + JSON.stringify(err)); }); ``` @@ -3291,9 +3455,11 @@ setAppAccountSyncEnable(name: string, isEnable: boolean): Promise<void> **示例:** ```js + import { BusinessError } from '@ohos.base'; + appAccountManager .setAppAccountSyncEnable('ZhangSan', true).then(() => { console.log('setAppAccountSyncEnable Success'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('setAppAccountSyncEnable err: ' + JSON.stringify(err)); }); ``` @@ -3323,7 +3489,9 @@ setAssociatedData(name: string, key: string, value: string, callback: AsyncCallb **示例:** ```js - appAccountManager.setAssociatedData('ZhangSan', 'k001', 'v001', (err) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.setAssociatedData('ZhangSan', 'k001', 'v001', (err: BusinessError) => { console.log('setAssociatedData err: ' + JSON.stringify(err)); }); ``` @@ -3358,9 +3526,11 @@ setAssociatedData(name: string, key: string, value: string): Promise<void> **示例:** ```js + import { BusinessError } from '@ohos.base'; + appAccountManager.setAssociatedData('ZhangSan', 'k001', 'v001').then(() => { console.log('setAssociatedData Success'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('setAssociatedData err: ' + JSON.stringify(err)); }); ``` @@ -3388,7 +3558,9 @@ getAllAccessibleAccounts(callback: AsyncCallback<Array<AppAccountInfo>& **示例:** ```js - appAccountManager.getAllAccessibleAccounts((err, data)=>{ + import { BusinessError } from '@ohos.base'; + + appAccountManager.getAllAccessibleAccounts((err: BusinessError, data: account_appAccount.AppAccountInfo[])=>{ console.debug('getAllAccessibleAccounts err: ' + JSON.stringify(err)); console.debug('getAllAccessibleAccounts data: ' + JSON.stringify(data)); }); @@ -3417,9 +3589,11 @@ getAllAccessibleAccounts(): Promise<Array<AppAccountInfo>> **示例:** ```js - appAccountManager.getAllAccessibleAccounts().then((data) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.getAllAccessibleAccounts().then((data: account_appAccount.AppAccountInfo[]) => { console.log('getAllAccessibleAccounts: ' + data); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getAllAccessibleAccounts err: ' + JSON.stringify(err)); }); ``` @@ -3448,8 +3622,10 @@ getAllAccounts(owner: string, callback: AsyncCallback<Array<AppAccountInfo **示例:** ```js + import { BusinessError } from '@ohos.base'; + const selfBundle = 'com.example.actsgetallaaccounts'; - appAccountManager.getAllAccounts(selfBundle, (err, data)=>{ + appAccountManager.getAllAccounts(selfBundle, (err: BusinessError, data: account_appAccount.AppAccountInfo[])=>{ console.debug('getAllAccounts err: ' + JSON.stringify(err)); console.debug('getAllAccounts data:' + JSON.stringify(data)); }); @@ -3484,10 +3660,12 @@ getAllAccounts(owner: string): Promise<Array<AppAccountInfo>> **示例:** ```js + import { BusinessError } from '@ohos.base'; + const selfBundle = 'com.example.actsgetallaaccounts'; - appAccountManager.getAllAccounts(selfBundle).then((data) => { + appAccountManager.getAllAccounts(selfBundle).then((data: account_appAccount.AppAccountInfo[]) => { console.log('getAllAccounts: ' + data); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getAllAccounts err: ' + JSON.stringify(err)); }); ``` @@ -3515,7 +3693,9 @@ getAccountCredential(name: string, credentialType: string, callback: AsyncCallba **示例:** ```js - appAccountManager.getAccountCredential('ZhangSan', 'credentialType001', (err, result) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.getAccountCredential('ZhangSan', 'credentialType001', (err: BusinessError, result: string) => { console.log('getAccountCredential err: ' + JSON.stringify(err)); console.log('getAccountCredential result: ' + result); }); @@ -3549,9 +3729,11 @@ getAccountCredential(name: string, credentialType: string): Promise<string> **示例:** ```js - appAccountManager.getAccountCredential('ZhangSan', 'credentialType001').then((data) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.getAccountCredential('ZhangSan', 'credentialType001').then((data: string) => { console.log('getAccountCredential, result: ' + data); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getAccountCredential err: ' + JSON.stringify(err)); }); ``` @@ -3578,7 +3760,9 @@ getAccountExtraInfo(name: string, callback: AsyncCallback<string>): void **示例:** ```js - appAccountManager.getAccountExtraInfo('ZhangSan', (err, result) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.getAccountExtraInfo('ZhangSan', (err: BusinessError, result: string) => { console.log('getAccountExtraInfo err: ' + JSON.stringify(err)); console.log('getAccountExtraInfo result: ' + result); }); @@ -3611,9 +3795,11 @@ getAccountExtraInfo(name: string): Promise<string> **示例:** ```js - appAccountManager.getAccountExtraInfo('ZhangSan').then((data) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.getAccountExtraInfo('ZhangSan').then((data: string) => { console.log('getAccountExtraInfo, result: ' + data); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getAccountExtraInfo err: ' + JSON.stringify(err)); }); ``` @@ -3641,7 +3827,9 @@ getAssociatedData(name: string, key: string, callback: AsyncCallback<string&g **示例:** ```js - appAccountManager.getAssociatedData('ZhangSan', 'k001', (err, result) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.getAssociatedData('ZhangSan', 'k001', (err: BusinessError, result: string) => { console.log('getAssociatedData err: ' + JSON.stringify(err)); console.log('getAssociatedData result: ' + result); }); @@ -3675,9 +3863,11 @@ getAssociatedData(name: string, key: string): Promise<string> **示例:** ```js - appAccountManager.getAssociatedData('ZhangSan', 'k001').then((data) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.getAssociatedData('ZhangSan', 'k001').then((data: string) => { console.log('getAssociatedData: ' + data); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getAssociatedData err: ' + JSON.stringify(err)); }); ``` @@ -3705,7 +3895,7 @@ on(type: 'change', owners: Array<string>, callback: Callback<Array<A **示例:** ```js - function changeOnCallback(data){ + function changeOnCallback(data: account_appAccount.AppAccountInfo[]){ console.debug('receive change data:' + JSON.stringify(data)); } try{ @@ -3738,9 +3928,9 @@ off(type: 'change', callback?: Callback<Array<AppAccountInfo>>): voi **示例:** ```js - function changeOnCallback(data){ + function changeOnCallback(data: account_appAccount.AppAccountInfo[]){ console.debug('receive change data: ' + JSON.stringify(data)); - appAccountManager.off('change', function(){ + appAccountManager.off('change', () => { console.debug('off finish'); }) } @@ -3777,12 +3967,15 @@ authenticate(name: string, owner: string, authType: string, options: {[key: stri **示例:** ```js - function onResultCallback(code, result) { + import { BusinessError } from '@ohos.base'; + import Want from '@ohos.app.ability.Want'; + + function onResultCallback(code: number, result: { [key: string]: Object }) { console.log('resultCode: ' + code); console.log('result: ' + JSON.stringify(result)); } - function onRequestRedirectedCallback(request) { + function onRequestRedirectedCallback(request: Want) { let wantInfo = { deviceId: '', bundleName: 'com.example.accountjsdemo', @@ -3791,7 +3984,7 @@ authenticate(name: string, owner: string, authType: string, options: {[key: stri } this.context.startAbility(wantInfo).then(() => { console.log('startAbility successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('startAbility err: ' + JSON.stringify(err)); }) } @@ -3826,10 +4019,13 @@ getOAuthToken(name: string, owner: string, authType: string, callback: AsyncCall **示例:** ```js - appAccountManager.getOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', (err, data) => { - console.log('getOAuthToken err: ' + JSON.stringify(err)); - console.log('getOAuthToken token: ' + data); - }); + import { BusinessError } from '@ohos.base'; + + appAccountManager.getOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', + (err: BusinessError, data: string) => { + console.log('getOAuthToken err: ' + JSON.stringify(err)); + console.log('getOAuthToken token: ' + data); + }); ``` ### getOAuthToken(deprecated) @@ -3861,9 +4057,11 @@ getOAuthToken(name: string, owner: string, authType: string): Promise<string& **示例:** ```js - appAccountManager.getOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData').then((data) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.getOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData').then((data: string) => { console.log('getOAuthToken token: ' + data); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getOAuthToken err: ' + JSON.stringify(err)); }); ``` @@ -3892,7 +4090,9 @@ setOAuthToken(name: string, authType: string, token: string, callback: AsyncCall **示例:** ```js - appAccountManager.setOAuthToken('LiSi', 'getSocialData', 'xxxx', (err) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.setOAuthToken('LiSi', 'getSocialData', 'xxxx', (err: BusinessError) => { console.log('setOAuthToken err: ' + JSON.stringify(err)); }); ``` @@ -3926,9 +4126,11 @@ setOAuthToken(name: string, authType: string, token: string): Promise<void> **示例:** ```js + import { BusinessError } from '@ohos.base'; + appAccountManager.setOAuthToken('LiSi', 'getSocialData', 'xxxx').then(() => { console.log('setOAuthToken successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('setOAuthToken err: ' + JSON.stringify(err)); }); ``` @@ -3958,9 +4160,12 @@ deleteOAuthToken(name: string, owner: string, authType: string, token: string, c **示例:** ```js - appAccountManager.deleteOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx', (err) => { - console.log('deleteOAuthToken err: ' + JSON.stringify(err)); - }); + import { BusinessError } from '@ohos.base'; + + appAccountManager.deleteOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx', + (err: BusinessError) => { + console.log('deleteOAuthToken err: ' + JSON.stringify(err)); + }); ``` ### deleteOAuthToken(deprecated) @@ -3993,9 +4198,11 @@ deleteOAuthToken(name: string, owner: string, authType: string, token: string): **示例:** ```js + import { BusinessError } from '@ohos.base'; + appAccountManager.deleteOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx').then(() => { console.log('deleteOAuthToken successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('deleteOAuthToken err: ' + JSON.stringify(err)); }); ``` @@ -4025,9 +4232,12 @@ setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVi **示例:** ```js - appAccountManager.setOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true, (err) => { - console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); - }); + import { BusinessError } from '@ohos.base'; + + appAccountManager.setOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true, + (err: BusinessError) => { + console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); + }); ``` ### setOAuthTokenVisibility(deprecated) @@ -4060,9 +4270,11 @@ setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVi **示例:** ```js + import { BusinessError } from '@ohos.base'; + appAccountManager.setOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true).then(() => { console.log('setOAuthTokenVisibility successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); }); ``` @@ -4091,10 +4303,13 @@ checkOAuthTokenVisibility(name: string, authType: string, bundleName: string, ca **示例:** ```js - appAccountManager.checkOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', (err, data) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.checkOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', + (err: BusinessError, data: boolean) => { console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); console.log('checkOAuthTokenVisibility isVisible: ' + data); - }); + }); ``` ### checkOAuthTokenVisibility(deprecated) @@ -4126,10 +4341,13 @@ checkOAuthTokenVisibility(name: string, authType: string, bundleName: string): P **示例:** ```js - appAccountManager.checkOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo').then((data) => { - console.log('checkOAuthTokenVisibility isVisible: ' + data); - }).catch((err) => { - console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); + import { BusinessError } from '@ohos.base'; + + appAccountManager.checkOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo').then(( + data: boolean) => { + console.log('checkOAuthTokenVisibility isVisible: ' + data); + }).catch((err: BusinessError) => { + console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); }); ``` @@ -4156,10 +4374,13 @@ getAllOAuthTokens(name: string, owner: string, callback: AsyncCallback<Array& **示例:** ```js - appAccountManager.getAllOAuthTokens('LiSi', 'com.example.accountjsdemo', (err, data) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.getAllOAuthTokens('LiSi', 'com.example.accountjsdemo', + (err: BusinessError, data: account_appAccount.OAuthTokenInfo[]) => { console.log('getAllOAuthTokens err: ' + JSON.stringify(err)); console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); - }); + }); ``` ### getAllOAuthTokens(deprecated) @@ -4190,10 +4411,13 @@ getAllOAuthTokens(name: string, owner: string): Promise<Array<OAuthTokenIn **示例:** ```js - appAccountManager.getAllOAuthTokens('LiSi', 'com.example.accountjsdemo').then((data) => { - console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); - }).catch((err) => { - console.log('getAllOAuthTokens err: ' + JSON.stringify(err)); + import { BusinessError } from '@ohos.base'; + + appAccountManager.getAllOAuthTokens('LiSi', 'com.example.accountjsdemo').then(( + data: account_appAccount.OAuthTokenInfo[]) => { + console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); + }).catch((err: BusinessError) => { + console.log('getAllOAuthTokens err: ' + JSON.stringify(err)); }); ``` @@ -4220,7 +4444,9 @@ getOAuthList(name: string, authType: string, callback: AsyncCallback<Array< **示例:** ```js - appAccountManager.getOAuthList('LiSi', 'getSocialData', (err, data) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.getOAuthList('LiSi', 'getSocialData', (err: BusinessError, data: string[]) => { console.log('getOAuthList err: ' + JSON.stringify(err)); console.log('getOAuthList data: ' + JSON.stringify(data)); }); @@ -4254,9 +4480,11 @@ getOAuthList(name: string, authType: string): Promise<Array<string>> **示例:** ```js - appAccountManager.getOAuthList('LiSi', 'getSocialData').then((data) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.getOAuthList('LiSi', 'getSocialData').then((data: string[]) => { console.log('getOAuthList data: ' + JSON.stringify(data)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getOAuthList err: ' + JSON.stringify(err)); }); ``` @@ -4283,22 +4511,26 @@ getAuthenticatorCallback(sessionId: string, callback: AsyncCallback<Authentic **示例:** ```js + import { BusinessError } from '@ohos.base'; import UIAbility from '@ohos.app.ability.UIAbility'; + import Want from '@ohos.app.ability.Want'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; export default class EntryAbility extends UIAbility { - onCreate(want, param) { - var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; - appAccountManager.getAuthenticatorCallback(sessionId, (err, callback) => { - if (err.code != account_appAccount.ResultCode.SUCCESS) { - console.log('getAuthenticatorCallback err: ' + JSON.stringify(err)); - return; - } - var result = {[account_appAccount.Constants.KEY_NAME]: 'LiSi', - [account_appAccount.Constants.KEY_OWNER]: 'com.example.accountjsdemo', - [account_appAccount.Constants.KEY_AUTH_TYPE]: 'getSocialData', - [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - }); + onCreate(want: Want, param: AbilityConstant.LaunchParam) { + let sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; + appAccountManager.getAuthenticatorCallback(sessionId, + (err: BusinessError, callback: account_appAccount.AuthenticatorCallback) => { + if (err.code != account_appAccount.ResultCode.SUCCESS) { + console.log('getAuthenticatorCallback err: ' + JSON.stringify(err)); + return; + } + let result = {[account_appAccount.Constants.KEY_NAME]: 'LiSi', + [account_appAccount.Constants.KEY_OWNER]: 'com.example.accountjsdemo', + [account_appAccount.Constants.KEY_AUTH_TYPE]: 'getSocialData', + [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'}; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + }); } } ``` @@ -4330,18 +4562,22 @@ getAuthenticatorCallback(sessionId: string): Promise<AuthenticatorCallback> **示例:** ```js + import { BusinessError } from '@ohos.base'; import UIAbility from '@ohos.app.ability.UIAbility'; + import Want from '@ohos.app.ability.Want'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; export default class EntryAbility extends UIAbility { - onCreate(want, param) { - var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; - appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { - var result = {[account_appAccount.Constants.KEY_NAME]: 'LiSi', + onCreate(want: Want, param: AbilityConstant.LaunchParam) { + let sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; + appAccountManager.getAuthenticatorCallback(sessionId).then(( + callback: account_appAccount.AuthenticatorCallback) => { + let result = {[account_appAccount.Constants.KEY_NAME]: 'LiSi', [account_appAccount.Constants.KEY_OWNER]: 'com.example.accountjsdemo', [account_appAccount.Constants.KEY_AUTH_TYPE]: 'getSocialData', [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'}; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getAuthenticatorCallback err: ' + JSON.stringify(err)); }); } @@ -4370,10 +4606,13 @@ getAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorInfo **示例:** ```js - appAccountManager.getAuthenticatorInfo('com.example.accountjsdemo', (err, data) => { + import { BusinessError } from '@ohos.base'; + + appAccountManager.getAuthenticatorInfo('com.example.accountjsdemo', + (err: BusinessError, data: account_appAccount.AuthenticatorInfo) => { console.log('getAuthenticatorInfo err: ' + JSON.stringify(err)); console.log('getAuthenticatorInfo data: ' + JSON.stringify(data)); - }); + }); ``` ### getAuthenticatorInfo(deprecated) @@ -4403,10 +4642,13 @@ getAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> **示例:** ```js - appAccountManager.getAuthenticatorInfo('com.example.accountjsdemo').then((data) => { - console.log('getAuthenticatorInfo: ' + JSON.stringify(data)); - }).catch((err) => { - console.log('getAuthenticatorInfo err: ' + JSON.stringify(err)); + import { BusinessError } from '@ohos.base'; + + appAccountManager.getAuthenticatorInfo('com.example.accountjsdemo').then(( + data: account_appAccount.AuthenticatorInfo) => { + console.log('getAuthenticatorInfo: ' + JSON.stringify(data)); + }).catch((err: BusinessError) => { + console.log('getAuthenticatorInfo err: ' + JSON.stringify(err)); }); ``` @@ -4608,10 +4850,12 @@ onResult: (code: number, result?: AuthResult) => void **示例:** ```js + import { BusinessError } from '@ohos.base'; + let appAccountManager = account_appAccount.createAppAccountManager(); - var sessionId = '1234'; - appAccountManager.getAuthCallback(sessionId).then((callback) => { - var result = { + let sessionId = '1234'; + appAccountManager.getAuthCallback(sessionId).then((callback: account_appAccount.AuthCallback) => { + let result = { accountInfo: { name: 'Lisi', owner: 'com.example.accountjsdemo', @@ -4622,7 +4866,7 @@ onResult: (code: number, result?: AuthResult) => void } }; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getAuthCallback err: ' + JSON.stringify(err)); }); ``` @@ -4645,15 +4889,17 @@ onRequestRedirected: (request: Want) => void ```js class MyAuthenticator extends account_appAccount.Authenticator { - createAccountImplicitly(options, callback) { + createAccountImplicitly( + options: account_appAccount.CreateAccountImplicitlyOptions, callback: account_appAccount.AuthCallback) { callback.onRequestRedirected({ bundleName: 'com.example.accountjsdemo', abilityName: 'com.example.accountjsdemo.LoginAbility', }); } - auth(name, authType, options, callback) { - var result = { + auth(name: string, authType: string, + options: { [key: string]: Object }, callback: account_appAccount.AuthCallback) { + let result = { accountInfo: { name: 'Lisi', owner: 'com.example.accountjsdemo', @@ -4679,11 +4925,13 @@ onRequestContinued?: () => void **示例:** ```js + import { BusinessError } from '@ohos.base'; + let appAccountManager = account_appAccount.createAppAccountManager(); - var sessionId = '1234'; - appAccountManager.getAuthCallback(sessionId).then((callback) => { + let sessionId = '1234'; + appAccountManager.getAuthCallback(sessionId).then((callback: account_appAccount.AuthCallback) => { callback.onRequestContinued(); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getAuthCallback err: ' + JSON.stringify(err)); }); ``` @@ -4714,15 +4962,17 @@ onResult: (code: number, result: {[key: string]: any}) => void **示例:** ```js + import { BusinessError } from '@ohos.base'; + let appAccountManager = account_appAccount.createAppAccountManager(); - var sessionId = '1234'; - appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { - var result = {[account_appAccount.Constants.KEY_NAME]: 'LiSi', + let sessionId = '1234'; + appAccountManager.getAuthenticatorCallback(sessionId).then((callback: account_appAccount.AuthenticatorCallback) => { + let result = {[account_appAccount.Constants.KEY_NAME]: 'LiSi', [account_appAccount.Constants.KEY_OWNER]: 'com.example.accountjsdemo', [account_appAccount.Constants.KEY_AUTH_TYPE]: 'getSocialData', [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'}; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getAuthenticatorCallback err: ' + JSON.stringify(err)); }); ``` @@ -4745,15 +4995,17 @@ onRequestRedirected: (request: Want) => void ```js class MyAuthenticator extends account_appAccount.Authenticator { - addAccountImplicitly(authType, callerBundleName, options, callback) { + addAccountImplicitly(authType: string, callerBundleName: string, + options: { [key: string]: Object }, callback: account_appAccount.AuthenticatorCallback) { callback.onRequestRedirected({ bundleName: 'com.example.accountjsdemo', abilityName: 'com.example.accountjsdemo.LoginAbility', }); } - authenticate(name, authType, callerBundleName, options, callback) { - var result = {[account_appAccount.Constants.KEY_NAME]: name, + authenticate(name: string, authType: string, callerBundleName: string, + options: { [key: string]: Object }, callback: account_appAccount.AuthenticatorCallback) { + let result = {[account_appAccount.Constants.KEY_NAME]: name, [account_appAccount.Constants.KEY_AUTH_TYPE]: authType, [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'}; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); @@ -4772,11 +5024,13 @@ onRequestContinued?: () => void **示例:** ```js + import { BusinessError } from '@ohos.base'; + let appAccountManager = account_appAccount.createAppAccountManager(); - var sessionId = '1234'; - appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { + let sessionId = '1234'; + appAccountManager.getAuthenticatorCallback(sessionId).then((callback: account_appAccount.AuthenticatorCallback) => { callback.onRequestContinued(); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getAuthenticatorCallback err: ' + JSON.stringify(err)); }); ``` @@ -4934,48 +5188,53 @@ getRemoteObject(): rpc.RemoteObject; **示例:** ```js + import rpc from '@ohos.rpc'; + class MyAuthenticator extends account_appAccount.Authenticator { - addAccountImplicitly(authType, callerBundleName, options, callback) { - callback.onRequestRedirected({ - bundleName: 'com.example.accountjsdemo', - abilityName: 'com.example.accountjsdemo.LoginAbility', - }); + addAccountImplicitly(authType: string, callerBundleName: string, + options: { [key: string]: Object }, callback: account_appAccount.AuthenticatorCallback) { + callback.onRequestRedirected({ + bundleName: 'com.example.accountjsdemo', + abilityName: 'com.example.accountjsdemo.LoginAbility', + }); } - authenticate(name, authType, callerBundleName, options, callback) { - var result = {[account_appAccount.Constants.KEY_NAME]: name, - [account_appAccount.Constants.KEY_AUTH_TYPE]: authType, - [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + authenticate(name: string, authType: string, callerBundleName: string, + options: { [key: string]: Object }, callback: account_appAccount.AuthenticatorCallback) { + let result = {[account_appAccount.Constants.KEY_NAME]: name, + [account_appAccount.Constants.KEY_AUTH_TYPE]: authType, + [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'}; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); } - verifyCredential(name, options, callback) { - callback.onRequestRedirected({ - bundleName: 'com.example.accountjsdemo', - abilityName: 'com.example.accountjsdemo.VerifyAbility', - parameters: { - name: name - } - }); + verifyCredential(name: string, + options: account_appAccount.VerifyCredentialOptions, callback: account_appAccount.AuthCallback) { + callback.onRequestRedirected({ + bundleName: 'com.example.accountjsdemo', + abilityName: 'com.example.accountjsdemo.VerifyAbility', + parameters: { + name: name + } + }); } - setProperties(options, callback) { + setProperties(options: account_appAccount.SetPropertiesOptions, callback: account_appAccount.AuthCallback) { callback.onResult(account_appAccount.ResultCode.SUCCESS, {}); } - checkAccountLabels(name, labels, callback) { - var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: false}; + checkAccountLabels(name: string, labels: string[], callback: account_appAccount.AuthCallback) { + let result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: false}; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); } - checkAccountRemovable(name, callback) { - var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: true}; + checkAccountRemovable(name: string, callback: account_appAccount.AuthCallback) { + let result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: true}; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); } } - var authenticator = null; + let authenticator = null; export default { - onConnect(want) { + onConnect(want): rpc.RemoteObject { authenticator = new MyAuthenticator(); return authenticator.getRemoteObject(); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-appControl.md b/zh-cn/application-dev/reference/apis/js-apis-appControl.md index 03286aaa8a0cabe11779d0755aefe5802dbf2eb3..a0a7b55af9f4fd4e745d57d6d11bb97942db3ecb 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-appControl.md +++ b/zh-cn/application-dev/reference/apis/js-apis-appControl.md @@ -81,9 +81,9 @@ setDisposedStatus(appId: string, disposedWant: Want, callback: AsyncCallback\ appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 | +| appId | string | 是 | 需要设置处置的应用的appId。
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 | | disposedWant | Want | 是 | 对应用的处置意图。 | -| callback | AsyncCallback\ | 是 | 回调函数,当设置处置状态成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback\ | 是 | 回调函数,当设置处置状态成功,err为null,否则为错误对象。 | **错误码:** @@ -112,6 +112,49 @@ try { } ``` +## appControl.setDisposedStatusSync + +setDisposedStatusSync(appId: string, disposedWant: Want): void; + +以同步方法设置应用的处置状态。成功返回null,失败抛出对应异常。 + +**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**系统能力:** SystemCapability.BundleManager.BundleFramework.AppControl + +**系统API:** 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------------------------------- | ---- | --------------------------------------- | +| appId | string | 是 | 需要设置处置的应用的appId。
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 | +| disposedWant | Want | 是 | 对应用的处置意图。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| ------ | -------------------------------------- | +| 17700005 | The specified app ID is empty string. | + +**示例:** + +```ts +import appControl from '@ohos.bundle.appControl'; +import Want from '@ohos.app.ability.Want'; + +let appId: string = "com.example.myapplication_xxxxx"; +let want: Want = {bundleName: 'com.example.myapplication'}; + +try { + appControl.setDisposedStatusSync(appId, want); +} catch (error) { + console.error('setDisposedStatusSync failed ' + error.message); +} +``` + ## appControl.getDisposedStatus getDisposedStatus(appId: string): Promise\; @@ -128,7 +171,7 @@ getDisposedStatus(appId: string): Promise\; | 参数名 | 类型 | 必填 | 说明 | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | 是 | 要查询的应用的appId
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 | +| appId | string | 是 | 要查询的应用的appId。
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 | **返回值:** @@ -177,8 +220,8 @@ getDisposedStatus(appId: string, callback: AsyncCallback\): void; | 参数名 | 类型 | 必填 | 说明 | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | 是 | 要查询的应用的appId
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 | -| callback | AsyncCallback\ | 是 | 回调函数。当获取应用的处置状态成功时,err为undefined,data为获取到的处置状态;否则为错误对象。 | +| appId | string | 是 | 要查询的应用的appId。
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 | +| callback | AsyncCallback\ | 是 | 回调函数。当获取应用的处置状态成功时,err为null,data为获取到的处置状态;否则为错误对象。 | **错误码:** @@ -206,6 +249,54 @@ try { } ``` +## appControl.getDisposedStatusSync + +getDisposedStatusSync(appId: string): Want; + +以同步方法获取指定应用已设置的处置状态。成功返回应用的处置状态,失败抛出对应异常。 + +**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**系统能力:** SystemCapability.BundleManager.BundleFramework.AppControl + +**系统API:** 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | --------------------------------------- | +| appId | string | 是 | 要查询的应用的appId。
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------- | ------------------ | +| Want | 返回应用的处置状态。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| ------ | -------------------------------------- | +| 17700005 | The specified app ID is empty string. | + +**示例:** + +```ts +import appControl from '@ohos.bundle.appControl'; +import Want from '@ohos.app.ability.Want'; + +let appId: string = "com.example.myapplication_xxxxx"; +let want: Want; + +try { + want = appControl.getDisposedStatusSync(appId); +} catch (error) { + console.error('getDisposedStatusSync failed ' + error.message); +} +``` + ## appControl.deleteDisposedStatus deleteDisposedStatus(appId: string): Promise\ @@ -222,7 +313,7 @@ deleteDisposedStatus(appId: string): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | 是 | 要删除处置状态的应用的appId
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 | +| appId | string | 是 | 要删除处置状态的应用的appId。
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 | **返回值:** @@ -272,7 +363,7 @@ deleteDisposedStatus(appId: string, callback: AsyncCallback\) : void | 参数名 | 类型 | 必填 | 说明 | | ----------- | ------ | ---- | --------------------------------------- | | appId | string | 是 | 要查询的应用的appId。
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 | -| callback | AsyncCallback\ | 是 | 回调函数,当设置处置状态成功时,err返回undefined。否则回调函数返回具体错误对象。 | +| callback | AsyncCallback\ | 是 | 回调函数,当设置处置状态成功时,err返回null。否则回调函数返回具体错误对象。 | **错误码:** @@ -299,6 +390,46 @@ try { } ``` +## appControl.deleteDisposedStatusSync + +deleteDisposedStatusSync(appId: string) : void + +以同步方法删除应用的处置状态。成功返回null,失败抛出对应异常。 + +**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**系统能力:** SystemCapability.BundleManager.BundleFramework.AppControl + +**系统API:** 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | --------------------------------------- | +| appId | string | 是 | 要查询的应用的appId。
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| ------ | -------------------------------------- | +| 17700005 | The specified app ID is empty string. | + +**示例:** + +```ts +import appControl from '@ohos.bundle.appControl'; + +let appId: string = "com.example.myapplication_xxxxx"; + +try { + appControl.deleteDisposedStatusSync(appId); +} catch (error) { + console.error('deleteDisposedStatusSync failed ' + error.message); +} +``` + ## 获取应用的appId appId是应用的唯一标识,由应用Bundle名称和签名信息决定,可以通过[getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo)接口获取。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md index 15bc8eed451e45318577a284976516647700288e..d988832ce62ba906765916f4141f5fa46bfe5f51 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md @@ -50,17 +50,17 @@ let TBL_NAME = 'TBL00'; let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' + TBL_NAME + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; -let rdbStore; +let rdbStore: relationalStore.RdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - onCreate(want, callback) { + onCreate(want: Want, callback: Function) { rdb.getRdbStore(this.context, { name: DB_NAME, securityLevel: rdb.SecurityLevel.S1 - }, function (err, data) { + }, (err, data) => { console.info(`getRdbStore done, data : ${data}`); rdbStore = data; - rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { + rdbStore.executeSql(DDL_TBL_CREATE, [], (err) => { console.error(`executeSql done, error message : ${err}`); }); if (callback) { @@ -91,21 +91,22 @@ insert?(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback<numbe ```ts import rdb from '@ohos.data.relationalStore'; +import { ValuesBucket } from '@ohos.data.ValuesBucket' let DB_NAME = 'DB00.db'; let TBL_NAME = 'TBL00'; let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' + TBL_NAME + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; -let rdbStore; +let rdbStore: relationalStore.RdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - insert(uri, valueBucket, callback) { + insert(uri: string, valueBucket: ValuesBucket, callback: Function) { if (valueBucket === null) { console.error('invalid valueBuckets'); return; } - rdbStore.insert(TBL_NAME, valueBucket, function (err, ret) { + rdbStore.insert(TBL_NAME, valueBucket, (err, ret) => { console.info(`callback ret: ${ret}`); if (callback !== undefined) { callback(err, ret); @@ -136,20 +137,22 @@ update?(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueB ```ts import rdb from '@ohos.data.relationalStore'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import { ValuesBucket } from '@ohos.data.ValuesBucket' let DB_NAME = 'DB00.db'; let TBL_NAME = 'TBL00'; let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' + TBL_NAME + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; -let rdbStore; +let rdbStore: relationalStore.RdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - update(uri, predicates, valueBucket, callback) { + update(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueBucket: ValuesBucket, callback: Function) { if (predicates === null || predicates === undefined) { return; } - rdbStore.update(TBL_NAME, valueBucket, predicates, function (err, ret) { + rdbStore.update(TBL_NAME, valueBucket, predicates, (err, ret) => { if (callback !== undefined) { callback(err, ret); } @@ -178,20 +181,21 @@ delete?(uri: string, predicates: dataSharePredicates.DataSharePredicates, callba ```ts import rdb from '@ohos.data.relationalStore'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let DB_NAME = 'DB00.db'; let TBL_NAME = 'TBL00'; let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' + TBL_NAME + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; -let rdbStore; +let rdbStore: relationalStore.RdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - delete(uri, predicates, callback) { + delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: Function) { if (predicates === null || predicates === undefined) { return; } - rdbStore.delete(TBL_NAME, predicates, function (err, ret) { + rdbStore.delete(TBL_NAME, predicates, (err, ret) => { if (callback !== undefined) { callback(err, ret); } @@ -221,20 +225,21 @@ query?(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns ```ts import rdb from '@ohos.data.relationalStore'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let DB_NAME = 'DB00.db'; let TBL_NAME = 'TBL00'; let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' + TBL_NAME + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; -let rdbStore; +let rdbStore: relationalStore.RdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - query(uri, predicates, columns, callback) { + query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array, callback: Function) { if (predicates === null || predicates === undefined) { return; } - rdbStore.query(TBL_NAME, predicates, columns, function (err, resultSet) { + rdbStore.query(TBL_NAME, predicates, columns, (err, resultSet) => { if (resultSet !== undefined) { console.info(`resultSet.rowCount: ${resultSet.rowCount}`); } @@ -266,21 +271,22 @@ batchInsert?(uri: string, valueBuckets: Array<ValuesBucket>, callback: Asy ```ts import rdb from '@ohos.data.relationalStore'; +import { ValuesBucket } from '@ohos.data.ValuesBucket' let DB_NAME = 'DB00.db'; let TBL_NAME = 'TBL00'; let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' + TBL_NAME + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; -let rdbStore; +let rdbStore: relationalStore.RdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - batchInsert(uri, valueBuckets, callback) { + batchInsert(uri: string, valueBuckets: Array, callback: Function) { if (valueBuckets === null || valueBuckets.length === undefined) { console.error('invalid valueBuckets'); return; } - rdbStore.batchInsert(TBL_NAME, valueBuckets, function (err, ret) { + rdbStore.batchInsert(TBL_NAME, valueBuckets, (err, ret) => { if (callback !== undefined) { callback(err, ret); } @@ -308,11 +314,17 @@ normalizeUri?(uri: string, callback: AsyncCallback<string>): void ```ts export default class DataShareExtAbility extends DataShareExtensionAbility { - normalizeUri(uri, callback) { - let err = {'code':0}; - let ret = `normalize: ${uri}`; - callback(err, ret); - } + normalizeUri(uri: string, callback: Function) { + let key = 'code'; + let value = 0; + let err: BusinessError = { + code: value, + name: key, + message: key + }; + let ret: string = `normalize: ${uri}`; + callback(err, ret); + } }; ``` @@ -335,10 +347,16 @@ denormalizeUri?(uri: string, callback: AsyncCallback<string>): void ```ts export default class DataShareExtAbility extends DataShareExtensionAbility { - denormalizeUri(uri, callback) { - let err = {'code':0}; - let ret = `denormalize ${uri}`; - callback(err, ret); - } + denormalizeUri(uri: string, callback: Function) { + let key = 'code'; + let value = 0; + let err: BusinessError = { + code: value, + name: key, + message: key + }; + let ret = `denormalize ${uri}`; + callback(err, ret); + } }; ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md b/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md index f483bde4cbcf7d38e91f6a05814d31db24dd3690..fe1b4d6237abab97c9259bef1cd5cae8f85f8030 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md @@ -214,7 +214,7 @@ struct AnimateToExample { ### showAlertDialog -showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButtons): void +showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButtons | AlertDialogParamWithOptions): void 显示警告弹窗组件,可设置文本内容与响应回调。 @@ -224,7 +224,8 @@ showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButto | 参数名 | 类型 | 必填 | 说明 | | ---- | --------------- | -------- | -------- | -| options | [AlertDialogParamWithConfirm](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithconfirm对象说明) \| [AlertDialogParamWithButtons](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithbuttons对象说明) | 是 | 定义并显示AlertDialog组件。 | +| options | [AlertDialogParamWithConfirm](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithconfirm对象说明) \| [AlertDialogParamWithButtons](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithbuttons对象说明) \| [AlertDialogParamWithOptions](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithoptions10对象说明) | 是 | 定义并显示AlertDialog组件。 | + **示例:** @@ -1201,7 +1202,7 @@ try { ### pushNamedRoute -pushNamedRoute(options: router.NamedRouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void +pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void 跳转到指定的命名路由页面。 @@ -1361,7 +1362,7 @@ replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): | 错误码ID | 错误信息 | | --------- | ------- | -| 100001 | if UI execution context not found, only throw in standard system. | +| 100001 | if can not get the delegate, only throw in standard system. | | 100004 | if the named route is not exist. | **示例:** @@ -1425,7 +1426,7 @@ router.replaceNamedRoute({ ### back -back(options: router.RouterOptions ): void +back(options?: router.RouterOptions ): void 返回上一页面或指定的页面。 @@ -1435,7 +1436,7 @@ back(options: router.RouterOptions ): void | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 返回页面描述信息,其中参数url指路由跳转时会返回到指定url的界面,如果页面栈上没有url页面,则不响应该情况。如果url未设置,则返回上一页,页面不会重新构建,页面栈里面的page不会回收,出栈后会被回收。 | +| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 否 | 返回页面描述信息,其中参数url指路由跳转时会返回到指定url的界面,如果页面栈上没有url页面,则不响应该情况。如果url未设置,则返回上一页,页面不会重新构建,页面栈里面的page不会回收,出栈后会被回收。 | **示例:** @@ -1618,7 +1619,7 @@ try { ### showDialog -showDialog(options: promptAction.ShowDialogOptions, callback: AsyncCallback<promptAction.ShowDialogSuccessResponse<): void +showDialog(options: promptAction.ShowDialogOptions, callback: AsyncCallback<promptAction.ShowDialogSuccessResponse>): void 创建并显示对话框,对话框响应结果异步返回。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-arkui-dragController.md b/zh-cn/application-dev/reference/apis/js-apis-arkui-dragController.md index 60fe7f95f7041db90977a63690fb4575c0701a6c..471fc303f6ad40f975d9f8a56f0dfe2af3a93015 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arkui-dragController.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arkui-dragController.md @@ -175,7 +175,7 @@ struct DragControllerPage { 发起拖拽所需要的属性和拖拽时携带的信息。 -| 名称 | 类型 | 必填 | 描述 | +| 名称 | 类型 | 必填 | 说明 | | ----------- | ------------------------------------------------------ | ---- | ---------------------------------------- | | pointerId | number | 是 | 设置启动拖拽时屏幕上触摸点的Id。 | | data | [UDMF.UnifiedData](./js-apis-data-udmf.md#unifieddata) | 否 | 设置拖拽过程中携带的数据。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md b/zh-cn/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md index 67a8d3a70bd12d37bb4f71785814f741d3f18815..ed1e4495a6798ce533d8f1a9966ff3d8ae786a3c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md @@ -141,7 +141,7 @@ getBackground(): DrawableDescriptor; **示例:** ```ts let resManager = getContext().resourceManager -drawable: DrawableDescriptor = ( (resManager.getDrawableDescriptor($r('app.media.icon') +let drawable: DrawableDescriptor = ( (resManager.getDrawableDescriptor($r('app.media.icon') .id))).getBackground(); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-audio.md b/zh-cn/application-dev/reference/apis/js-apis-audio.md index ed2c521ace2e1f25f7ac493fade668b8a8c1c637..01ec48911898f3ae2be5b72eb17152cce9a69ba3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-audio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-audio.md @@ -4461,6 +4461,156 @@ off(type: 'preferredOutputDeviceChangeForRendererInfo', callback?: Callback10+ + +getPreferredInputDeviceForCapturerInfo(capturerInfo: AudioCapturerInfo, callback: AsyncCallback<AudioDeviceDescriptors>): void + +根据音频信息,返回优先级最高的输入设备,使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | 是 | 表示采集器信息。 | +| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | 是 | 回调,返回优先级最高的输入设备信息。 | + +**错误码:** + +以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。 + +| 错误码ID | 错误信息 | +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | +| 6800301 | System error | + +**示例:** +```js +let capturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags: 0 +} + +audioRoutingManager.getPreferredInputDeviceForCapturerInfo(capturerInfo, (err, desc) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info(`device descriptor: ${desc}`); + } +}); +``` + +### getPreferredInputDeviceForCapturerInfo10+ + +getPreferredInputDeviceForCapturerInfo(capturerInfo: AudioCapturerInfo): Promise<AudioDeviceDescriptors> + +根据音频信息,返回优先级最高的输入设备,使用promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | +| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | 是 | 表示采集器信息。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | --------------------------- | +| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise返回优先级最高的输入设备信息。 | + +**错误码:** + +以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。 + +| 错误码ID | 错误信息 | +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | +| 6800301 | System error | + +**示例:** + +```js +let capturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags: 0 +} + +audioRoutingManager.getPreferredInputDeviceForCapturerInfo(capturerInfo).then((desc) => { + console.info(`device descriptor: ${desc}`); +}).catch((err) => { + console.error(`Result ERROR: ${err}`); +}) +``` + +### on('preferredInputDeviceChangeForCapturerInfo')10+ + +on(type: 'preferredInputDeviceChangeForCapturerInfo', capturerInfo: AudioCapturerInfo, callback: Callback): void + +订阅最高优先级输入设备变化事件,使用callback获取最高优先级输入设备。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | +| type | string | 是 | 订阅的事件的类型。支持事件:'preferredInputDeviceChangeForCapturerInfo' | +| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | 是 | 表示采集器信息。 | +| callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)\> | 是 | 获取优先级最高的输入设备信息。 | + +**错误码:** + +以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。 + +| 错误码ID | 错误信息 | +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | + +**示例:** + +```js +let capturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags: 0 +} + +audioRoutingManager.on('preferredInputDeviceChangeForCapturerInfo', capturerInfo, (desc) => { + console.info(`device descriptor: ${desc}`); +}); +``` + +### off('preferredInputDeviceChangeForCapturerInfo')10+ + +off(type: 'preferredInputDeviceChangeForCapturerInfo', callback?: Callback): void + +取消订阅最高优先级输入音频设备变化事件。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | +| type | string | 是 | 订阅的事件的类型。支持事件:'preferredInputDeviceChangeForCapturerInfo' | +| callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | 否 | 监听方法的回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。 + +| 错误码ID | 错误信息 | +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | + +**示例:** + +```js +audioRoutingManager.off('preferredInputDeviceChangeForCapturerInfo'); +``` + ## AudioRendererChangeInfoArray9+ 数组类型,AudioRenderChangeInfo数组,只读。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-bluetooth-ble.md b/zh-cn/application-dev/reference/apis/js-apis-bluetooth-ble.md index a9875e133df4292bd4d7108ebc632e75f1151744..c6b4f0f9e15754c5b2de3142425322e5ea5dffdd 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bluetooth-ble.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bluetooth-ble.md @@ -983,6 +983,66 @@ gattServer.off('connectionStateChange'); ``` +### on('BLEMtuChange') + +on(type: 'BLEMtuChange', callback: Callback<number>): void + +server端订阅MTU状态变化事件。 + +**需要权限**:ohos.permission.ACCESS_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 必须填写"BLEMtuChange"字符串,表示MTU状态变化事件。填写不正确将导致回调无法注册。 | +| callback | Callback<number> | 是 | 返回MTU字节数的值,通过注册回调函数获取。 | + +**示例:** + +```js +try { + let gattServer = ble.createGattServer(); + gattServer.on('BLEMtuChange', (mtu) => { + console.info('BLEMtuChange, mtu: ' + mtu); + }); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### off('BLEMtuChange') + +off(type: 'BLEMtuChange', callback?: Callback<number>): void + +server端取消订阅MTU状态变化事件。 + +**需要权限**:ohos.permission.ACCESS_BLUETOOTH + +**系统能力**:SystemCapability.Communication.Bluetooth.Core。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 必须填写"BLEMtuChange"字符串,表示MTU状态变化事件。填写不正确将导致回调无法注册。 | +| callback | Callback<number> | 否 | 返回MTU字节数的值,通过注册回调函数获取。不填该参数则取消订阅该type对应的所有回调。 | + +**示例:** + +```js +try { + let gattServer = ble.createGattServer(); + gattServer.off('BLEMtuChange'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + ## GattClientDevice client端类,使用client端方法之前需要创建该类的实例进行操作,通过createGattClientDevice(deviceId: string)方法构造此实例。 @@ -2179,7 +2239,7 @@ try { on(type: 'BLEMtuChange', callback: Callback<number>): void -订阅Mtu状态变化事件。 +client端订阅MTU状态变化事件。 **需要权限**:ohos.permission.ACCESS_BLUETOOTH @@ -2189,8 +2249,8 @@ on(type: 'BLEMtuChange', callback: Callback<number>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | string | 是 | 填写"BLEMtuChange"字符串,表示Mtu状态变化事件。 | -| callback | Callback<number> | 是 | 表示Mtu状态,已连接或是断开。 | +| type | string | 是 | 必须填写"BLEMtuChange"字符串,表示MTU状态变化事件。填写不正确将导致回调无法注册。 | +| callback | Callback<number> | 是 | 返回MTU字节数的值,通过注册回调函数获取。 | **示例:** @@ -2210,7 +2270,7 @@ try { off(type: 'BLEMtuChange', callback?: Callback<number>): void -取消订阅Mtu状态变化事件。 +client端取消订阅MTU状态变化事件。 **需要权限**:ohos.permission.ACCESS_BLUETOOTH @@ -2220,8 +2280,8 @@ off(type: 'BLEMtuChange', callback?: Callback<number>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | string | 是 | 填写"BLEMtuChange"字符串,表示Mtu状态变化事件。 | -| callback | Callback<number> | 否 | 表示取消订阅Mtu状态变化事件。不填该参数则取消订阅该type对应的所有回调。 | +| type | string | 是 | 必须填写"BLEMtuChange"字符串,表示MTU状态变化事件。填写不正确将导致回调无法注册。 | +| callback | Callback<number> | 否 | 返回MTU字节数的值,通过注册回调函数获取。不填该参数则取消订阅该type对应的所有回调。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md index ae5328800429e186efd37c03c9f8431cbac566e0..8f0261ed7ae4afddae29b768bf3192a3c7befe4f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md @@ -113,8 +113,10 @@ Ability组件信息标志,指示需要获取的Ability组件信息的内容。 | THUMBNAIL | 13 | ThumbnailExtensionAbility:文件缩略图扩展能力,用于为文件提供图标缩略图的能力。预留能力,当前暂未支持。 | | PREVIEW | 14 | PreviewExtensionAbility:文件预览扩展能力,提供文件预览的能力,其他应用可以直接在应用中嵌入显示。预留能力,当前暂未支持。 | | PRINT10+ | 15 | PrintExtensionAbility:文件打印扩展能力,提供应用打印照片、文档等办公场景。当前支持图片打印,文档类型暂未支持。 | +| SHARE10+ | 16 | [ShareExtensionAbility](js-apis-app-ability-shareExtensionAbility.md):提供分享业务能力,为开发者提供基于UIExtension的分享业务模板。 | | PUSH10+ | 17 | PushExtensionAbility:推送扩展能力,提供推送场景化消息能力。预留能力,当前暂未支持。 | | DRIVER10+ | 18 | DriverExtensionAbility:驱动扩展能力,提供外设驱动扩展能力,当前暂未支持。 | +| ACTION10+ | 19 | [ActionExtensionAbility](js-apis-app-ability-actionExtensionAbility.md):自定义服务扩展能力,为开发者提供基于UIExtension的自定义操作业务模板。 | | UNSPECIFIED | 255 | 不指定类型,配合queryExtensionAbilityInfo接口可以查询所有类型的ExtensionAbility。 | @@ -1141,6 +1143,82 @@ try { } ``` +### bundleManager.queryAbilityInfoSync + +queryAbilityInfoSync(want: Want, abilityFlags: [number](#abilityflag), userId?: number): Array\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)>; + +以同步方法根据给定的want、abilityFlags和userId获取一个或多个AbilityInfo。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------ | ------ | ---- | ------------------------------------------------------- | +| want | Want | 是 | 表示包含要查询的应用Bundle名称的Want。 | +| abilityFlags | [number](#abilityflag) | 是 | 表示指定返回的AbilityInfo所包含的信息。 | +| userId | number | 否 | 表示用户ID,默认值:调用方所在用户,取值范围:大于等于0。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | ------------------------------------ | +| Array\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)> | Array\信息。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------- | +| 17700001 | The specified bundleName is not found. | +| 17700003 | The specified ability is not found. | +| 17700004 | The specified userId is invalid. | +| 17700026 | The specified bundle is disabled. | +| 17700029 | The specified ability is disabled. | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; +let userId = 100; +let want = { + bundleName : "com.example.myapplication", + abilityName : "EntryAbility" +}; + +try { + + let infos = bundleManager.queryAbilityInfoSync(want, abilityFlags, userId); + hilog.info(0x0000, 'testTag', 'queryAbilityInfoSync successfully. Data: %{public}s', JSON.stringify(infos)); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfoSync failed. Cause: %{public}s', err.message); +} +``` + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; +let want = { + bundleName : "com.example.myapplication", + abilityName : "EntryAbility" +}; + +try { + let infos = bundleManager.queryAbilityInfoSync(want, abilityFlags); + hilog.info(0x0000, 'testTag', 'queryAbilityInfoSync successfully. Data: %{public}s', JSON.stringify(infos)); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfoSync failed. Cause: %{public}s', err.message); +} +``` + ### bundleManager.queryExtensionAbilityInfo queryExtensionAbilityInfo(want: Want, extensionAbilityType: [ExtensionAbilityType](#extensionabilitytype), extensionAbilityFlags: [number](#extensionabilityflag), userId: number, callback: AsyncCallback>): void; @@ -1340,6 +1418,84 @@ try { } ``` +### bundleManager.queryExtensionAbilityInfoSync + +queryExtensionAbilityInfoSync(want: Want, extensionAbilityType: [ExtensionAbilityType](#extensionabilitytype), extensionAbilityFlags: [number](#extensionabilityflag), userId?: number): Array\<[ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md)>; + +以同步方法根据给定的want、extensionAbilityType、extensionAbilityFlags和userId获取ExtensionAbilityInfo。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------------------- | --------------------------------------------- | ---- | --------------------------------------------------------- | +| want | Want | 是 | 表示包含要查询的应用Bundle名称的Want。 | +| extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | 是 | 标识extensionAbility的类型。 | +| extensionAbilityFlags | [number](#extensionabilityflag) | 是 | 表示用于指定将返回的ExtensionInfo对象中包含的信息的标志。 | +| userId | number | 否 | 表示用户ID,默认值:调用方所在用户,取值范围:大于等于0。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | --------------------------------------------- | +| Array\<[ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md)> | Array\信息。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------| +| 17700001 | The specified bundleName is not found. | +| 17700003 | The specified extensionAbility is not found. | +| 17700004 | The specified userId is invalid. | +| 17700026 | The specified bundle is disabled. | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; + +let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM; +let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT; +let userId = 100; +let want = { + bundleName : "com.example.myapplication", + abilityName : "EntryAbility" +}; + +try { + let extenInfos = bundleManager.queryExtensionAbilityInfoSync(want, extensionAbilityType, extensionFlags, userId); + hilog.info(0x0000, 'testTag', 'queryExtensionAbilityInfoSync successfully. Data: %{public}s', JSON.stringify(extenInfos)); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfoSync failed. Cause: %{public}s', err.message); +} +``` + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM; +let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT; +let want = { + bundleName : "com.example.myapplication", + abilityName : "EntryAbility" +}; + +try { + let extenInfos = bundleManager.queryExtensionAbilityInfoSync(want, extensionAbilityType, extensionFlags); + hilog.info(0x0000, 'testTag', 'queryExtensionAbilityInfoSync successfully. Data: %{public}s', JSON.stringify(extenInfos)); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfoSync failed. Cause: %{public}s', err.message); +} +``` + ### bundleManager.getBundleNameByUid getBundleNameByUid(uid: number, callback: AsyncCallback\): void; @@ -1435,6 +1591,52 @@ try { } ``` +### bundleManager.getBundleNameByUidSync10+ + +getBundleNameByUidSync(uid: number): string; + +以同步方法根据给定的uid获取对应的bundleName。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | ------------------ | +| uid | number | 是 | 表示应用程序的UID。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | --------------------------- | +| string | 返回获取到的bundleName。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------| +| 17700021 | The uid is not found. | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let uid = 20010005; +try { + let data = bundleManager.getBundleNameByUidSync(uid); + hilog.info(0x0000, 'testTag', 'getBundleNameByUidSync successfully. Data: %{public}s', JSON.stringify(data)); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleNameByUidSync failed. Cause: %{public}s', err.message); +} +``` + ### bundleManager.getBundleArchiveInfo getBundleArchiveInfo(hapFilePath: string, bundleFlags: [number](#bundleflag), callback: AsyncCallback\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)>): void; @@ -1536,6 +1738,55 @@ try { } ``` +### bundleManager.getBundleArchiveInfoSync10+ + +getBundleArchiveInfoSync(hapFilePath: string, bundleFlags: number): BundleInfo; + +以同步方法根据给定的hapFilePath和bundleFlags获取BundleInfo对象。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ------------------------------------------------------------ | +| hapFilePath | string | 是 | 表示存储HAP的路径,路径应该是当前应用程序数据目录的相对路径。 | +| bundleFlags | [number](#bundleflag) | 是 | 表示用于指定要返回的BundleInfo对象中包含的信息的标志。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------------------------- | --------------------------- | +| [BundleInfo](js-apis-bundleManager-bundleInfo.md) | 返回BundleInfo对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------- | +| 17700022 | The hapFilePath is invalid. | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let hapFilePath = "/data/xxx/test.hap"; +let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; + +try { + let data = bundleManager.getBundleArchiveInfoSync(hapFilePath, bundleFlags) + hilog.info(0x0000, 'testTag', 'getBundleArchiveInfoSync successfully. Data: %{public}s', JSON.stringify(data)); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleArchiveInfoSync failed. Cause: %{public}s', err.message); +} +``` + ### bundleManager.cleanBundleCacheFiles cleanBundleCacheFiles(bundleName: string, callback: AsyncCallback\): void; @@ -2438,6 +2689,72 @@ try { } ``` + +### bundleManager.getLaunchWantForBundleSync + +getLaunchWantForBundleSync(bundleName: string, userId?: number): Want; + +以同步方法根据给定的bundleName和userId获取用于启动应用程序的Want参数。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------ | ---- | ------------------------- | +| bundleName | string | 是 | 表示应用程序的bundleName。 | +| userId | number | 否 | 表示用户ID,默认值:调用方所在用户,取值范围:大于等于0。 | + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------- | +| Want | Want对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------| +| 17700001 | The specified bundleName is not found. | +| 17700004 | The specified user ID is not found. | +| 17700026 | The specified bundle is disabled. | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let bundleName = 'com.example.myapplication'; +let userId = 100; + +try { + let want = bundleManager.getLaunchWantForBundleSync(bundleName, userId); + hilog.info(0x0000, 'testTag', 'getLaunchWantForBundleSync successfully. Data: %{public}s', JSON.stringify(want)); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundleSync failed. Cause: %{public}s', err.message); +} +``` + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let bundleName = 'com.example.myapplication'; +let userId = 100; + +try { + let want = bundleManager.getLaunchWantForBundleSync(bundleName); + hilog.info(0x0000, 'testTag', 'getLaunchWantForBundleSync successfully. Data: %{public}s', JSON.stringify(want)); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundleSync failed. Cause: %{public}s', err.message); +} +``` + ### bundleManager.getProfileByAbility getProfileByAbility(moduleName: string, abilityName: string, metadataName: string, callback: AsyncCallback\\>): void; @@ -2559,6 +2876,70 @@ try { } ``` +### bundleManager.getProfileByAbilitySync10+ + +getProfileByAbilitySync(moduleName: string, abilityName: string, metadataName?: string): Array\; + +以同步方法根据给定的moduleName、abilityName和metadataName获取相应配置文件的json格式字符串,返回对象为string数组。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------ | ------ | ---- | -------------------------- | +| moduleName | string | 是 | 表示应用程序的moduleName。 | +| abilityName | string | 是 | 表示应用程序的abilityName。 | +| metadataName | string | 否 | 表示应用程序的metadataName,默认值为空。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------- | ------------------------------- | +| Array\ | 数组对象,返回Array\。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------------------ | +| 17700002 | The specified moduleName is not existed. | +| 17700003 | The specified abilityName is not existed. | +| 17700024 | Failed to get the profile because there is no profile in the HAP. | +| 17700026 | The specified bundle is disabled. | +| 17700029 | The specified ability is disabled. | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let moduleName = 'entry'; +let abilityName = 'EntryAbility'; + +try { + let data = bundleManager.getProfileByAbilitySync(moduleName, abilityName); + hilog.info(0x0000, 'testTag', 'getProfileByAbilitySync successfully. Data: %{public}s', JSON.stringify(data)); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getProfileByAbilitySync failed. Cause: %{public}s', err.message); +} +``` + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let moduleName: string = 'entry'; +let abilityName: string = 'EntryAbility'; +let metadataName: string = 'com.example.myapplication.metadata'; +try { + let data = bundleManager.getProfileByAbilitySync(moduleName, abilityName, metadataName); + hilog.info(0x0000, 'testTag', 'getProfileByAbilitySync successfully. Data: %{public}s', JSON.stringify(data)); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getProfileByAbilitySync failed. Cause: %{public}s', err.message); +} +``` + ### bundleManager.getProfileByExtensionAbility getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName: string, callback: AsyncCallback\\>): void; @@ -2672,6 +3053,63 @@ try { } ``` +### bundleManager.getProfileByExtensionAbilitySync10+ + +getProfileByExtensionAbilitySync(moduleName: string, extensionAbilityName: string, metadataName?: string): Array\; + +以同步方法根据给定的moduleName、extensionAbilityName和metadataName获取相应配置文件的json格式字符串,返回对象为string数组。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------------------- | ------ | ---- | ---------------------------------- | +| moduleName | string | 是 | 表示应用程序的moduleName。 | +| extensionAbilityName | string | 是 | 表示应用程序的extensionAbilityName。 | +| metadataName | string | 否 | 表示应用程序的metadataName,默认值为空。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------- | ----------------------------------- | +| Array\ | 返回Array\对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------------------ | +| 17700002 | The specified moduleName is not existed. | +| 17700003 | The specified extensionAbilityName not existed. | +| 17700024 | Failed to get the profile because there is no profile in the HAP. | +| 17700026 | The specified bundle is disabled. | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let moduleName = 'entry'; +let extensionAbilityName = 'com.example.myapplication.extension'; +let metadataName = 'com.example.myapplication.metadata'; + +try { + let data = bundleManager.getProfileByExtensionAbilitySync(moduleName, extensionAbilityName); + hilog.info(0x0000, 'testTag', 'getProfileByExtensionAbilitySync successfully. Data: %{public}s', JSON.stringify(data)); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbilitySync failed. Cause: %{public}s', err.message); +} + +try { + let data = bundleManager.getProfileByExtensionAbilitySync(moduleName, extensionAbilityName, metadataName); + hilog.info(0x0000, 'testTag', 'getProfileByExtensionAbilitySync successfully. Data: %{public}s', JSON.stringify(data)); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbilitySync failed. Cause: %{public}s', err.message); +} +``` + ### bundleManager.getPermissionDef getPermissionDef(permissionName: string, callback: AsyncCallback\<[PermissionDef](js-apis-bundleManager-permissionDef.md)>): void; @@ -2767,6 +3205,52 @@ try { } ``` +### bundleManager.getPermissionDefSync + +getPermissionDefSync(permissionName: string): [PermissionDef](js-apis-bundleManager-permissionDef.md); + +以同步方法根据给定的permissionName获取权限定义结构体PermissionDef信息。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ------ | ---- | -------------- | +| permissionName | string | 是 | 表示权限参数名。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | ------------------------------------------ | +|[PermissionDef](js-apis-bundleManager-permissionDef.md) | PermissionDef对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------- | +| 17700006 | The specified permission is not found. | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let permissionName = "ohos.permission.GET_BUNDLE_INFO"; +try { + let PermissionDef = bundleManager.getPermissionDefSync(permission); + hilog.info(0x0000, 'testTag', 'getPermissionDefSync successfully. Data: %{public}s', JSON.stringify(PermissionDef)); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getPermissionDefSync failed. Cause: %{public}s', err.message); +} +``` + ### bundleManager.getAbilityLabel getAbilityLabel(bundleName: string, moduleName: string, abilityName: string, callback: AsyncCallback\): void; @@ -2880,6 +3364,60 @@ try { } ``` +### bundleManager.getAbilityLabelSync + +getAbilityLabelSync(bundleName: string, moduleName: string, abilityName: string): string; + +以同步的方法获取指定bundleName、moduleName和abilityName的label。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Resource + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ------------------------- | +| bundleName | string | 是 | 表示应用程序的bundleName。 | +| moduleName | string | 是 | 表示应用程序的moduleName。 | +| abilityName | string | 是 | 表示应用程序的abilityName。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ----------------------------------- | +| string | 指定组件的Lablel值。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------- | +| 17700001 | The specified bundleName is not found. | +| 17700002 | The specified moduleName is not found. | +| 17700003 | The specified abilityName is not found. | +| 17700026 | The specified bundle is disabled. | +| 17700029 | The specified ability is disabled. | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let bundleName = 'com.example.myapplication'; +let moduleName = 'entry'; +let abilityName = 'EntryAbility'; + +try { + let abilityLabel = bundleManager.getAbilityLabelSync(bundleName, moduleName, abilityName); + hilog.info(0x0000, 'testTag', 'getAbilityLabelSync successfully. Data: %{public}s', abilityLabel); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAbilityLabelSync failed. Cause: %{public}s', err.message); +} +``` ### bundleManager.getApplicationInfoSync @@ -3423,6 +3961,64 @@ try { } ``` +### bundleManager.getAppProvisionInfoSync10+ + +getAppProvisionInfoSync(bundleName: string, userId?: number): AppProvisionInfo; + +以同步方法根据bundleName和userId获取应用的provision配置文件信息并返回结果。 + +**系统接口:** 此接口为系统接口 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleName | string | 是 | 指定的bundleName。 | +| userId | number | 否 | 表示用户ID,默认值:调用方所在用户,取值范围:大于等于0,可以通过接口[getOsAccountLocalId](js-apis-osAccount.md#getosaccountlocalid9)获取当前设备上的用户ID。 | + + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | ----------------------------------- | +| [AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md) | AppProvisionInfo对象,返回应用的provision配置文件信息。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found. | +| 17700004 | The specified user ID is not found. | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let bundleName = "com.ohos.myapplication"; +let userId = 100; + +try { + let data = bundleManager.getAppProvisionInfoSync(bundleName); + hilog.info(0x0000, 'testTag', 'getAppProvisionInfoSync successfully. Data: %{public}s', JSON.stringify(data)); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAppProvisionInfoSync failed. Cause: %{public}s', err.message); +} + +try { + let data = bundleManager.getAppProvisionInfoSync(bundleName, userId); + hilog.info(0x0000, 'testTag', 'getAppProvisionInfoSync successfully. Data: %{public}s', JSON.stringify(data)); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAppProvisionInfoSync failed. Cause: %{public}s', err.message); +} +``` + ### bundleManager.getSpecifiedDistributionType10+ getSpecifiedDistributionType(bundleName: string): string; diff --git a/zh-cn/application-dev/reference/apis/js-apis-call.md b/zh-cn/application-dev/reference/apis/js-apis-call.md index a0b3c7d0e44d160275cef852b1276dc895058957..61010d4eeb9553e1ebcd9435739422c27a9eb7ac 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-call.md +++ b/zh-cn/application-dev/reference/apis/js-apis-call.md @@ -2821,7 +2821,7 @@ call.off('mmiCodeResult', data => { ## call.on('audioDeviceChange')10+ -on\(type: 'audioDeviceChange', callback: Callback\\): void +on\(type: 'audioDeviceChange', callback: Callback\\): void 订阅通话音频设备切换事件。使用callback异步回调。 @@ -2836,7 +2836,7 @@ on\(type: 'audioDeviceChange', callback: Callback\\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------- | ---- | --------------------------------------------------- | | type | string | 是 | 通话音频设备发生变化,参数固定为'audioDeviceChange'。 | -| callback | Callback<[AudioDeviceInfo](#audiodeviceinfo10)> | 是 | 回调函数。 | +| callback | Callback<[AudioDeviceCallbackInfo](#audiodevicecallbackinfo10)> | 是 | 回调函数。 | **错误码:** @@ -2863,7 +2863,7 @@ call.on('audioDeviceChange', data => { ## call.off('audioDeviceChange')10+ -off\(type: 'audioDeviceChange', callback?: Callback\\): void +off\(type: 'audioDeviceChange', callback?: Callback\\): void 取消订阅audioDeviceChange事件。使用callback异步回调。 @@ -2878,7 +2878,7 @@ off\(type: 'audioDeviceChange', callback?: Callback\\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------------------------- | ---- | --------------------------------------------------- | | type | string | 是 | 通话音频设备发生变化,参数固定为'audioDeviceChange'。 | -| callback | Callback<[AudioDeviceInfo](#audiodeviceinfo10)> | 否 | 回调函数。不填该参数将不会收到取消订阅的处理结果。 | +| callback | Callback<[AudioDeviceCallbackInfo](#audiodevicecallbackinfo10)> | 否 | 回调函数。不填该参数将不会收到取消订阅的处理结果。 | **错误码:** @@ -4978,7 +4978,7 @@ IP多媒体系统调用模式。 | DEVICE_WIRED_HEADSET | 2 | 有线耳机设备 | | DEVICE_BLUETOOTH_SCO | 3 | 蓝牙SCO设备 | -## AudioDeviceInfo10+ +## AudioDeviceCallbackInfo10+ 音频设备信息。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-camera.md b/zh-cn/application-dev/reference/apis/js-apis-camera.md index bc142a89e0bc30656e500e536e519716e6778ee3..5dade7559397f5b961c4ac947664ff7e8ad98998 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-camera.md +++ b/zh-cn/application-dev/reference/apis/js-apis-camera.md @@ -164,60 +164,62 @@ let modeManager = camera.getModeManager(context); 相机模式。 +**系统接口:** 此接口为系统接口。 + **系统能力:** SystemCapability.Multimedia.Camera.Core | 名称 | 值 | 说明 | | ----------------| ---- | ---------| -| NORMAL | 0 | 普通模式 | -| CAPTURE | 1 | 拍照模式 | -| VIDEO | 2 | 录像模式 | -| PORTRAIT | 3 | 人像模式 | -| NIGHT | 4 | 夜景模式 | -| PROFESSIONAL | 5 | 专业模式 | -| SLOW_MOTION | 6 | 慢动作模式| +| PORTRAIT | 1 | 人像模式 | ## FilterType 滤镜类型。 +**系统接口:** 此接口为系统接口。 + **系统能力:** SystemCapability.Multimedia.Camera.Core | 名称 | 值 | 说明 | | ----------------| ---- | ---------| -| NONE | 0 | 原图 | -| CLASSIC | 1 | 经典 | -| DAWN | 2 | 晨光 | -| PURE | 3 | 清纯 | -| GREY | 4 | 灰调 | -| NATURAL | 5 | 自然 | -| MORI | 6 | 森系 | -| FAIR | 7 | 白皙 | -| PINK | 8 | 粉调 | +| NONE | 0 | 原图。 | +| CLASSIC | 1 | 经典。 | +| DAWN | 2 | 晨光。 | +| PURE | 3 | 清纯。 | +| GREY | 4 | 灰调。 | +| NATURAL | 5 | 自然。 | +| MORI | 6 | 森系。 | +| FAIR | 7 | 白皙。 | +| PINK | 8 | 粉调。 | ## PortraitEffect 人像效果类型。 +**系统接口:** 此接口为系统接口。 + **系统能力:** SystemCapability.Multimedia.Camera.Core | 名称 | 值 | 说明 | | ----------------| ---- | ---------| -| OFF | 0 | 关闭 | -| CIRCLES | 1 | 圆形 | +| OFF | 0 | 关闭。 | +| CIRCLES | 1 | 圆形。 | ## BeautyType 美颜类型。 +**系统接口:** 此接口为系统接口。 + **系统能力:** SystemCapability.Multimedia.Camera.Core | 名称 | 值 | 说明 | | ----------------| ---- | ---------| -| AUTO_TYPE | 0 | 自动 | -| SKIN_SMOOTH | 1 | 光滑 | -| FACE_SLENDER | 2 | 瘦脸 | -| SKIN_TONE | 3 | 肤色 | +| AUTO | 0 | 自动。 | +| SKIN_SMOOTH | 1 | 光滑。 | +| FACE_SLENDER | 2 | 瘦脸。 | +| SKIN_TONE | 3 | 肤色。 | ## CameraManager @@ -654,6 +656,27 @@ cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { }) ``` +### off('cameraStatus') + +off(type: 'cameraStatus', callback?: AsyncCallback\): void + +相机设备状态注销回调,通过注销回调函数取消获取相机的状态变化。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -----------------| ---- | --------- | +| type | string | 是 | 监听事件,固定为'cameraStatus'。cameraManager对象获取成功后可监听。 | +| callback | AsyncCallback\<[CameraStatusInfo](#camerastatusinfo)\> | 否 | 可选参数,有表明匹配on接口callback。 | | + +**示例:** + +```js +cameraManager.off('cameraStatus') +``` + ### on('cameraMute') on(type: 'cameraMute', callback: AsyncCallback\): void @@ -679,6 +702,33 @@ cameraManager.on('cameraMute', (err, curMuetd) => { }) ``` +### off('cameraMute') + +off(type: 'cameraMute', callback?: AsyncCallback\): void + +禁用回调,通过注销注册回调函数获取相机禁用状态变化。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------- | ---- | --------- | +| type | string | 是 | 监听事件,固定为'cameraMute',系统相机摄像头开关,cameraManager对象获取成功后可监听。 | +| callback | AsyncCallback\ | 否 | 回调函数,可选参数,有表明匹配on接口callback。 | + +**示例:** + +```js +func(err, curMuetd) { + let isMuted = curMuetd; +} +cameraManager.on('cameraMute', func) +cameraManager.off('cameraMute', func) +``` + ### isPrelaunchSupported isPrelaunchSupported(camera: CameraDevice): boolean @@ -824,7 +874,7 @@ function getDeferredPreviewOutput(context: Context, previewProfile: camera.Profi ### getSupportedModes -getSupportedModes(camera: CameraDevice): Array\ +getSupportedModes(device: CameraDevice): Array\ 获取指定相机设备支持的模式列表,同步返回结果。 @@ -836,7 +886,7 @@ getSupportedModes(camera: CameraDevice): Array\ | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------- | ---- | ------------------- | -| camera | \<[CameraDevice](#cameradevice)> | 是 | 相机设备实例,通过[getSupportedCameras](#getsupportedcameras)接口获取。 | +| device | [CameraDevice](#cameradevice) | 是 | 相机设备实例,通过[getSupportedCameras](#getsupportedcameras)接口获取。 | **返回值:** @@ -853,7 +903,7 @@ let cameraModes = cameraManager.getSupportedModes(cameraDevices[0]); ### getSupportedOutputCapability -getSupportedOutputCapability(camera:CameraDevice, mode: CameraMode): CameraOutputCapability +getSupportedOutputCapability(device:CameraDevice, mode: CameraMode): CameraOutputCapability 获取指定模式下相机设备支持的输出能力,同步返回结果。 @@ -865,7 +915,7 @@ getSupportedOutputCapability(camera:CameraDevice, mode: CameraMode): CameraOutpu | 参数名 | 类型 | 必填 | 说明 | | ------------ |--------------------------------------------------------------- | -- | -------------------------- | -| cameraDevice | [CameraDevice](#cameradevice) | 是 | 相机设备,通过[getSupportedCameras](#getsupportedcameras)接口获取。 | +| device | [CameraDevice](#cameradevice) | 是 | 相机设备,通过[getSupportedCameras](#getsupportedcameras)接口获取。 | | mode | [CameraMode](#cameramode) | 是 | 指定模式,通过[getSupportedModes](#getsupportedmodes)接口获取。 | **返回值:** @@ -1207,6 +1257,28 @@ cameraInput.on('error', cameraDevice, (error) => { }) ``` +### off('error') + +off(type: 'error', camera:CameraDevice, callback?: ErrorCallback): void + +注销监听CameraInput的错误事件。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------- | --- | ------------------------------------------- | +| type | string | 是 | 监听事件,固定为'error',CameraInput对象创建成功可监听。相机设备出错情况下可触发该事件并返回结果,比如(设备不可用或者冲突等返回对应错误信息) | +| cameraDevice | [CameraDevice](#cameradevice) | 是 | CameraDevice对象。 | +| callback | ErrorCallback | 否 | 回调函数,可选,有就是匹配on('error') callback | + +**示例:** + +```js +cameraInput.off('error', cameraDevice) +``` + ## FlashMode 枚举,闪光灯模式。 @@ -2615,7 +2687,7 @@ try { ``` ### getSupportedFilters -getSupportedFilters(): Array\ +getSupportedFilters(): Array\ 获取当前支持的滤镜效果列表。 @@ -2629,6 +2701,14 @@ getSupportedFilters(): Array\ | ---------- | ----------------------------- | | Array\ | 返回支持的滤镜效果列表。 | +**错误码:** + +以下错误码的详细介绍请参见[Camera错误码](../errorcodes/errorcode-camera.md)。 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -2636,7 +2716,7 @@ let FilterTypes = captureSession.getSupportedFilters(); ``` ### setFilter -setFilter(filter: FilterType): void +setFilter(filter: number): void 设置滤镜效果。 @@ -2648,7 +2728,16 @@ setFilter(filter: FilterType): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------| ---- | ---------------------| -| filter | [FilterType](#filtertype) | 是 | 当前用户设置的滤镜类型。 | +| filter | [number](#filtertype) | 是 | 当前用户设置的滤镜类型。 | + +**错误码:** + +以下错误码的详细介绍请参见[Camera错误码](../errorcodes/errorcode-camera.md)。 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400101 | Parameter missing or parameter type incorrect. | +| 7400103 | Session not config. | **示例:** @@ -2673,7 +2762,15 @@ if (!FilterTypes.empty()) { | 类型 | 说明 | | ---------- | ----------------------------| -| [FilterType](#filtertype)| 已设置的滤镜效果。可查阅[FilterType](#filtertype)。| +| [number](#filtertype)| 已设置的滤镜效果。可查阅[FilterType](#filtertype)。| + +**错误码:** + +以下错误码的详细介绍请参见[Camera错误码](../errorcodes/errorcode-camera.md)。 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | **示例:** @@ -2682,7 +2779,7 @@ let FilterType = captureSession.getFilter(); ``` ### getSupportedBeautyTypes -getSupportedBeautyTypes(): Array +getSupportedBeautyTypes(): Array<[BeautyType](#beautytype)> 获取当前支持的美颜效果列表。 @@ -2694,19 +2791,29 @@ getSupportedBeautyTypes(): Array | 类型 | 说明 | | ---------- | ----------------------------- | -| Array\| 返回当前支持的美颜效果列表。 | +| Array\<[BeautyType](#beautytype)\>| 返回当前支持的美颜效果列表。 | + +**错误码:** + +以下错误码的详细介绍请参见[Camera错误码](../errorcodes/errorcode-camera.md)。 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | **示例:** ```js let FilterTypes = captureSession.getSupportedBeautyTypes(); ``` -### getSupportedBeautyRanges +### getSupportedBeautyRange -getSupportedBeautyRanges(type: BeautyType): Array +getSupportedBeautyRange(type: BeautyType): Array 获取指定美颜效果的范围值。 +**系统接口:** 此接口为系统接口。 + **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** @@ -2721,12 +2828,20 @@ getSupportedBeautyRanges(type: BeautyType): Array | ---------- | ----------------------------- | | Array\ | 当前美颜类型所支持的美颜强度。 | +**错误码:** + +以下错误码的详细介绍请参见[Camera错误码](../errorcodes/errorcode-camera.md)。 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js let beautyTypes = captureSession.getSupportedBeautyTypes(); if (!beautyTypes.empty()) { - let nums = captureSession.getSupportedBeautyRanges(beautyTypes[0]); + let nums = captureSession.getSupportedBeautyRange(beautyTypes[0]); } ``` @@ -2744,8 +2859,16 @@ setBeauty(type: BeautyType, value: number): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------| ---- | --------------------- | -| type | [BeautyType](#beautytype) | 是 | 美颜类型 | -| value | [number] | 是 | 美颜强度,通过[getSupportedBeautyRanges](#getsupportedbeautyranges)接口获取。| +| type | [BeautyType](#beautytype) | 是 | 美颜类型 | +| value | number | 是 | 美颜强度,通过[getSupportedBeautyRange](#getsupportedbeautyrange)接口获取。| + +**错误码:** + +以下错误码的详细介绍请参见[Camera错误码](../errorcodes/errorcode-camera.md)。 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | **示例:** @@ -2753,7 +2876,7 @@ setBeauty(type: BeautyType, value: number): void let beautyTypes = captureSession.getSupportedBeautyTypes(); let beautyLevels; if (!beautyTypes.empty()) { - beautyLevels = captureSession.getSupportedBeautyRanges(beautyTypes[0]); + beautyLevels = captureSession.getSupportedBeautyRange(beautyTypes[0]); } if (!beautyTypes.empty() && beautyLevels.empty()) { captureSession.setBeauty(beautyTypes[0], beautyLevels[0]); @@ -2779,7 +2902,15 @@ getBeauty(type: BeautyType): number **返回值:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------- | ---- | --------------------- | -| value | [number] | 是 | 美颜强度 | +| value | number | 是 | 美颜强度 | + +**错误码:** + +以下错误码的详细介绍请参见[Camera错误码](../errorcodes/errorcode-camera.md)。 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | **示例:** @@ -2787,7 +2918,7 @@ getBeauty(type: BeautyType): number let BeautyTypes = captureSession.getSupportedBeautyTypes(); let beautyLevels; if (!BeautyTypes.empty()) { - beautyLevels = captureSession.getSupportedBeautyRanges(BeautyTypes[0]); + beautyLevels = captureSession.getSupportedBeautyRange(BeautyTypes[0]); } if (!BeautyTypes.empty() && beautyLevels.empty()) { captureSession.setBeauty(BeautyTypes[0], beautyLevels[0]); @@ -2818,6 +2949,27 @@ captureSession.on('focusStateChange', (err, focusState) => { }) ``` +### off('focusStateChange') + +off(type: 'focusStateChange', callback?: AsyncCallback\): void + +注销监听相机聚焦的状态变化。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------- | ---- | ------------------------ | +| type | string | 是 | 监听事件,固定为'focusStateChange',session 创建成功可监听。| +| callback | AsyncCallback\<[FocusState](#focusstate)\> | 否 | 回调函数,可选 | + +**示例:** + +```js +captureSession.off('focusStateChange') +``` + ### on('error') on(type: 'error', callback: ErrorCallback): void @@ -2840,13 +2992,34 @@ captureSession.on('error', (error) => { console.log(`Capture session error code: ${error.code}`); }) ``` + +### off('error') + +off(type: 'error', callback?: ErrorCallback): void + +监听拍照会话的错误事件,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------ | +| type | string | 是 | 监听事件,固定为'error',session创建成功之后可监听该接口。 | +| callback | ErrorCallback| 否 | 回调函数,可选 | + +**示例:** + +```js +captureSession.off('error') +``` ## PortraitSession 继承自[CaptureSession](#capturesession),用于设置人像模式的参数。 ### getSupportedPortraitEffects -getSupportedPortraitEffects(): Array +getSupportedPortraitEffects(): Array<[PortraitEffect](#portraiteffect)> 获取支持的人像虚化效果列表。 @@ -2860,6 +3033,14 @@ getSupportedPortraitEffects(): Array | ----------------------------------------------- | ---------------------------- | | Array<[PortraitEffect](#portraiteffect) > | 支持的人像虚化效果列表。 | +**错误码:** + +以下错误码的详细介绍请参见[Camera错误码](../errorcodes/errorcode-camera.md)。 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -2881,6 +3062,14 @@ setPortraitEffect(effect: PortraitEffect): void | ------------ |--------------------------------------------------------------- | -- | -------------------------- | | effect | [PortraitEffect](#portraiteffect) | 是 | 人像虚化效果,通过[getSupportedPortraitEffects](#getsupportedportraiteffects)接口获取。 | +**错误码:** + +以下错误码的详细介绍请参见[Camera错误码](../errorcodes/errorcode-camera.md)。 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | + **示例:** ```js @@ -2905,6 +3094,13 @@ getPortraitEffect(): PortraitEffect | ----------------------------------------------- | ---------------------------- | | [PortraitEffect](#portraiteffect) | 当前设置的人像虚化效果。 | +**错误码:** + +以下错误码的详细介绍请参见[Camera错误码](../errorcodes/errorcode-camera.md)。 + +| 错误码ID | 错误信息 | +| --------------- | --------------- | +| 7400103 | Session not config. | **示例:** @@ -3128,6 +3324,27 @@ previewOutput.on('frameStart', () => { }) ``` +### off('frameStart') + +off(type: 'frameStart', callback?: AsyncCallback\): void + +注销监听预览帧启动。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | --------------------------------------- | +| type | string | 是 | 监听事件,固定为'frameStart',previewOutput创建成功可监听。 | +| callback | AsyncCallback\ | 否 | 回调函数,可选 | + +**示例:** + +```js +previewOutput.off('frameStart') +``` + ### on('frameEnd') on(type: 'frameEnd', callback: AsyncCallback\): void @@ -3151,6 +3368,27 @@ previewOutput.on('frameEnd', () => { }) ``` +### off('frameEnd') + +off(type: 'frameEnd', callback?: AsyncCallback\): void + +注销监听预览帧结束。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------------------- | +| type | string | 是 | 监听事件,固定为'frameEnd',previewOutput创建成功可监听。 | +| callback | AsyncCallback\ | 否 | 回调函数,可选 | + +**示例:** + +```js +previewOutput.off('frameEnd') +``` + ### on('error') on(type: 'error', callback: ErrorCallback): void @@ -3174,6 +3412,27 @@ previewOutput.on('error', (previewOutputError) => { }) ``` +### off('error') + +off(type: 'error', callback?: ErrorCallback): void + +注销监听预览输出的错误事件。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------| ---- | ------------------------ | +| type | string | 是 | 监听事件,固定为'error',previewOutput创建成功可监听。| +| callback | ErrorCallback | 否 | 回调函数,可选 | + +**示例:** + +```js +previewOutput.off('error') +``` + ### addDeferredSurface addDeferredSurface(surfaceId: string): void @@ -3548,6 +3807,27 @@ photoOutput.on('captureStart', (err, captureId) => { }) ``` +### off('captureStart') + +off(type: 'captureStart', callback?: AsyncCallback\): void + +注销监听拍照开始。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | ------------------------------------------ | +| type | string | 是 | 监听事件,固定为'captureStart',photoOutput创建成功后可监听 | +| callback | AsyncCallback\ | 否 | 可选。 | + +**示例:** + +```js +photoOutput.off('captureStart') +``` + ### on('frameShutter') on(type: 'frameShutter', callback: AsyncCallback\): void @@ -3572,6 +3852,27 @@ photoOutput.on('frameShutter', (err, frameShutterInfo) => { }) ``` +### off('frameShutter') + +off(type: 'frameShutter', callback?: AsyncCallback\): void + +注销监听拍照帧输出捕获。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------- | --- | ------------------------------------ | +| type | string | 是 | 监听事件,固定为'frameShutter',photoOutput创建成功后可监听。 | +| callback | AsyncCallback\<[FrameShutterInfo](#frameshutterinfo)\> | 否 | 回调函数,可选。 | + +**示例:** + +```js +photoOutput.off('frameShutter') +``` + ### on('captureEnd') on(type: 'captureEnd', callback: AsyncCallback\): void @@ -3596,6 +3897,27 @@ photoOutput.on('captureEnd', (err, captureEndInfo) => { }) ``` +### off('captureEnd') + +off(type: 'captureEnd', callback?: AsyncCallback\): void + +注销监听拍照结束。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------- | ---- | ---------------------------------------- | +| type | string | 是 | 监听事件,固定为'captureEnd',photoOutput创建成功后可监听。 | +| callback | AsyncCallback\<[CaptureEndInfo](#captureendinfo)\> | 否 | 回调函数,可选。 | + +**示例:** + +```js +photoOutput.off('captureEnd') +``` + ### on('error') on(type: 'error', callback: ErrorCallback): void @@ -3619,6 +3941,27 @@ photoOutput.on('error', (error) => { }) ``` +### off('error') + +off(type: 'error', callback?: ErrorCallback): void + +注销监听拍照输出发生错误。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------- | ---- | ----------------------------------- | +| type | string | 是 | 监听事件,固定为'error',photoOutput创建成功后可监听。 | +| callback | ErrorCallback | 否 | 回调函数,可选 | + +**示例:** + +```js +photoOutput.off('error') +``` + ### isQuickThumbnailSupported isQuickThumbnailSupported(): boolean @@ -3643,7 +3986,7 @@ isQuickThumbnailSupported(): boolean | 错误码ID | 错误信息 | | --------------- | --------------- | -| 7400101 | Parameter missing or parameter type incorrect | +| 7400104 | session is not running | **示例:** @@ -3689,7 +4032,7 @@ enableQuickThumbnail(enabled: boolean): void | 错误码ID | 错误信息 | | --------------- | --------------- | -| 7400101 | Parameter missing or parameter type incorrect | +| 7400104 | session is not running | **示例:** @@ -3731,7 +4074,57 @@ on(type: 'quickThumbnail', callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------- | ---- | ----------------------------------- | | type | string | 是 | 监听事件,固定为'quickThumbnail'。 | -| callback | AsyncCallback\<[image.PixelMap](js-apis-image.md#pixelmap7)> | 回调返回PixelMap。 | +| callback | AsyncCallback\<[image.PixelMap](js-apis-image.md#pixelmap7)> | 是 | 回调返回PixelMap。 | + +**示例:** + +```js +import camera from '@ohos.multimedia.camera' + +this.cameraManager = camera.getCameraManager(globalThis.abilityContext); +let cameras = this.cameraManager.getSupportedCameras() +// 创建CaptureSession实例 +this.captureSession = await this.cameraManager.createCaptureSession() +// 开始配置会话 +await this.captureSession.beginConfig() +// 把CameraInput加入到会话 +this.cameraInput = await this.cameraManager.createCameraInput(cameras[0]) +await this.cameraInput.open() +await this.captureSession.addInput(this.cameraInput) +// 把PhotoOutPut加入到会话 +this.photoOutPut = await this.cameraManager.createPhotoOutput(photoProfile, surfaceId) +await this.captureSession.addOutput(this.photoOutPut) +boolean isSupported = this.photoOutPut.isQuickThumbnailSupported() +if (isSupported) { + // 使能快速缩略图 + this.photoOutPut.enableQuickThumbnail(true) +} +this.photoOutPut.on('quickThumbnail', (err, pixelmap) => { + if (err || pixelmap === undefined) { + Logger.error(this.tag, 'photoOutPut on thumbnail failed ') + return + } + // 显示或保存pixelmap + this.showOrSavePicture(pixelmap) +}) +``` + +### off('quickThumbnail') + +off(type: 'quickThumbnail', callback?: AsyncCallback\): void + +注销监听快速缩略图输出事件。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------- | ---- | ----------------------------------- | +| type | string | 是 | 监听事件,固定为'quickThumbnail'。 | +| callback | AsyncCallback\<[image.PixelMap](js-apis-image.md#pixelmap7)> | 否 | 可选。 | **示例:** @@ -3764,6 +4157,7 @@ this.photoOutPut.on('quickThumbnail', (err, pixelmap) => { // 显示或保存pixelmap this.showOrSavePicture(pixelmap) }) +this.photoOutPut.off('quickThumbnail') ``` ## FrameShutterInfo @@ -3999,6 +4393,27 @@ videoOutput.on('frameStart', () => { }) ``` +### off('frameStart') + +off(type: 'frameStart', callback?: AsyncCallback\): void + +注销监听录像开始。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ----------------------------------------- | +| type | string | 是 | 监听事件,固定为'frameStart',videoOutput创建成功后可监听。 | +| callback | AsyncCallback\ | 否 | 回调函数,可选 | + +**示例:** + +```js +videoOutput.off('frameStart') +``` + ### on('frameEnd') on(type: 'frameEnd', callback: AsyncCallback\): void @@ -4022,6 +4437,27 @@ videoOutput.on('frameEnd', () => { }) ``` +### off('frameEnd') + +off(type: 'frameEnd', callback?: AsyncCallback\): void + +注销监听录像结束。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------------------------ | +| type | string | 是 | 监听事件,固定为'frameEnd',videoOutput创建成功后可监听 。 | +| callback | AsyncCallback\ | 否 | 回调函数,可选 | + +**示例:** + +```js +videoOutput.off('frameEnd') +``` + ### on('error') on(type: 'error', callback: ErrorCallback): void @@ -4045,6 +4481,27 @@ videoOutput.on('error', (error) => { }) ``` +### off('error') + +off(type: 'error', callback?: ErrorCallback): void + +注销监听录像输出发生错误。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------- | ---- | -------------------------------------- | +| type | string | 是 | 监听事件,固定为'error',videoOutput创建成功后可监听。 | +| callback | ErrorCallback | 否 | 回调函数,可选 | + +**示例:** + +```js +videoOutput.off('error') +``` + ## MetadataOutput metadata流。继承[CameraOutput](#cameraoutput) @@ -4190,6 +4647,27 @@ metadataOutput.on('metadataObjectsAvailable', (err, metadataObjectArr) => { }) ``` +### off('metadataObjectsAvailable') + +off(type: 'metadataObjectsAvailable', callback?: AsyncCallback\\>): void + +注销监听检测到的metadata对象。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------- | ---- | ------------------------------------ | +| type | string | 是 | 监听事件,固定为'metadataObjectsAvailable',metadataOutput创建成功后可监听。 | +| callback | Callback\\> | 否 | 回调函数,可选。 | + +**示例:** + +```js +metadataOutput.off('metadataObjectsAvailable') +``` + ### on('error') on(type: 'error', callback: ErrorCallback): void @@ -4213,6 +4691,27 @@ metadataOutput.on('error', (metadataOutputError) => { }) ``` +### off('error') + +off(type: 'error', callback?: ErrorCallback): void + +注销监听metadata流的错误。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------- | ---- | --------------------------------------- | +| type | string | 是 | 监听事件,固定为'error',metadataOutput创建成功后可监听。 | +| callback | ErrorCallback | 否 | 回调函数,可选 | + +**示例:** + +```js +metadataOutput.off('error') +``` + ## MetadataObjectType 枚举,metadata流。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md b/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md index cf45a3b3f424c03c29c3c37a1d0ef39090d3813e..372c407d57f1c0ef3ff7e73222d5c7e67e587947 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md @@ -11,6 +11,8 @@ ```ts import CommonEvent from '@ohos.commonEvent'; +import CommonEventManager from '@ohos.commonEventManager'; +import Base from '@ohos.base'; ``` ## Support @@ -41,7 +43,7 @@ publish(event: string, callback: AsyncCallback\): void ```ts //发布公共事件回调 -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err.code) { console.error(`publish failed, code is ${err.code}`); } else { @@ -77,14 +79,14 @@ publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\ ```ts //公共事件相关信息 -let options = { +let options:CommonEventManager.CommonEventPublishData = { code: 0, //公共事件的初始代码 data: "initial data",//公共事件的初始数据 isOrdered: true //有序公共事件 } //发布公共事件回调 -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err.code) { console.error(`publish failed, code is ${err.code}`); } else { @@ -121,7 +123,7 @@ publishAsUser(event: string, userId: number, callback: AsyncCallback\): vo ```ts // 发布公共事件回调 -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err.code) { console.error(`publishAsUser failed, code is ${err.code}`); } else { @@ -163,14 +165,14 @@ publishAsUser(event: string, userId: number, options: CommonEventPublishData, ca ```ts // 公共事件相关信息 -let options = { +let options:CommonEventManager.CommonEventPublishData = { code: 0, // 公共事件的初始代码 data: "initial data",// 公共事件的初始数据 } // 发布公共事件回调 -function publishCB(err) { - if (err.code) { +function publishCB(err:Base.BusinessError) { + if (err.code) { console.error(`publishAsUser failed, code is ${err.code}`); } else { console.info("publishAsUser"); @@ -206,15 +208,15 @@ createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallbac ```ts -let subscriber; // 用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 +let subscriber:CommonEventManager.CommonEventSubscriber; // 用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 // 订阅者信息 -let subscribeInfo = { - events: ["event"] +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { + events: ["event"] }; // 创建订阅者回调 -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if (err.code) { console.error(`createSubscriber failed, code is ${err.code}`); } else { @@ -252,18 +254,18 @@ createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\ { +CommonEvent.createSubscriber(subscribeInfo).then((commonEventSubscriber:CommonEventManager.CommonEventSubscriber) => { console.info("createSubscriber"); subscriber = commonEventSubscriber; -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`createSubscriber failed, code is ${err.code}`); }); ``` @@ -289,15 +291,15 @@ subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\): **示例:** ```ts -let subscriber; // 用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 +let subscriber:CommonEventManager.CommonEventSubscriber; // 用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 // 订阅者信息 -let subscribeInfo = { - events: ["event"] +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { + events: ["event"] }; // 订阅公共事件回调 -function subscribeCB(err, data) { +function subscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) { if (err.code) { console.error(`subscribe failed, code is ${err.code}`); } else { @@ -359,20 +361,20 @@ function subscribeCB(err, data) { } // 创建订阅者回调 -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if (err.code) { console.error(`createSubscriber failed, code is ${err.code}`); } else { console.info("createSubscriber"); subscriber = commonEventSubscriber; - // 订阅公共事件 + // Subscribe to a common event. CommonEvent.subscribe(subscriber, subscribeCB); } } // 取消订阅公共事件回调 -function unsubscribeCB(err) { - if (err.code) { +function unsubscribeCB(err:Base.BusinessError) { + if (err.code) { console.error(`unsubscribe failed, code is ${err.code}`); } else { console.info("unsubscribe"); diff --git a/zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md b/zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md index 7cb58125b8042d6a8d188749c7fa6a6a1344c665..1f423c9c2441f4ba9240ca7d8c504c05aea1e554 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md @@ -10,6 +10,7 @@ ```ts import CommonEventManager from '@ohos.commonEventManager'; +import Base from '@ohos.base'; ``` ## Support @@ -48,8 +49,8 @@ publish(event: string, callback: AsyncCallback\): void ```ts //发布公共事件回调 -function publishCB(err) { - if (err) { +function publishCB(err:Base.BusinessError) { + if (err) { console.error(`publish failed, code is ${err.code}, message is ${err.message}`); } else { console.info("publish"); @@ -95,14 +96,14 @@ publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\ ```ts //公共事件相关信息 -let options = { +let options:CommonEventManager.CommonEventPublishData = { code: 0, //公共事件的初始代码 data: "initial data",//公共事件的初始数据 isOrdered: true //有序公共事件 } //发布公共事件回调 -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err) { console.error(`publish failed, code is ${err.code}, message is ${err.message}`); } else { @@ -151,7 +152,7 @@ publishAsUser(event: string, userId: number, callback: AsyncCallback\): vo ```ts //发布公共事件回调 -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err) { console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`); } else { @@ -205,13 +206,13 @@ publishAsUser(event: string, userId: number, options: CommonEventPublishData, ca ```ts //公共事件相关信息 -let options = { +let options:CommonEventManager.CommonEventPublishData = { code: 0, //公共事件的初始代码 data: "initial data",//公共事件的初始数据 } //发布公共事件回调 -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err) { console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`); } else { @@ -248,15 +249,15 @@ createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallbac **示例:** ```ts -let subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 +let subscriber:CommonEventManager.CommonEventSubscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 //订阅者信息 -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; //创建订阅者回调 -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if(!err) { console.info("createSubscriber"); subscriber = commonEventSubscriber; @@ -295,18 +296,18 @@ createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\ { +CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber:CommonEventManager.CommonEventSubscriber) => { console.info("createSubscriber"); subscriber = commonEventSubscriber; -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); }); @@ -341,15 +342,15 @@ subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\): **示例:** ```ts -let subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 +let subscriber:CommonEventManager.CommonEventSubscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 //订阅者信息 -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; //订阅公共事件回调 -function subscribeCB(err, data) { +function subscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) { if (err) { console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { @@ -423,7 +424,7 @@ function subscribeCB(err, data) { } } //创建订阅者回调 -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if (err) { console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); } else { @@ -438,7 +439,7 @@ function createCB(err, commonEventSubscriber) { } } //取消订阅公共事件回调 -function unsubscribeCB(err) { +function unsubscribeCB(err:Base.BusinessError) { if (err) { console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`); } else { @@ -493,7 +494,7 @@ removeStickyCommonEvent(event: string, callback: AsyncCallback\): void ```ts -CommonEventManager.removeStickyCommonEvent("sticky_event", (err) => { +CommonEventManager.removeStickyCommonEvent("sticky_event", (err:Base.BusinessError) => { if (err) { console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`); return; @@ -542,7 +543,7 @@ removeStickyCommonEvent(event: string): Promise\ ```ts CommonEventManager.removeStickyCommonEvent("sticky_event").then(() => { console.info(`Remove sticky event AsyncCallback success`); -}).catch ((err) => { +}).catch ((err:Base.BusinessError) => { console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`); }); ``` @@ -577,7 +578,7 @@ setStaticSubscriberState(enable: boolean, callback: AsyncCallback\): void; ```ts -CommonEventManager.setStaticSubscriberState(true, (err) => { +CommonEventManager.setStaticSubscriberState(true, (err:Base.BusinessError) => { if (!err) { console.info(`Set static subscriber state callback failed, err is null.`); return; @@ -627,7 +628,7 @@ setStaticSubscriberState(enable: boolean): Promise\; ```ts CommonEventManager.setStaticSubscriberState(false).then(() => { console.info(`Set static subscriber state promise success`); -}).catch ((err) => { +}).catch ((err:Base.BusinessError) => { console.info(`Set static subscriber state promise failed, errCode: ${err.code}, errMes: ${err.message}`); }); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-curve.md b/zh-cn/application-dev/reference/apis/js-apis-curve.md index 21cc66f6a3078b306be8e98bc585f5315b8b5dd0..fff376653d0a691788e8623a0bd2e880de014476 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-curve.md +++ b/zh-cn/application-dev/reference/apis/js-apis-curve.md @@ -316,7 +316,7 @@ interpolate(fraction: number): number ```ts import Curves from '@ohos.curves' -let curve = Curves.initCurve(Curve.EaseIn) // 创建一个默认先慢后快插值曲线 +let curveValue = Curves.initCurve(Curve.EaseIn) // 创建一个默认先慢后快插值曲线 let value: number = curve.interpolate(0.5) // 计算得到时间到一半时的插值 ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-DataShareResultSet.md b/zh-cn/application-dev/reference/apis/js-apis-data-DataShareResultSet.md index bbf4408ef4aa8b7484da6a233886af3b7253a3fb..19c48240cb78a981159e00814e80e34567f6c92f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-DataShareResultSet.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-DataShareResultSet.md @@ -22,8 +22,9 @@ import DataShareResultSet from '@ohos.data.DataShareResultSet'; ```ts import dataShare from '@ohos.data.dataShare'; import dataSharePredicates from '@ohos.data.dataSharePredicates' +import { BusinessError } from '@ohos.base' -let dataShareHelper; +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); await dataShare.createDataShareHelper(this.context, uri, (err, data) => { if (err != undefined) { @@ -36,12 +37,12 @@ await dataShare.createDataShareHelper(this.context, uri, (err, data) => { let columns = ["*"]; let da = new dataSharePredicates.DataSharePredicates(); -let resultSet; +let resultSet: DataShareResultSet; da.equalTo("name", "ZhangSan"); -dataShareHelper.query(uri, da, columns).then((data) => { +dataShareHelper.query(uri, da, columns).then((data: DataShareResultSet) => { console.info("query end, data : " + data); resultSet = data; -}).catch((err) => { +}).catch((err: BusinessError) => { console.error("query fail, error message : " + err); }); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-dataShare.md b/zh-cn/application-dev/reference/apis/js-apis-data-dataShare.md index 5b0f680eb5ee5e7c5bba9269c48c31769d67cd10..638af4c034f3dea509dacd760e97e39d3f8c7102 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-dataShare.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-dataShare.md @@ -52,7 +52,7 @@ createDataShareHelper(context: Context, uri: string, callback: AsyncCallback< import UIAbility from '@ohos.app.ability.UIAbility'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); -let dataShareHelper; +let dataShareHelper: dataShare.DataShareHelper; try { dataShare.createDataShareHelper(this.context, uri, (err, data) => { if (err !== undefined) { @@ -101,7 +101,7 @@ createDataShareHelper(context: Context, uri: string, options: DataShareHelperOpt import UIAbility from '@ohos.app.ability.UIAbility'; let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); -let dataShareHelper; +let dataShareHelper: dataShare.DataShareHelper; try { dataShare.createDataShareHelper(this.context, uri, {isProxy : true}, (err, data) => { if (err !== undefined) { @@ -154,14 +154,15 @@ createDataShareHelper(context: Context, uri: string, options?: DataShareHelperOp ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); -let dataShareHelper; +let dataShareHelper: dataShare.DataShareHelper; try { - dataShare.createDataShareHelper(this.context, uri, {isProxy : true}).then((data) => { + dataShare.createDataShareHelper(this.context, uri, {isProxy : true}).then((data: dataShare.DataShareHelper) => { console.info("createDataShareHelper succeed, data : " + data); dataShareHelper = data; - }). catch((err) => { + }). catch((err: BusinessError) => { console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); }); } catch (err) { @@ -269,7 +270,8 @@ on(type: 'dataChange', uri: string, callback: AsyncCallback<void>): void **示例:** ```ts -function onCallback() { +let dataShareHelper: dataShare.DataShareHelper; +let onCallback: () => void = (): void => { console.info("**** Observer on callback ****"); } let uri = ("datashare:///com.samples.datasharetest.DataShare"); @@ -295,8 +297,9 @@ off(type: 'dataChange', uri: string, callback?: AsyncCallback<void>): void **示例:** ```ts -function callback() { - console.info("**** Observer callback ****"); +let dataShareHelper: dataShare.DataShareHelper; +let callback: () => void = (): void => { + console.info("**** Observer on callback ****"); } let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.on("dataChange", uri, callback); @@ -330,12 +333,17 @@ addTemplate(uri: string, subscriberId: string, template: Template): void **示例:** ```ts +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); let subscriberId = '11'; -let template = { +let key1: string = "p1"; +let value1: string = "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true"; +let key2: string = "p2"; +let value2: string = "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false"; +let template: dataShare.Template = { predicates : { - "p1" : "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true", - "p2" : "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false", + key1 : value1, + key2 : value2, }, scheduler : "select remindTimer(time) from TBL00" } @@ -368,12 +376,17 @@ delTemplate(uri: string, subscriberId: string): void **示例:** ```ts +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); let subscriberId = '11'; -let template = { +let key1: string = "p1"; +let value1: string = "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true"; +let key2: string = "p2"; +let value2: string = "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false"; +let template: dataShare.Template = { predicates : { - "p1" : "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true", - "p2" : "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false", + key1 : value1, + key2 : value2, }, scheduler : "select remindTimer(time) from TBL00" } @@ -407,7 +420,10 @@ on(type: 'rdbDataChange', uris: Array<string>, templateId: TemplateId, cal **示例:** ```ts -function onCallback(err, node:dataShare.RdbDataChangeNode) { +import { BusinessError } from '@ohos.base' + +let dataShareHelper: dataShare.DataShareHelper; +let onCallback: (err: BusinessError, node: dataShare.RdbDataChangeNode) => void = (err: BusinessError, node:dataShare.RdbDataChangeNode): void => { console.info("onCallback " + JSON.stringify(node.uri)); console.info("onCallback " + JSON.stringify(node.templateId)); console.info("onCallback " + node.data.length); @@ -447,6 +463,7 @@ off(type: 'rdbDataChange', uris: Array<string>, templateId: TemplateId, ca **示例:** ```ts +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); let templateId:dataShare.TemplateId = {subscriberId:"11", bundleNameOfOwner:"com.acts.ohos.data.datasharetest"}; let result:Array = dataShareHelper.off("rdbDataChange", [uri], templateId); @@ -478,7 +495,10 @@ on(type: 'publishedDataChange', uris: Array<string>, subscriberId: string, **示例:** ```ts -function onPublishCallback(err, node:dataShare.PublishedDataChangeNode) { +import { BusinessError } from '@ohos.base' + +let dataShareHelper: dataShare.DataShareHelper; +let onPublishCallback: (err: BusinessError, node: dataShare.PublishedDataChangeNode) => void = (err: BusinessError, node:dataShare.PublishedDataChangeNode): void => { console.info("onPublishCallback node bundleName " + JSON.stringify(node.bundleName)); console.info("onPublishCallback node data size" + node.data.length); for (let i = 0; i < node.data.length; i++) { @@ -522,7 +542,10 @@ off(type: 'publishedDataChange', uris: Array<string>, subscriberId: string **示例:** ```ts -function offCallback(err, node:dataShare.PublishedDataChangeNode) { +import { BusinessError } from '@ohos.base' + +let dataShareHelper: dataShare.DataShareHelper; +let offCallback: (err: BusinessError, node: dataShare.PublishedDataChangeNode) => void = (err: BusinessError, node:dataShare.PublishedDataChangeNode): void => { console.info("**** Observer off callback ****"); } let uris:Array = ["city", "datashareproxy://com.acts.ohos.data.datasharetest/appInfo", "key2"]; @@ -558,10 +581,13 @@ publish(data: Array<PublishedItem>, bundleName: string, version: number, c **示例:** ```ts +import { BusinessError } from '@ohos.base' + +let dataShareHelper: dataShare.DataShareHelper; let arrayBuffer = new ArrayBuffer(1); let version = 1; let dataArray : Array = [{key:"key2", subscriberId:"11", data:arrayBuffer}]; -function publishCallback(err, result: Array) { +let publishCallback: (err: BusinessError, result: Array) => void = (err: BusinessError, result: Array): void => { console.info("publishCallback " + JSON.stringify(result)); } try { @@ -599,7 +625,10 @@ publish(data: Array<PublishedItem>, bundleName: string, callback: AsyncCal | 15700012 | The data area is not exist.| ```ts -function publishCallback(err, result: Array) { +import { BusinessError } from '@ohos.base' + +let dataShareHelper: dataShare.DataShareHelper; +let publishCallback: (err: BusinessError, result: Array) => void = (err: BusinessError, result: Array): void => { console.info("publishCallback " + JSON.stringify(result)); } let dataArray : Array = [ @@ -642,11 +671,12 @@ publish(data: Array<PublishedItem>, bundleName: string, version?: number): **示例:** ```ts -let dataArray : Array = [ +let dataShareHelper: dataShare.DataShareHelper; +let dataArray: Array = [ {key:"city", subscriberId:"11", data:"xian"}, {key:"datashareproxy://com.acts.ohos.data.datasharetest/appInfo", subscriberId:"11", data:"appinfo is just a test app"}, {key:"empty", subscriberId:"11", data:"nobody sub"}]; -let result: Array = dataShareHelper.publish(dataArray, "com.acts.ohos.data.datasharetest"); +let result: Promise> = dataShareHelper.publish(dataArray, "com.acts.ohos.data.datasharetest"); ``` ### getPublishedData10+ @@ -675,7 +705,10 @@ getPublishedData(bundleName: string, callback: AsyncCallback<Array<Publish **示例:** ```ts -function publishCallback(err, data: Array) { +import { BusinessError } from '@ohos.base' + +let dataShareHelper: dataShare.DataShareHelper; +let publishCallback: (err: BusinessError, data: Array) => void = (err: BusinessError, result: Array): void => { console.info("**** Observer publish callback ****"); } dataShareHelper.getPublishedData("com.acts.ohos.data.datasharetest", publishCallback); @@ -712,7 +745,8 @@ getPublishedData(bundleName: string): Promise<Array<PublishedItem>> **示例:** ```ts -let publishedData:Array = dataShareHelper.getPublishedData("com.acts.ohos.data.datasharetest"); +let dataShareHelper: dataShare.DataShareHelper; +let publishedData: Promise> = dataShareHelper.getPublishedData("com.acts.ohos.data.datasharetest"); ``` ### insert @@ -734,11 +768,20 @@ insert(uri: string, value: ValuesBucket, callback: AsyncCallback<number>): **示例:** ```ts +import { ValuesBucket } from '@ohos.data.ValuesBucket' + +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); -const valueBucket = { - "name": "rose", - "age": 22, - "salary": 200.5, +let key1: string = "name"; +let value1: string = "rose"; +let key2: string = "age"; +let value2: number = 22; +let key3: string = "salary"; +let value3: number = 200.5; +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, } try { dataShareHelper.insert(uri, valueBucket, (err, data) => { @@ -777,16 +820,26 @@ insert(uri: string, value: ValuesBucket): Promise<number> **示例:** ```ts +import { BusinessError } from '@ohos.base' +import { ValuesBucket } from '@ohos.data.ValuesBucket' + +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); -const valueBucket = { - "name": "rose1", - "age": 221, - "salary": 20.5, +let key1: string = "name"; +let value1: string = "rose1"; +let key2: string = "age"; +let value2: number = 21; +let key3: string = "salary"; +let value3: number = 20.5; +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, } try { - dataShareHelper.insert(uri, valueBucket).then((data) => { + dataShareHelper.insert(uri, valueBucket).then((data: number) => { console.info("insert succeed, data : " + data); - }). catch((err) => { + }). catch((err: BusinessError) => { console.error(`insert error: code: ${err.code}, message: ${err.message} `); }); } catch (err) { @@ -815,6 +868,7 @@ delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callbac ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); @@ -856,14 +910,16 @@ delete(uri: string, predicates: dataSharePredicates.DataSharePredicates): Promis ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import { BusinessError } from '@ohos.base' +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); try { - dataShareHelper.delete(uri, da).then((data) => { + dataShareHelper.delete(uri, da).then((data: number) => { console.info("delete succeed, data : " + data); - }). catch((err) => { + }). catch((err: BusinessError) => { console.error(`delete error: code: ${err.code}, message: ${err.message} `); }); } catch (err) { @@ -893,6 +949,7 @@ query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let columns = ["*"]; let da = new dataSharePredicates.DataSharePredicates(); @@ -936,15 +993,17 @@ query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import { BusinessError } from '@ohos.base' +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let columns = ["*"]; let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); try { - dataShareHelper.query(uri, da, columns).then((data) => { + dataShareHelper.query(uri, da, columns).then((data: DataShareResultSet) => { console.info("query succeed, rowCount : " + data.rowCount); - }). catch((err) => { + }). catch((err: BusinessError) => { console.error(`query error: code: ${err.code}, message: ${err.message} `); }); } catch (err) { @@ -973,15 +1032,22 @@ update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import { ValuesBucket } from '@ohos.data.ValuesBucket' +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -const va = { - "name": "roe1", - "age": 21, - "salary": 20.5, - +let key1: string = "name"; +let value1: string = "roe1" +let key2: string = "age"; +let value2: number = 21 +let key3: string = "salary"; +let value3: number = 20.5; +const va: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, } try { dataShareHelper.update(uri, da, va, (err, data) => { @@ -1022,20 +1088,28 @@ update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import { ValuesBucket } from '@ohos.data.ValuesBucket' +import { BusinessError } from '@ohos.base' +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -const va = { - "name": "roe1", - "age": 21, - "salary": 20.5, - +let key1: string = "name"; +let value1: string = "roe1" +let key2: string = "age"; +let value2: number = 21 +let key3: string = "salary"; +let value3: number = 20.5; +const va: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, } try { - dataShareHelper.update(uri, da, va).then((data) => { + dataShareHelper.update(uri, da, va).then((data: number) => { console.info("update succeed, data : " + data); - }). catch((err) => { + }). catch((err: BusinessError) => { console.error(`update error: code: ${err.code}, message: ${err.message} `); }); } catch (err) { @@ -1062,10 +1136,22 @@ batchInsert(uri: string, values: Array<ValuesBucket>, callback: AsyncCallb **示例:** ```ts +import { ValuesBucket } from '@ohos.data.ValuesBucket' + +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); -let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,}, - {"name": "roe12", "age": 21, "salary": 20.5,}, - {"name": "roe13", "age": 21, "salary": 20.5,}) +let key1: string = "name"; +let value11: string = "roe11" +let key2: string = "age"; +let value21: number = 21; +let key3: string = "salary"; +let value31: number = 20.5; +let valuesBucket1: ValuesBucket = { + key1: value11, + key2: value21, + key3: value31, +} +let vbs = new Array(valuesBucket1); try { dataShareHelper.batchInsert(uri, vbs, (err, data) => { if (err !== undefined) { @@ -1103,14 +1189,27 @@ batchInsert(uri: string, values: Array<ValuesBucket>): Promise<number&g **示例:** ```ts +import { ValuesBucket } from '@ohos.data.ValuesBucket' +import { BusinessError } from '@ohos.base' + +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); -let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,}, - {"name": "roe12", "age": 21, "salary": 20.5,}, - {"name": "roe13", "age": 21, "salary": 20.5,}) +let key1: string = "name"; +let value11: string = "roe11" +let key2: string = "age"; +let value21: number = 21; +let key3: string = "salary"; +let value31: number = 20.5; +let valuesBucket1: ValuesBucket = { + key1: value11, + key2: value21, + key3: value31, +} +let vbs = new Array(valuesBucket1); try { - dataShareHelper.batchInsert(uri, vbs).then((data) => { + dataShareHelper.batchInsert(uri, vbs).then((data: number) => { console.info("batchInsert succeed, data : " + data); - }). catch((err) => { + }). catch((err: BusinessError) => { console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); }); } catch (err) { @@ -1136,6 +1235,7 @@ normalizeUri(uri: string, callback: AsyncCallback<string>): void **示例:** ```ts +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.normalizeUri(uri, (err, data) => { if (err !== undefined) { @@ -1169,10 +1269,13 @@ normalizeUri(uri: string): Promise<string> **示例:** ```ts +import { BusinessError } from '@ohos.base' + +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); -dataShareHelper.normalizeUri(uri).then((data) => { +dataShareHelper.normalizeUri(uri).then((data: string) => { console.info("normalizeUri = " + data); -}).catch((err) => { +}).catch((err: BusinessError) => { console.info("normalizeUri failed, error message : " + err); }); ``` @@ -1195,6 +1298,7 @@ denormalizeUri(uri: string, callback: AsyncCallback<string>): void **示例:** ```ts +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.denormalizeUri(uri, (err, data) => { if (err !== undefined) { @@ -1228,10 +1332,13 @@ denormalizeUri(uri: string): Promise<string> **示例:** ```ts +import { BusinessError } from '@ohos.base' + +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); -dataShareHelper.denormalizeUri(uri).then((data) => { +dataShareHelper.denormalizeUri(uri).then((data: string) => { console.info("denormalizeUri = " + data); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error("denormalizeUri failed, error message : " + err); }); ``` @@ -1254,6 +1361,7 @@ notifyChange(uri: string, callback: AsyncCallback<void>): void **示例:** ```ts +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.notifyChange(uri, () => { console.info("***** notifyChange *****"); @@ -1283,6 +1391,7 @@ notifyChange(uri: string): Promise<void> **示例:** ```ts +let dataShareHelper: dataShare.DataShareHelper; let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.notifyChange(uri); ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md b/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md index fd257e428ceff0683c0e0a6fa0462f8284592904..1f8fd812f7db9e83f9d467e9c1ecaac8fe1f7286 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md @@ -587,7 +587,8 @@ class EntryAbility extends UIAbility { | 键类型 | 值类型 | | ------ | ----------------------- | -| string | [ValueType](#valuetype) | +| number | 主键的类型可以是number | +| string | 主键的类型可以是string。 | ## PRIKeyType10+ @@ -802,7 +803,8 @@ inDevices(devices: Array<string>): RdbPredicates > **说明:** > -> 其中devices通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> 其中devices通过调用[deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync)方法得到。 +数据库同步时调用Sync接口,需要在入参谓词中调用inDevices接口选择设备。如果不调用inDevices接口即默认连接组网内所有的设备。 **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core @@ -821,22 +823,20 @@ inDevices(devices: Array<string>): RdbPredicates **示例:** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; - +import deviceManager from '@ohos.distributedDeviceManager'; let dmInstance: deviceManager.DeviceManager = null; let deviceIds: Array = []; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); + +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); for (let i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].deviceId; + deviceIds[i] = devices[i].networkId; } -}) - +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} + let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.inDevices(deviceIds); ``` @@ -848,6 +848,7 @@ inAllDevices(): RdbPredicates 同步分布式数据库时连接到组网内所有的远程设备。 + **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: @@ -2850,7 +2851,7 @@ remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: A > **说明:** > -> 其中device通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> 其中device通过调用[deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync)方法得到。 **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core @@ -2875,19 +2876,17 @@ remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: A **示例:** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; +import deviceManager from '@ohos.distributedDeviceManager'; let dmInstance: deviceManager.DeviceManager = null; let deviceId: string = null; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); - deviceId = devices[0].deviceId; -}) +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + deviceId = devices[0].networkId; +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.greaterThan("id", 0); @@ -2917,7 +2916,7 @@ remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: A > **说明:** > -> 其中device通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> 其中device通过调用[deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync)方法得到。 **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core @@ -2947,19 +2946,17 @@ remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: A **示例:** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; +import deviceManager from '@ohos.distributedDeviceManager'; let dmInstance: deviceManager.DeviceManager = null; let deviceId: string = null; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); - deviceId = devices[0].deviceId; -}) +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + deviceId = devices[0].networkId; +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.greaterThan("id", 0); @@ -3821,7 +3818,7 @@ obtainDistributedTableName(device: string, table: string, callback: AsyncCallbac > **说明:** > -> 其中device通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> 其中device通过调用[deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync)方法得到。 **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC @@ -3846,19 +3843,17 @@ obtainDistributedTableName(device: string, table: string, callback: AsyncCallbac **示例:** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; +import deviceManager from '@ohos.distributedDeviceManager'; let dmInstance: deviceManager.DeviceManager = null; let deviceId: string = null; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); - deviceId = devices[0].deviceId; -}) +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + deviceId = devices[0].networkId; +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} store.obtainDistributedTableName(deviceId, "EMPLOYEE", (err, tableName) => { if (err) { @@ -3877,7 +3872,7 @@ store.obtainDistributedTableName(deviceId, "EMPLOYEE", (err, tableName) => { > **说明:** > -> 其中device通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> 其中device通过调用[deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync)方法得到。 **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC @@ -3907,19 +3902,17 @@ store.obtainDistributedTableName(deviceId, "EMPLOYEE", (err, tableName) => { **示例:** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; +import deviceManager from '@ohos.distributedDeviceManager'; let dmInstance: deviceManager.DeviceManager = null; let deviceId: string = null; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); - deviceId = devices[0].deviceId; -}) +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); + deviceId = devices[0].networkId; +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} let promise = store.obtainDistributedTableName(deviceId, "EMPLOYEE"); promise.then((tableName: string) => { @@ -3958,21 +3951,19 @@ sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback<Array **示例:** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; +import deviceManager from '@ohos.distributedDeviceManager'; let dmInstance: deviceManager.DeviceManager = null; let deviceIds: Array = []; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); for (let i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].deviceId; + deviceIds[i] = devices[i].networkId; } -}) +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.inDevices(deviceIds); @@ -4022,21 +4013,19 @@ store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates, (err, result) => **示例:** ```js -import deviceManager from '@ohos.distributedHardware.deviceManager'; +import deviceManager from '@ohos.distributedDeviceManager'; let dmInstance: deviceManager.DeviceManager = null; let deviceIds: Array = []; -deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { - if (err) { - console.log("create device manager failed, err=" + err); - return; - } - dmInstance = manager; - let devices = dmInstance.getTrustedDeviceListSync(); +try { + dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); + let devices = dmInstance.getAvailableDeviceListSync(); for (let i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].deviceId; + deviceIds[i] = devices[i].networkId; } -}) +} catch (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); +} let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.inDevices(deviceIds); @@ -4973,13 +4962,9 @@ close(): void **示例:** ```js -let predicatesClose = new relationalStore.RdbPredicates("EMPLOYEE"); -let promiseClose = store.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promiseClose.then((resultSet: relationalStore.ResultSet) => { + resultSet.close(); -}).catch((err: BusinessError) => { - console.error(`resultset close failed, code is ${err.code},message is ${err.message}`); -}); + ``` **错误码:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-udmf.md b/zh-cn/application-dev/reference/apis/js-apis-data-unifiedDataChannel.md similarity index 83% rename from zh-cn/application-dev/reference/apis/js-apis-data-udmf.md rename to zh-cn/application-dev/reference/apis/js-apis-data-unifiedDataChannel.md index 6f60d20239157bbb274259a74d1d4d760d5206b6..18d326b90d190eb0c3313cbe17aa061bac1a8eb2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-udmf.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-unifiedDataChannel.md @@ -1,6 +1,6 @@ -# @ohos.data.UDMF(统一数据管理框架) +# @ohos.data.unifiedDataChannel(标准化数据通路) -本模块提供数据统一管理的能力,包括对文本、图片等数据类型的标准化定义。通过调用对应数据类型的接口,应用程序可将各种数据封装为统一数据对象。 +本模块为统一数据管理框架(Unified Data Management Framework,UDMF)的组成部分,针对多对多跨应用数据共享的不同业务场景提供了标准化的数据通路,提供了标准化的数据接入与读取接口。同时对文本、图片等数据类型提供了标准化定义,方便不同应用间进行数据交互,减少数据类型适配的工作量。 > **说明:** > @@ -9,32 +9,9 @@ ## 导入模块 ```js -import UDMF from '@ohos.data.UDMF'; +import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; ``` -## UnifiedDataType - -[统一数据对象](#unifieddata)中各[数据记录](#unifiedrecord)的数据类型。 - -**系统能力:** SystemCapability.DistributedDataManager.UDMF.Core - -| 名称 | 值 | 说明 | -|----------------------------|------------------------------|-----------| -| TEXT | 'Text' | 文本类型。 | -| PLAIN_TEXT | 'Text.PlainText' | 纯文本类型。 | -| HYPERLINK | 'Text.Hyperlink' | 超链接类型。 | -| HTML | 'Text.HTML' | 富文本类型。 | -| FILE | 'File' | 文件类型。 | -| IMAGE | 'File.Media.Image' | 图片类型。 | -| VIDEO | 'File.Media.Video' | 视频类型。 | -| AUDIO | 'File.Media.Audio' | 音频类型。 | -| FOLDER | 'File.Folder' | 文件夹类型。 | -| SYSTEM_DEFINED_RECORD | 'SystemDefinedType' | 系统服务数据类型。 | -| SYSTEM_DEFINED_FORM | 'SystemDefinedType.Form' | 卡片类型。 | -| SYSTEM_DEFINED_APP_ITEM | 'SystemDefinedType.AppItem' | 图标类型。 | -| SYSTEM_DEFINED_PIXEL_MAP | 'SystemDefinedType.PixelMap' | 二进制图片类型。 | -| APPLICATION_DEFINED_RECORD | 'ApplicationDefinedType' | 应用自定义类型。 | - ## UnifiedData 表示UDMF统一数据对象,提供封装一组数据记录的方法。 @@ -58,9 +35,9 @@ constructor(record: UnifiedRecord) **示例:** ```js -let text = new UDMF.PlainText(); +let text = new unifiedDataChannel.PlainText(); text.textContent = 'this is textContent of text'; -let unifiedData = new UDMF.UnifiedData(text); +let unifiedData = new unifiedDataChannel.UnifiedData(text); ``` ### addRecord @@ -80,11 +57,11 @@ addRecord(record: UnifiedRecord): void **示例:** ```js -let text1 = new UDMF.PlainText(); +let text1 = new unifiedDataChannel.PlainText(); text1.textContent = 'this is textContent of text1'; -let unifiedData = new UDMF.UnifiedData(text1); +let unifiedData = new unifiedDataChannel.UnifiedData(text1); -let text2 = new UDMF.PlainText(); +let text2 = new unifiedDataChannel.PlainText(); text2.textContent = 'this is textContent of text2'; unifiedData.addRecord(text2); ``` @@ -106,22 +83,24 @@ getRecords(): Array\ **示例:** ```js -let text = new UDMF.PlainText(); +import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; + +let text = new unifiedDataChannel.PlainText(); text.textContent = 'this is textContent of text'; -let unifiedData = new UDMF.UnifiedData(text); +let unifiedData = new unifiedDataChannel.UnifiedData(text); -let link = new UDMF.Hyperlink(); +let link = new unifiedDataChannel.Hyperlink(); link.url = 'www.XXX.com'; unifiedData.addRecord(link); let records = unifiedData.getRecords(); for (let i = 0; i < records.length; i++) { let record = records[i]; - if (record.getType() == UDMF.UnifiedDataType.PLAIN_TEXT) { - let plainText = (record); + if (record.getType() == uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let plainText = (record); console.info(`textContent: ${plainText.textContent}`); - } else if (record.getType() == UDMF.UnifiedDataType.HYPERLINK) { - let hyperlink = (record); + } else if (record.getType() == uniformTypeDescriptor.UniformDataType.HYPERLINK) { + let hyperlink = (record); console.info(`linkUrl: ${hyperlink.url}`); } } @@ -135,7 +114,7 @@ for (let i = 0; i < records.length; i++) { | 名称 | 类型 | 可读 | 可写 | 说明 | | --------- | ------------------------- | ---- | ---- |-----------------------------------------------------------------------------------| -| summary | { [key: string]: number } | 是 | 否 | 是一个字典类型对象,key表示数据类型(见[UnifiedDataType](#unifieddatatype)),value为统一数据对象中该类型记录大小总和(单位:Byte)。 | +| summary | { [key: string]: number } | 是 | 否 | 是一个字典类型对象,key表示数据类型(见[UniformDataType](js-apis-data-uniformTypeDescriptor.md#uniformdatatype)),value为统一数据对象中该类型记录大小总和(单位:Byte)。 | | totalSize | number | 是 | 否 | 统一数据对象内记录总大小(单位:Byte)。 | ## UnifiedRecord @@ -156,18 +135,20 @@ getType(): string | 类型 | 说明 | | ------ |------------------------------------------------------| -| string | 当前数据记录对应的具体数据类型,见[UnifiedDataType](#unifieddatatype)。| +| string | 当前数据记录对应的具体数据类型,见[UniformDataType](js-apis-data-uniformTypeDescriptor.md#uniformdatatype)。| **示例:** ```js -let text = new UDMF.PlainText(); +import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; + +let text = new unifiedDataChannel.PlainText(); text.textContent = 'this is textContent of text'; -let unifiedData = new UDMF.UnifiedData(text); +let unifiedData = new unifiedDataChannel.UnifiedData(text); let records = unifiedData.getRecords(); -if (records[0].getType() == UDMF.UnifiedDataType.PLAIN_TEXT) { - let plainText = (records[0]); +if (records[0].getType() == uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let plainText = (records[0]); console.info(`textContent: ${plainText.textContent}`); } ``` @@ -185,12 +166,12 @@ if (records[0].getType() == UDMF.UnifiedDataType.PLAIN_TEXT) { **示例:** ```js -let text = new UDMF.Text(); +let text = new unifiedDataChannel.Text(); text.details = { title: 'MyTitle', content: 'this is content', }; -let unifiedData = new UDMF.UnifiedData(text); +let unifiedData = new unifiedDataChannel.UnifiedData(text); ``` ## PlainText @@ -207,7 +188,7 @@ let unifiedData = new UDMF.UnifiedData(text); **示例:** ```js -let text = new UDMF.PlainText(); +let text = new unifiedDataChannel.PlainText(); text.textContent = 'this is textContent'; text.abstract = 'this is abstract'; ``` @@ -226,7 +207,7 @@ text.abstract = 'this is abstract'; **示例:** ```js -let link = new UDMF.Hyperlink(); +let link = new unifiedDataChannel.Hyperlink(); link.url = 'www.XXX.com'; link.description = 'this is description'; ``` @@ -245,7 +226,7 @@ HTML类型数据,是[Text](#text)的子类,用于描述超文本标记语言 **示例:** ```js -let html = new UDMF.HTML(); +let html = new unifiedDataChannel.HTML(); html.htmlContent = '

标题

'; html.plainContent = 'this is plainContent'; ``` @@ -264,7 +245,7 @@ File类型数据,是[UnifiedRecord](#unifiedrecord)的子类,也是文件类 **示例:** ```js -let file = new UDMF.File(); +let file = new unifiedDataChannel.File(); file.details = { name: 'test', type: 'txt', @@ -285,7 +266,7 @@ file.uri = 'schema://com.samples.test/files/test.txt'; **示例:** ```js -let image = new UDMF.Image(); +let image = new unifiedDataChannel.Image(); image.imageUri = 'schema://com.samples.test/files/test.jpg'; ``` @@ -302,7 +283,7 @@ image.imageUri = 'schema://com.samples.test/files/test.jpg'; **示例:** ```js -let video = new UDMF.Video(); +let video = new unifiedDataChannel.Video(); video.videoUri = 'schema://com.samples.test/files/test.mp4'; ``` @@ -319,7 +300,7 @@ video.videoUri = 'schema://com.samples.test/files/test.mp4'; **示例:** ```js -let audio = new UDMF.Audio(); +let audio = new unifiedDataChannel.Audio(); audio.audioUri = 'schema://com.samples.test/files/test.mp3'; ``` @@ -336,7 +317,7 @@ audio.audioUri = 'schema://com.samples.test/files/test.mp3'; **示例:** ```js -let folder = new UDMF.Folder(); +let folder = new unifiedDataChannel.Folder(); folder.folderUri = 'schema://com.samples.test/files/folder/'; ``` @@ -353,14 +334,14 @@ SystemDefinedRecord是[UnifiedRecord](#unifiedrecord)的子类,也是OpenHarmo **示例:** ```js -let sdr = new UDMF.SystemDefinedRecord(); +let sdr = new unifiedDataChannel.SystemDefinedRecord(); let u8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); sdr.details = { title: 'recordTitle', version: 1, content: u8Array, }; -let unifiedData = new UDMF.UnifiedData(sdr); +let unifiedData = new unifiedDataChannel.UnifiedData(sdr); ``` ## SystemDefinedForm @@ -380,7 +361,7 @@ let unifiedData = new UDMF.UnifiedData(sdr); **示例:** ```js -let form = new UDMF.SystemDefinedForm(); +let form = new unifiedDataChannel.SystemDefinedForm(); form.formId = 123456; form.formName = 'MyFormName'; form.bundleName = 'MyBundleName'; @@ -392,7 +373,7 @@ form.details = { formKey2: 'formValue', formKey3: u8Array, }; -let unifiedData = new UDMF.UnifiedData(form); +let unifiedData = new unifiedDataChannel.UnifiedData(form); ``` ## SystemDefinedAppItem @@ -413,7 +394,7 @@ let unifiedData = new UDMF.UnifiedData(form); **示例:** ```js -let appItem = new UDMF.SystemDefinedAppItem(); +let appItem = new unifiedDataChannel.SystemDefinedAppItem(); appItem.appId = 'MyAppId'; appItem.appName = 'MyAppName'; appItem.appIconId = 'MyAppIconId'; @@ -426,7 +407,7 @@ appItem.details = { appItemKey2: 'appItemValue', appItemKey3: u8Array, }; -let unifiedData = new UDMF.UnifiedData(appItem); +let unifiedData = new unifiedDataChannel.UnifiedData(appItem); ``` ## SystemDefinedPixelMap @@ -454,9 +435,9 @@ image.createPixelMap(color, opts, (error, pixelmap) => { let arrayBuf = new ArrayBuffer(pixelmap.getPixelBytesNumber()); pixelmap.readPixelsToBuffer(arrayBuf); let u8Array = new Uint8Array(arrayBuf); - let sdpixel = new UDMF.SystemDefinedPixelMap(); + let sdpixel = new unifiedDataChannel.SystemDefinedPixelMap(); sdpixel.rawData = u8Array; - let unifiedData = new UDMF.UnifiedData(sdpixel); + let unifiedData = new unifiedDataChannel.UnifiedData(sdpixel); } }) ``` @@ -475,11 +456,11 @@ ApplicationDefinedRecord是[UnifiedRecord](#unifiedrecord)的子类,也是应 **示例:** ```js -let record = new UDMF.ApplicationDefinedRecord(); +let record = new unifiedDataChannel.ApplicationDefinedRecord(); let u8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); record.applicationDefinedType = 'ApplicationDefinedType'; record.rawData = u8Array; -let unifiedData = new UDMF.UnifiedData(record); +let unifiedData = new unifiedDataChannel.UnifiedData(record); ``` ## Intention @@ -502,11 +483,11 @@ UDMF提供的数据操作接口可选项,包含intention和key两个可选参 | 名称 | 类型 | 可读 | 可写 | 必填 | 说明 | |-----------|-------------------------|----|----|----|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | intention | [Intention](#intention) | 是 | 是 | 否 | 表示数据操作相关的数据通路类型。 | -| key | string | 是 | 是 | 否 | UDMF中数据对象的唯一标识符,可通过[insertData](#udmfinsertdata)接口的返回值获取。
由udmf:/、intention、bundleName和groupId四部分组成,以'/'连接,比如:udmf://DataHub/com.ohos.test/0123456789。
其中udmf:/固定,DataHub为对应枚举的取值,com.ohos.test为包名,0123456789为随机生成的groupId。 | +| key | string | 是 | 是 | 否 | UDMF中数据对象的唯一标识符,可通过[insertData](#unifieddatachannelinsertdata)接口的返回值获取。
由udmf:/、intention、bundleName和groupId四部分组成,以'/'连接,比如:udmf://DataHub/com.ohos.test/0123456789。
其中udmf:/固定,DataHub为对应枚举的取值,com.ohos.test为包名,0123456789为随机生成的groupId。 | -## UDMF.insertData +## unifiedDataChannel.insertData insertData(options: Options, data: UnifiedData, callback: AsyncCallback<string>): void @@ -525,17 +506,17 @@ insertData(options: Options, data: UnifiedData, callback: AsyncCallback<strin **示例:** ```ts -import UDMF from '@ohos.data.UDMF'; +import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; -let plainText = new UDMF.PlainText(); +let plainText = new unifiedDataChannel.PlainText(); plainText.textContent = 'hello world!'; -let unifiedData = new UDMF.UnifiedData(plainText); +let unifiedData = new unifiedDataChannel.UnifiedData(plainText); let options = { - intention: UDMF.Intention.DATA_HUB + intention: unifiedDataChannel.Intention.DATA_HUB } try { - UDMF.insertData(options, unifiedData, (err, data) => { + unifiedDataChannel.insertData(options, unifiedData, (err, data) => { if (err === undefined) { console.info(`Succeeded in inserting data. key = ${data}`); } else { @@ -548,7 +529,7 @@ try { ``` -## UDMF.insertData +## unifiedDataChannel.insertData insertData(options: Options, data: UnifiedData): Promise<string> @@ -572,17 +553,17 @@ insertData(options: Options, data: UnifiedData): Promise<string> **示例:** ```ts -import UDMF from '@ohos.data.UDMF'; +import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; -let plainText = new UDMF.PlainText(); +let plainText = new unifiedDataChannel.PlainText(); plainText.textContent = 'hello world!'; -let unifiedData = new UDMF.UnifiedData(plainText); +let unifiedData = new unifiedDataChannel.UnifiedData(plainText); let options = { - intention: UDMF.Intention.DATA_HUB + intention: unifiedDataChannel.Intention.DATA_HUB } try { - UDMF.insertData(options, unifiedData).then((data) => { + unifiedDataChannel.insertData(options, unifiedData).then((data) => { console.info(`Succeeded in inserting data. key = ${data}`); }).catch((err) => { console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `); @@ -592,7 +573,7 @@ try { } ``` -## UDMF.updateData +## unifiedDataChannel.updateData updateData(options: Options, data: UnifiedData, callback: AsyncCallback<void>): void @@ -611,18 +592,18 @@ updateData(options: Options, data: UnifiedData, callback: AsyncCallback<void& **示例:** ```ts -import UDMF from '@ohos.data.UDMF'; +import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; -let plainText = new UDMF.PlainText(); +let plainText = new unifiedDataChannel.PlainText(); plainText.textContent = 'hello world!'; -let unifiedData = new UDMF.UnifiedData(plainText); +let unifiedData = new unifiedDataChannel.UnifiedData(plainText); let options = { key: 'udmf://DataHub/com.ohos.test/0123456789' }; try { - UDMF.updateData(options, unifiedData, (err) => { + unifiedDataChannel.updateData(options, unifiedData, (err) => { if (err === undefined) { console.info('Succeeded in updating data.'); } else { @@ -634,7 +615,7 @@ try { } ``` -## UDMF.updateData +## unifiedDataChannel.updateData updateData(options: Options, data: UnifiedData): Promise<void> @@ -658,18 +639,18 @@ updateData(options: Options, data: UnifiedData): Promise<void> **示例:** ```ts -import UDMF from '@ohos.data.UDMF'; +import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; -let plainText = new UDMF.PlainText(); +let plainText = new unifiedDataChannel.PlainText(); plainText.textContent = 'hello world!'; -let unifiedData = new UDMF.UnifiedData(plainText); +let unifiedData = new unifiedDataChannel.UnifiedData(plainText); let options = { key: 'udmf://DataHub/com.ohos.test/0123456789' }; try { - UDMF.updateData(options, unifiedData).then(() => { + unifiedDataChannel.updateData(options, unifiedData).then(() => { console.info('Succeeded in updating data.'); }).catch((err) => { console.error(`Failed to update data. code is ${err.code},message is ${err.message} `); @@ -679,7 +660,7 @@ try { } ``` -## UDMF.queryData +## unifiedDataChannel.queryData queryData(options: Options, callback: AsyncCallback<Array<UnifiedData>>): void @@ -697,21 +678,22 @@ queryData(options: Options, callback: AsyncCallback<Array<UnifiedData>& **示例:** ```ts -import UDMF from '@ohos.data.UDMF'; +import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; +import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; let options = { - intention: UDMF.Intention.DATA_HUB + intention: unifiedDataChannel.Intention.DATA_HUB }; try { - UDMF.queryData(options, (err, data) => { + unifiedDataChannel.queryData(options, (err, data) => { if (err === undefined) { console.info(`Succeeded in querying data. size = ${data.length}`); for (let i = 0; i < data.length; i++) { let records = data[i].getRecords(); for (let j = 0; j < records.length; j++) { - if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) { - let text = (records[j]); + if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let text = (records[j]); console.info(`${i + 1}.${text.textContent}`); } } @@ -725,7 +707,7 @@ try { } ``` -## UDMF.queryData +## unifiedDataChannel.queryData queryData(options: Options): Promise<Array<UnifiedData>> @@ -748,20 +730,21 @@ queryData(options: Options): Promise<Array<UnifiedData>> **示例:** ```ts -import UDMF from '@ohos.data.UDMF'; +import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; +import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; let options = { key: 'udmf://DataHub/com.ohos.test/0123456789' }; try { - UDMF.queryData(options).then((data) => { + unifiedDataChannel.queryData(options).then((data) => { console.info(`Succeeded in querying data. size = ${data.length}`); for (let i = 0; i < data.length; i++) { let records = data[i].getRecords(); for (let j = 0; j < records.length; j++) { - if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) { - let text = (records[j]); + if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let text = (records[j]); console.info(`${i + 1}.${text.textContent}`); } } @@ -774,7 +757,7 @@ try { } ``` -## UDMF.deleteData +## unifiedDataChannel.deleteData deleteData(options: Options, callback: AsyncCallback<Array<UnifiedData>>): void @@ -792,21 +775,22 @@ deleteData(options: Options, callback: AsyncCallback<Array<UnifiedData> **示例:** ```ts -import UDMF from '@ohos.data.UDMF'; +import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; +import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; let options = { - intention: UDMF.Intention.DATA_HUB + intention: unifiedDataChannel.Intention.DATA_HUB }; try { - UDMF.deleteData(options, (err, data) => { + unifiedDataChannel.deleteData(options, (err, data) => { if (err === undefined) { console.info(`Succeeded in deleting data. size = ${data.length}`); for (let i = 0; i < data.length; i++) { let records = data[i].getRecords(); for (let j = 0; j < records.length; j++) { - if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) { - let text = (records[j]); + if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let text = (records[j]); console.info(`${i + 1}.${text.textContent}`); } } @@ -820,7 +804,7 @@ try { } ``` -## UDMF.deleteData +## unifiedDataChannel.deleteData deleteData(options: Options): Promise<Array<UnifiedData>> @@ -843,20 +827,21 @@ deleteData(options: Options): Promise<Array<UnifiedData>> **示例:** ```ts -import UDMF from '@ohos.data.UDMF'; +import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; +import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; let options = { key: 'udmf://DataHub/com.ohos.test/0123456789' }; try { - UDMF.deleteData(options).then((data) => { + unifiedDataChannel.deleteData(options).then((data) => { console.info(`Succeeded in deleting data. size = ${data.length}`); for (let i = 0; i < data.length; i++) { let records = data[i].getRecords(); for (let j = 0; j < records.length; j++) { - if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) { - let text = (records[j]); + if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let text = (records[j]); console.info(`${i + 1}.${text.textContent}`); } } diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-uniformTypeDescriptor.md b/zh-cn/application-dev/reference/apis/js-apis-data-uniformTypeDescriptor.md new file mode 100644 index 0000000000000000000000000000000000000000..96d1150c184e0ab7cb9dd81a696b9d9f00df1643 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-data-uniformTypeDescriptor.md @@ -0,0 +1,34 @@ +# @ohos.data.uniformTypeDescriptor(标准化数据定义与描述) + +本模块描述OpenHarmony标准化数据类型的抽象定义。 + +> **说明:** +> +> 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +```js +import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; +``` + +## UniformDataType + +OpenHarmony标准化数据类型的枚举定义。 + +**系统能力:** SystemCapability.DistributedDataManager.UDMF.Core + +| 名称 | 值 | 说明 | +|----------------------------|------------------------------|-----------| +| TEXT | 'general.text' | 文本类型。 | +| PLAIN_TEXT | 'general.plain-text' | 纯文本类型。 | +| HYPERLINK | 'general.hyperlink' | 超链接类型。 | +| HTML | 'general.html' | 富文本类型。 | +| FILE | 'general.file' | 文件类型。 | +| IMAGE | 'general.image' | 图片类型。 | +| VIDEO | 'general.video' | 视频类型。 | +| AUDIO | 'general.audio' | 音频类型。 | +| FOLDER | 'general.folder' | 文件夹类型。 | +| OPENHARMONY_FORM | 'openharmony.form' | 卡片类型。 | +| OPENHARMONY_APP_ITEM | 'openharmony.app-item' | 图标类型。 | +| OPENHARMONY_PIXEL_MAP | 'openharmony.pixel-map' | 二进制图片类型。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md b/zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md index acd95567178272e55fd6ceca9c340d7ca5e0d036..38e53dcac11f83c22dec6ed1a89e5aed8018b6cd 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md @@ -99,6 +99,39 @@ defaultAppMgr.isDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, }); ``` +## defaultAppMgr.isDefaultApplicationSync10+ + +isDefaultApplicationSync(type: string): boolean; + +以同步方法根据系统已定义的应用类型判断当前应用是否是该应用类型的默认应用,使用boolean形式返回结果。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultApp + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------| ------ | ---- | --------------------------------------- | +| type | string | 是 | 要查询的应用类型,取[ApplicationType](#defaultappmgrapplicationtype)中的值。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | -------------------- | +| boolean | 返回当前应用是否是默认应用,true表示是默认应用,false表示不是默认应用。 | + + +**示例:** + +```ts +import defaultAppMgr from '@ohos.bundle.defaultAppManager'; +defaultAppMgr.isDefaultApplicationSync(defaultAppMgr.ApplicationType.BROWSER) +.then((data) => { + console.info('Operation successful. IsDefaultApplicationSync ? ' + JSON.stringify(data)); +}).catch((error) => { + console.error('Operation failed. Cause: ' + JSON.stringify(error)); +}); +``` + ## defaultAppMgr.getDefaultApplication getDefaultApplication(type: string, userId?: number): Promise\ @@ -255,6 +288,62 @@ defaultAppMgr.getDefaultApplication("image/png", (err, data) => { }); ``` +## defaultAppMgr.getDefaultApplicationSync10+ + +getDefaultApplicationSync(type: string, userId?: number): BundleInfo; + +以同步方法根据系统已定义的应用类型或者符合媒体类型格式(type/subtype)的文件类型获取默认应用信息,使用BundleInfo返回结果。 + +**需要权限:** ohos.permission.GET_DEFAULT_APPLICATION + +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultApp + +**系统API:** 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------| ------ | ---- | --------------------------------------- | +| type | string | 是 | 要查询的应用类型,取[ApplicationType](#defaultappmgrapplicationtype)中的值,或者符合媒体类型格式的文件类型。| +| userId | number | 否 | 用户ID。默认值:调用方所在用户。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------ | -------------------- | +| [BundleInfo](js-apis-bundle-BundleInfo.md) | 返回的默认应用包信息。| + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 17700004 | The specified user ID is not found. | +| 17700023 | The specified default app does not exist. | +| 17700025 | The specified type is invalid. | + +**示例:** + +```ts +import defaultAppMgr from '@ohos.bundle.defaultAppManager'; +defaultAppMgr.getDefaultApplicationSync(defaultAppMgr.ApplicationType.BROWSER) +.then((data) => { + console.info('Operation successful. bundleInfo: ' + JSON.stringify(data)); +}) +.catch((error) => { + console.error('Operation failed. Cause: ' + JSON.stringify(error)); +}); + +defaultAppMgr.getDefaultApplicationSync("image/png") +.then((data) => { + console.info('Operation successful. bundleInfo: ' + JSON.stringify(data)); +}) +.catch((error) => { + console.error('Operation failed. Cause: ' + JSON.stringify(error)); +}); +``` + ## defaultAppMgr.setDefaultApplication setDefaultApplication(type: string, elementName: ElementName, userId?: number): Promise\ @@ -446,6 +535,72 @@ defaultAppMgr.setDefaultApplication("image/png", { }); ``` +## defaultAppMgr.setDefaultApplicationSync10+ + +setDefaultApplicationSync(type: string, elementName: ElementName, userId?: number): void; + +以同步方法根据系统已定义的应用类型或者符合媒体类型格式(type/subtype)的文件类型设置默认应用。 + +**需要权限:** ohos.permission.SET_DEFAULT_APPLICATION + +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultApp + +**系统API:** 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | --------------------------------------- | +| type | string | 是 | 要设置的应用类型,取[ApplicationType](#defaultappmgrapplicationtype)中的值,或者符合媒体类型格式的文件类型。| +| elementName | [ElementName](js-apis-bundle-ElementName.md) | 是 | 要设置为默认应用的组件信息。 | +| userId | number | 否 | 用户ID。默认值:调用方所在用户。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------------- | +| 17700004 | The specified user ID is not found. | +| 17700025 | The specified type is invalid. | +| 17700028 | The specified ability does not match the type. | + +**示例:** + +```ts +import defaultAppMgr from '@ohos.bundle.defaultAppManager'; +defaultAppMgr.setDefaultApplicationSync(defaultAppMgr.ApplicationType.BROWSER, { + bundleName: "com.example.myapplication", + moduleName: "module01", + abilityName: "EntryAbility" +}).then((data) => { + console.info('Operation successful.'); +}).catch((error) => { + console.error('Operation failed. Cause: ' + JSON.stringify(error)); +}); + +let userId = 100; +defaultAppMgr.setDefaultApplicationSync(defaultAppMgr.ApplicationType.BROWSER, { + bundleName: "com.example.myapplication", + moduleName: "module01", + abilityName: "EntryAbility" +}, userId).then((data) => { + console.info('Operation successful.'); +}).catch((error) => { + console.error('Operation failed. Cause: ' + JSON.stringify(error)); +}); + +defaultAppMgr.setDefaultApplicationSync("image/png", { + bundleName: "com.example.myapplication", + moduleName: "module01", + abilityName: "EntryAbility" +}, userId).then((data) => { + console.info('Operation successful.'); +}).catch((error) => { + console.error('Operation failed. Cause: ' + JSON.stringify(error)); +}); +``` + ## defaultAppMgr.resetDefaultApplication resetDefaultApplication(type: string, userId?: number): Promise\ @@ -593,4 +748,54 @@ defaultAppMgr.resetDefaultApplication("image/png", (err, data) => { } console.info('Operation successful.'); }); +``` + +## defaultAppMgr.resetDefaultApplicationSync10+ + +resetDefaultApplicationSync(type: string, userId?: number): void; + +以同步方法根据系统已定义的应用类型或者符合媒体类型格式(type/subtype)的文件类型重置默认应用。 + +**需要权限:** ohos.permission.SET_DEFAULT_APPLICATION + +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultApp + +**系统API:** 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | --------------------------------------- | +| type | string | 是 | 要重置的应用类型,取[ApplicationType](#defaultappmgrapplicationtype)中的值,或者符合媒体类型格式的文件类型。| +| userId | number | 否 | 用户ID。默认值:调用方所在用户。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------- | +| 17700004 | The specified user ID is not found. | +| 17700025 | The specified type is invalid. | + +**示例:** + +```ts +import defaultAppMgr from '@ohos.bundle.defaultAppManager'; +let userId = 100; +defaultAppMgr.resetDefaultApplicationSync(defaultAppMgr.ApplicationType.BROWSER, userId) +.then((data) => { + console.info('Operation successful.'); +}) +.catch((error) => { + console.error('Operation failed. Cause: ' + JSON.stringify(error)); +}); + +defaultAppMgr.resetDefaultApplicationSync("image/png", userId) +.then((data) => { + console.info('Operation successful.'); +}) +.catch((error) => { + console.error('Operation failed. Cause: ' + JSON.stringify(error)); +}); ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md b/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md index fb15a53ee4e6989376abbb18d68c7d072a46caf0..3f28830d8aa18c113b4489ee756d409b6de959be 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @@ -59,15 +59,18 @@ getOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): voi **示例:** ```js + import { BusinessError } from '@ohos.base'; + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); try { - accountAbility.getOsAccountDistributedInfo((err, data) => { - if (err) { - console.log('getOsAccountDistributedInfo exception: ' + JSON.stringify(err)); - } else { - console.log('distributed information: ' + JSON.stringify(data)); - } - }); + accountAbility.getOsAccountDistributedInfo( + (err: BusinessError, data: account_distributedAccount.DistributedInfo) => { + if (err) { + console.log('getOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + } else { + console.log('distributed information: ' + JSON.stringify(data)); + } + }); } catch (err) { console.log('getOsAccountDistributedInfo exception: ' + JSON.stringify(err)); } @@ -97,11 +100,13 @@ getOsAccountDistributedInfo(): Promise<DistributedInfo> **示例:** ```js + import { BusinessError } from '@ohos.base'; + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); try { - accountAbility.getOsAccountDistributedInfo().then((data) => { + accountAbility.getOsAccountDistributedInfo().then((data: account_distributedAccount.DistributedInfo) => { console.log('distributed information: ' + JSON.stringify(data)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getOsAccountDistributedInfo exception: ' + JSON.stringify(err)); }); } catch (err) { @@ -137,15 +142,18 @@ getOsAccountDistributedInfoByLocalId(localId: number, callback: AsyncCallback< **示例:** ```js + import { BusinessError } from '@ohos.base'; + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); try { - accountAbility.getOsAccountDistributedInfoByLocalId(100, (err, data) => { - if (err) { - console.log('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); - } else { - console.log('distributed information: ' + JSON.stringify(data)); - } - }); + accountAbility.getOsAccountDistributedInfoByLocalId(100, + (err: BusinessError, data: account_distributedAccount.DistributedInfo) => { + if (err) { + console.log('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + } else { + console.log('distributed information: ' + JSON.stringify(data)); + } + }); } catch (err) { console.log('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); } @@ -178,15 +186,18 @@ getOsAccountDistributedInfoByLocalId(localId: number): Promise<DistributedInf **示例:** ```js + import { BusinessError } from '@ohos.base'; + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); try { - accountAbility.getOsAccountDistributedInfoByLocalId(100).then((data) => { - console.log('distributed information: ' + JSON.stringify(data)); - }).catch((err) => { - console.log('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + accountAbility.getOsAccountDistributedInfoByLocalId(100).then(( + data: account_distributedAccount.DistributedInfo) => { + console.log('distributed information: ' + JSON.stringify(data)); + }).catch((err: BusinessError) => { + console.log('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); }); } catch (err) { - console.log('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + console.log('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); } ``` @@ -211,14 +222,17 @@ queryOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): v **示例:** ```js + import { BusinessError } from '@ohos.base'; + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - accountAbility.queryOsAccountDistributedInfo((err, data) => { - if (err) { - console.log('queryOsAccountDistributedInfo exception: ' + JSON.stringify(err)); - } else { - console.log('distributed information: ' + JSON.stringify(data)); - } - }); + accountAbility.queryOsAccountDistributedInfo( + (err: BusinessError, data: account_distributedAccount.DistributedInfo) => { + if (err) { + console.log('queryOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + } else { + console.log('distributed information: ' + JSON.stringify(data)); + } + }); ``` ### queryOsAccountDistributedInfo(deprecated) @@ -243,10 +257,12 @@ queryOsAccountDistributedInfo(): Promise<DistributedInfo> **示例:** ```js + import { BusinessError } from '@ohos.base'; + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - accountAbility.queryOsAccountDistributedInfo().then((data) => { + accountAbility.queryOsAccountDistributedInfo().then((data: account_distributedAccount.DistributedInfo) => { console.log('distributed information: ' + JSON.stringify(data)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('queryOsAccountDistributedInfo exception: ' + JSON.stringify(err)); }); ``` @@ -278,10 +294,12 @@ setOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallbac **示例:** ```js + import { BusinessError } from '@ohos.base'; + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; try { - accountAbility.setOsAccountDistributedInfo(accountInfo, (err) => { + accountAbility.setOsAccountDistributedInfo(accountInfo, (err: BusinessError) => { if (err) { console.log('setOsAccountDistributedInfo exception: ' + JSON.stringify(err)); } else { @@ -325,12 +343,14 @@ setOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> **示例:** ```js + import { BusinessError } from '@ohos.base'; + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; try { accountAbility.setOsAccountDistributedInfo(accountInfo).then(() => { console.log('setOsAccountDistributedInfo successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('setOsAccountDistributedInfo exception: ' + JSON.stringify(err)); }); } catch (err) { @@ -368,10 +388,12 @@ setOsAccountDistributedInfoByLocalId(localId: number, distributedInfo: Distribut **示例:** ```js + import { BusinessError } from '@ohos.base'; + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; try { - accountAbility.setOsAccountDistributedInfoByLocalId(100, accountInfo, (err) => { + accountAbility.setOsAccountDistributedInfoByLocalId(100, accountInfo, (err: BusinessError) => { if (err) { console.log('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); } else { @@ -419,12 +441,14 @@ setOsAccountDistributedInfoByLocalId(localId: number, distributedInfo: Distribut **示例:** ```js + import { BusinessError } from '@ohos.base'; + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; try { accountAbility.setOsAccountDistributedInfoByLocalId(100, accountInfo).then(() => { console.log('setOsAccountDistributedInfoByLocalId successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); }); } catch (err) { @@ -455,9 +479,11 @@ updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCall **示例:** ```js + import { BusinessError } from '@ohos.base'; + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; - accountAbility.updateOsAccountDistributedInfo(accountInfo, (err) => { + accountAbility.updateOsAccountDistributedInfo(accountInfo, (err: BusinessError) => { if (err) { console.log('queryOsAccountDistributedInfo exception: ' + JSON.stringify(err)); } else { @@ -492,11 +518,13 @@ updateOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> **示例:** ```js + import { BusinessError } from '@ohos.base'; + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; accountAbility.updateOsAccountDistributedInfo(accountInfo).then(() => { console.log('updateOsAccountDistributedInfo successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('updateOsAccountDistributedInfo exception: ' + JSON.stringify(err)); }); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-emitter.md b/zh-cn/application-dev/reference/apis/js-apis-emitter.md index 88d4b90c88c683547d32ba3de0f1a64744461d02..e67e625907a1e6001d9422916c0126d2c50fafcf 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-emitter.md +++ b/zh-cn/application-dev/reference/apis/js-apis-emitter.md @@ -99,7 +99,7 @@ emitter.off(1); ## emitter.off10+ -off(eventId: number,callback: Callback\<[EventData](#eventdata)\>): void +off(eventId: number, callback: Callback\<[EventData](#eventdata)\>): void 取消针对该事件ID的订阅,传入可选参数callback,并且该callback已经通过on或者once接口订阅,则取消该订阅;否则,不做任何处理。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-file-fs.md b/zh-cn/application-dev/reference/apis/js-apis-file-fs.md index 8c1df075bfb6e5127c6209b70d502e02c46d7eda..6d0a51d60e0d3e10c80b3ce2744233bd3cee1c91 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-file-fs.md +++ b/zh-cn/application-dev/reference/apis/js-apis-file-fs.md @@ -1886,7 +1886,7 @@ listFile(path: string, options?: { | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | --------------------------- | - | recursion | boolean | 否 | 是否递归子目录下文件名,默认为false。 | + | recursion | boolean | 否 | 是否递归子目录下文件名,默认为false。当recursion为false时,返回当前目录下满足过滤要求的文件名及文件夹名。当recursion为true时,返回此目录下所有满足过滤要求的文件的相对路径(以/开头)。 | | listNum | number | 否 | 列出文件名数量。当设置0时,列出所有文件,默认为0。 | | filter | [Filter](#filter) | 否 | 文件过滤选项。当前仅支持后缀名匹配、文件名模糊查询、文件大小过滤、最近修改时间过滤。 | @@ -1946,7 +1946,7 @@ listFile(path: string, options?: { | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | --------------------------- | - | recursion | boolean | 否 | 是否递归子目录下文件名,默认为false。 | + | recursion | boolean | 否 | 是否递归子目录下文件名,默认为false。当recursion为false时,返回当前目录下满足过滤要求的文件名及文件夹名。当recursion为true时,返回此目录下所有满足过滤要求的文件的相对路径(以/开头)。| | listNum | number | 否 | 列出文件名数量。当设置0时,列出所有文件,默认为0。 | | filter | [Filter](#filter) | 否 | 文件过滤选项。当前仅支持后缀名匹配、文件名模糊查询、文件大小过滤、最近修改时间过滤。 | @@ -2002,7 +2002,7 @@ listFileSync(path: string, options?: { | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | --------------------------- | - | recursion | boolean | 否 | 是否递归子目录下文件名,默认为false。 | + | recursion | boolean | 否 | 是否递归子目录下文件名,默认为false。当recursion为false时,返回当前目录下满足过滤要求的文件名及文件夹名。当recursion为true时,返回此目录下所有满足过滤要求的文件的相对路径(以/开头)。 | | listNum | number | 否 | 列出文件名数量。当设置0时,列出所有文件,默认为0。 | | filter | [Filter](#filter) | 否 | 文件过滤选项。当前仅支持后缀名匹配、文件名模糊查询、文件大小过滤、最近修改时间过滤。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-file-picker.md b/zh-cn/application-dev/reference/apis/js-apis-file-picker.md index db11231b5dc5d4ef2a3368cfbbb54c7a1fef7d00..3e629cc7644d65ab86b3760e232a52bef271688e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-file-picker.md +++ b/zh-cn/application-dev/reference/apis/js-apis-file-picker.md @@ -244,7 +244,7 @@ async function example() { ## DocumentViewPicker -文件选择器对象,用来支撑选择和保存非媒体文件等用户场景,比如各种格式文档。在使用前,需要先创建DocumentViewPicker实例。 +文件选择器对象,用来支撑选择和保存各种格式文档。在使用前,需要先创建DocumentViewPicker实例。 **系统能力**:SystemCapability.FileManagement.UserFileService @@ -699,7 +699,7 @@ async function example() { 枚举,可选择的媒体文件类型。 -**系统能力:** 以下各项对应的系统能力均为 SystemCapability.FileManagement.UserFileService +**系统能力:** SystemCapability.FileManagement.UserFileService | 名称 | 值 | 说明 | | ----- | ---- | ---- | @@ -711,18 +711,18 @@ async function example() { 图库选择选项。 -**系统能力:** 以下各项对应的系统能力均为 SystemCapability.FileManagement.UserFileService +**系统能力:** SystemCapability.FileManagement.UserFileService | 名称 | 类型 | 必填 | 说明 | | ----------------------- | ------------------- | ---- | -------------------------------- | -| MIMEType? | [PhotoViewMIMETypes](#photoviewmimetypes) | 否 | 可选择的媒体文件类型,若无此参数,则默认为图片和视频类型 | -| maxSelectNumber? | number | 否 | 选择媒体文件数量的最大值(默认值为50,最大值为500) | +| MIMEType | [PhotoViewMIMETypes](#photoviewmimetypes) | 否 | 可选择的媒体文件类型,若无此参数,则默认为图片和视频类型 | +| maxSelectNumber | number | 否 | 选择媒体文件数量的最大值(默认值为50,最大值为500) | ## PhotoSelectResult 返回图库选择后的结果集。 -**系统能力:** 以下各项对应的系统能力均为 SystemCapability.FileManagement.UserFileService +**系统能力:** SystemCapability.FileManagement.UserFileService | 名称 | 类型 | 可读 | 可写 | 说明 | | ----------------------- | ------------------- | ---- | ---- | ------------------------------ | @@ -733,27 +733,35 @@ async function example() { 图片或视频的保存选项。 -**系统能力:** 以下各项对应的系统能力均为 SystemCapability.FileManagement.UserFileService +**系统能力:** SystemCapability.FileManagement.UserFileService | 名称 | 类型 | 必填 | 说明 | | ----------------------- | ------------------- | ---- | ---------------------------- | -| newFileNames? | Array<string> | 否 | 拉起photoPicker进行保存图片或视频资源的文件名,若无此参数,则默认需要用户自行输入 | +| newFileNames | Array<string> | 否 | 拉起photoPicker进行保存图片或视频资源的文件名,若无此参数,则默认需要用户自行输入 | ## DocumentSelectOptions -文档选择选项,目前不支持参数配置。 +文档选择选项。 **系统能力:** SystemCapability.FileManagement.UserFileService +| 名称 | 类型 | 必填 | 说明 | +| ----------------------- | ------------------- | ---- | -------------------------------- | +| maxSelectNumber | number | 否 | 选择文件/目录最大个数,上限500,有效值范围1-500 | +| defaultFilePathUri | string | 否 | 指定选择的文件或者目录路径 | +| fileSuffixFilters | Array<string> | 否 | 选择文件的后缀类型 | + ## DocumentSaveOptions 文档保存选项。 -**系统能力:** 以下各项对应的系统能力均为 SystemCapability.FileManagement.UserFileService +**系统能力:** SystemCapability.FileManagement.UserFileService | 名称 | 类型 | 必填 | 说明 | | ----------------------- | ------------------- | ---- | ---------------------------- | -| newFileNames? | Array<string> | 否 | 拉起documentPicker进行保存的文件名,若无此参数,则默认需要用户自行输入 | +| newFileNames | Array<string> | 否 | 拉起documentPicker进行保存的文件名,若无此参数,则默认需要用户自行输入 | +| defaultFilePathUri | string | 否 | 指定保存的文件或者目录路径 | +| fileSuffixChoices | Array<string> | 否 | 保存文件的后缀类型 | ## AudioSelectOptions @@ -765,8 +773,8 @@ async function example() { 音频的保存选项。 -**系统能力:** 以下各项对应的系统能力均为 SystemCapability.FileManagement.UserFileService +**系统能力:** SystemCapability.FileManagement.UserFileService | 名称 | 类型 | 必填 | 说明 | | ----------------------- | ------------------- | ---- | ---------------------------- | -| newFileNames? | Array<string> | 否 | 拉起audioPicker进行保存音频资源的文件名,若无此参数,则默认需要用户自行输入 | +| newFileNames | Array<string> | 否 | 拉起audioPicker进行保存音频资源的文件名,若无此参数,则默认需要用户自行输入 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-http.md b/zh-cn/application-dev/reference/apis/js-apis-http.md index f9493fbfcfadba201170f6bd80470cdd10750f41..6e867d3f132a5e54ef3219a9638d105eb6d91347 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-http.md +++ b/zh-cn/application-dev/reference/apis/js-apis-http.md @@ -874,7 +874,7 @@ httpRequest.off('dataReceiveProgress'); | 名称 | 类型 | 必填 | 说明 | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | method | [RequestMethod](#requestmethod) | 否 | 请求方式,默认为GET。 | -| extraData | string6+ \| Object6+ \| ArrayBuffer8+ | 否 | 发送请求的额外数据,默认无此字段。
- 当HTTP请求为POST、PUT等方法时,此字段为HTTP请求的content,以UTF-8编码形式作为请求体。当'Content-Type'为'application/x-www-form-urlencoded'时,请求提交的信息主体数据应在key和value进行URL转码后按照键值对"key1=value1&key2=value2&key3=value3"的方式进行编码。- 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT等方法时,此字段为HTTP请求参数的补充。开发者需传入Encode编码后的string类型参数,Object类型的参数无需预编码,参数内容会拼接到URL中进行发送;ArrayBuffer类型的参数不会做拼接处理。| +| extraData | string6+ \| Object6+ \| ArrayBuffer8+ | 否 | 发送请求的额外数据,默认无此字段。
- 当HTTP请求为POST、PUT等方法时,此字段为HTTP请求的content,以UTF-8编码形式作为请求体。当'Content-Type'为'application/x-www-form-urlencoded'时,请求提交的信息主体数据应在key和value进行URL转码后按照键值对"key1=value1&key2=value2&key3=value3"的方式进行编码,以字符串形式传入。
- 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT等方法时,此字段为HTTP请求参数的补充。开发者需传入Encode编码后的string类型参数,Object类型的参数无需预编码,参数内容会拼接到URL中进行发送;ArrayBuffer类型的参数不会做拼接处理。| | expectDataType9+ | [HttpDataType](#httpdatatype9) | 否 | 指定返回数据的类型,默认无此字段。如果设置了此参数,系统将优先返回指定的类型。 | | usingCache9+ | boolean | 否 | 是否使用缓存,默认为true。 | | priority9+ | number | 否 | 优先级,范围[1,1000],默认是1。 | @@ -883,7 +883,7 @@ httpRequest.off('dataReceiveProgress'); | connectTimeout | number | 否 | 连接超时时间。单位为毫秒(ms),默认为60000ms。 | | usingProtocol9+ | [HttpProtocol](#httpprotocol9) | 否 | 使用协议。默认值由系统自动指定。 | | usingProxy10+ | boolean \| Object | 否 | 是否使用HTTP代理,默认为false,不使用代理。
- 当usingProxy为布尔类型true时,使用默认网络代理。
- 当usingProxy为object类型时,使用指定网络代理。 -| caPath10+ | string | 否 | 如果设置了此参数,系统将使用用户指定路径的CA证书,否则将使用系统预设CA证书。 | +| caPath10+ | string | 否 | 如果设置了此参数,系统将使用用户指定路径的CA证书,否则将使用系统预设CA证书;证书路径为沙箱映射路径,系统预设CA证书位置:/etc/ssl/certs/cacert.pem,建议用户的CA证书存放在此路径下,目前仅支持后缀名为.pem的文本格式证书。 | ## RequestMethod6+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-huks.md b/zh-cn/application-dev/reference/apis/js-apis-huks.md index 9435650e018b8b97375756d5c5b95960fd75e876..35a639c989a2d4e581dc421c706e76e47c98f38d 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-huks.md +++ b/zh-cn/application-dev/reference/apis/js-apis-huks.md @@ -6,6 +6,7 @@ HUKS所管理的密钥可以由应用导入或者由应用调用HUKS接口生成 > **说明** > > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 以下示例代码片段仅适用于JS语言开发。 ## 导入模块 @@ -896,7 +897,7 @@ async function TestExportFunc(alias, options) { } } -function exportKey(alias, options) : Promise { +function exportKey(alias, options) { return new Promise((resolve, reject) => { try { huks.exportKeyItem(alias, options, function (error, data) { @@ -1652,7 +1653,6 @@ finishSession操作密钥接口,使用Callback回调异步返回结果。huks. | -------- | ---------------------------------------------------- | ---- | -------------------------------------------- | | handle | number | 是 | finishSession操作的handle。 | | options | [HuksOptions](#huksoptions) | 是 | finishSession的参数集合。 | -| token | Uint8Array | 是 | finishSession操作的token。 | | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | 是 | 回调函数。将finishSession操作的结果添加到密钥管理系统的回调。 | **错误码:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md index ed1b7034a08d789913d3abb9656d11c218142b9c..e317034f81cc54c30b84310e640b213dc01b7134 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md @@ -27,7 +27,6 @@ import Want from '@ohos.app.ability.Want'; | action | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。具体参考:[action说明](js-apis-ability-wantConstant.md#wantconstantaction)。隐式Want定义及匹配规则参考:[显式Want与隐式Want匹配规则](../../application-models/explicit-implicit-want-mappings.md)。 | | parameters | {[key: string]: Object} | 否 | 表示WantParams,由开发者自行决定传入的键值对。默认会携带以下key值:
ohos.aafwk.callerPid 表示拉起方的pid。
ohos.aafwk.param.callerToken 表示拉起方的token。
ohos.aafwk.param.callerUid 表示[bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo)中的uid,应用包里应用程序的uid。
- component.startup.newRules:表示是否启用新的管控规则。
- moduleName:表示拉起方的模块名,该字段的值即使定义成其他字符串,在传递到另一端时会被修改为正确的值。
- ohos.dlp.params.sandbox:表示dlp文件才会有。 | | entities | Array\ | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器),在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。具体参考:[entity说明](js-apis-app-ability-wantConstant.md#wantconstantentity)。 | -| moduleName10+ | string | 否 | 表示待启动的Ability所属的模块(module)。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md index 5b6a53f1434d60a7dc658f62f893d13d9f6d7683..ae9065fb26bfe209b7776a4c86a1892f6076fe88 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md @@ -1231,7 +1231,7 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout?: number): Promise | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | 是 | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) 实例 | -| timeout | number | 是 | 超时最大等待时间,以毫秒为单位。 | +| timeout | number | 否 | 超时最大等待时间,以毫秒为单位。 | **返回值:** @@ -1280,7 +1280,7 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout: number, callback: | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | 是 | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) 实例 | -| timeout | number | 否 | 超时最大等待时间,以毫秒为单位。 | +| timeout | number | 是 | 超时最大等待时间,以毫秒为单位。 | | callback | AsyncCallback\ | 是 | 成功返回AbilityStage对象,失败返回空。 | **错误码**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationContext.md index 94730d5e4f6656d9b62e3ef7649c507f184c49f8..aef767e99bd639816a8c132cc435a7c3428f5c66 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationContext.md @@ -321,42 +321,6 @@ export default class MyAbility extends UIAbility { } ``` -## ApplicationContext.off(type: 'applicationStateChange', callback: AsyncCallback\)10+ - -off(type: 'applicationStateChange', callback: AsyncCallback<**void**>): **void**; - -取消当前应用指定的前后台变化的监听。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------ | ---- | -------------------------------- | -| type | string | 是 | 取消监听事件的类型,必须为'applicationStateChange'。 | -| callback | AsyncCallback\ | 否 | 删除指定callback对应的注册监听。 | - -**示例:** - -```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - -export default class EntryAbility extends UIAbility { - onDestroy() { - globalThis.applicationStateChangeCallback = { - onApplicationForeground() { - console.info('applicationStateChangeCallback onApplicationForeground'); - }, - onApplicationBackground() { - console.info('applicationStateChangeCallback onApplicationBackground'); - } - } - let applicationContext = this.context.getApplicationContext(); - applicationContext.off('applicationStateChange', globalThis.ApplicationStateChangeCallback); - } -} -``` - ## ApplicationContext.off(type: 'applicationStateChange')10+ off(type: 'applicationStateChange', callback?: ApplicationStateChangeCallback): **void**; diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md index 12ae5dc96eadab1e23ca826de4733256b52c82f7..24d7470fd3a600322d98a00138e6443143f4eec7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md @@ -18,13 +18,13 @@ import appManager from '@ohos.app.ability.appManager'; **系统API**:该接口为系统接口,三方应用不支持调用。 -| 名称 | | 类型 | 可读 | 可写 | 说明 | -| ----------------------- | ---------| ---- | ---- | ------------------------- | ------------------------- | -| onForegroundApplicationChanged | [AppStateData](js-apis-inner-application-appStateData.md) | AsyncCallback\ | 是 | 否 | 应用前后台状态发生变化时执行的回调函数。 | -| onAbilityStateChanged | [AbilityStateData](js-apis-inner-application-abilityStateData.md) | AsyncCallback\ | 是 | 否 | ability状态发生变化时执行的回调函数。 | -| onProcessCreated | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | 是 | 否 | 进程创建时执行的回调函数。 | -| onProcessDied | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | 是 | 否 | 进程销毁时执行的回调函数。 | -| onProcessStateChanged9+ | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | 是 | 否 | 进程状态更新时执行的回调函数。 | +| 名称 | | 类型 | 可读 | 可写 | 说明 | +| -------------------------------- | -----------------------------------------------------------------| ---------------------- | ---- | ---- | ------------------ | +| onForegroundApplicationChanged | [AppStateData](js-apis-inner-application-appStateData.md) | AsyncCallback\ | 是 | 否 | 应用前后台状态发生变化时执行的回调函数。 | +| onAbilityStateChanged | [AbilityStateData](js-apis-inner-application-abilityStateData.md) | AsyncCallback\ | 是 | 否 | ability状态发生变化时执行的回调函数。 | +| onProcessCreated | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | 是 | 否 | 进程创建时执行的回调函数。 | +| onProcessDied | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | 是 | 否 | 进程销毁时执行的回调函数。 | +| onProcessStateChanged9+ | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | 是 | 否 | 进程状态更新时执行的回调函数。 | **示例:** ```ts diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-context.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-context.md index 7f819d1cc5957a87bed64fe5330b830dd1db1a5f..d6668198c5d5e9b762005936dd430a88556ec12b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-context.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-context.md @@ -97,6 +97,8 @@ try { } ``` +> 说明:仅支持获取本应用中其他Module的Context和[应用内HSP](../../../application-dev/quick-start/in-app-hsp.md)的Context,不支持获取其他应用的Context和[应用间HSP](../../../application-dev/quick-start/cross-app-hsp.md)的Context。 + ## Context.createModuleContext createModuleContext(bundleName: string, moduleName: string): Context; @@ -200,7 +202,7 @@ try { ## Context.getGroupDir10+ -getGroupDir(dataGroupID: string, callback: AsyncCallback\); +getGroupDir(dataGroupID: string, callback: AsyncCallback\): void; 通过使用元服务应用中的Group ID获取对应的共享目录,使用callback异步回调。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md index 80d383a3361402388c119cfe846c2332d04d1913..ed6f806ee0cbbeb465e4f07a9e69cf6ee3f49838 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md @@ -164,6 +164,7 @@ connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; | 16000001 | The specified ability does not exist. | | 16000002 | Incorrect ability type. | | 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | | 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000053 | The ability is not on the top of the UI. | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionInfo.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionInfo.md index c32c64357750d3c6d7e859d0d05cc8aafe0c674d..6112abf7c63f1e45f6f1a5c00703939f5b091a3c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionInfo.md @@ -28,7 +28,7 @@ import missionManager from '@ohos.app.ability.missionManager'; | label | string | 是 | 是 | 表示任务的标签。 | | iconPath | string | 是 | 是 | 表示任务的图标路径。 | | continuable | boolean | 是 | 是 | 表示任务是否可以迁移。 | -| abilityState | number | 是 | 是 | 表示此任务的能力状态。 | +| abilityState10+ | number | 是 | 是 | 表示此任务的能力状态。 | | unclearable10+ | boolean | 是 | 是 | 表示任务是否可以被用户手动删除。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md index 98908a1b1657f4bc1893d6faa8c7fab8ab243fc2..4bbe8559d9592c5809823dfb995164182bebef1e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md @@ -736,7 +736,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ ## ServiceExtensionContext.startAbilityAsCaller10+ -starAbilityAsCaller(want: Want, callback: AsyncCallback): void; +starAbilityAsCaller(want: Want, callback: AsyncCallback\): void; 使用设置的caller信息启动一个Ability,caller信息由want携带,在系统服务层识别,Ability可以在onCreate生命周期的want参数中获取到caller信息。使用该接口启动一个Ability时,want的caller信息不会被当前自身的应用信息覆盖,系统服务层可获取到初始caller的信息。使用callback异步回调。 @@ -807,7 +807,7 @@ export default class EntryAbility extends extension { ## UIAbiliServiceExtensionContexttyContext.startAbilityAsCaller10+ -startAbilityAsCaller(want: Want, options: StartOptions, callback: AsyncCallback): void; +startAbilityAsCaller(want: Want, options: StartOptions, callback: AsyncCallback\): void; 使用设置的caller信息启动一个Ability,caller信息由want携带,在系统服务层识别,Ability可以在onCreate生命周期的want参数中获取到caller信息。使用该接口启动一个Ability时,want的caller信息不会被当前自身的应用信息覆盖,系统服务层可获取到初始caller的信息。使用callback异步回调。 @@ -833,13 +833,11 @@ startAbilityAsCaller(want: Want, options: StartOptions, callback: AsyncCallback< | 错误码ID | 错误信息 | | ------- | -------------------------------- | | 16000001 | The specified ability does not exist. | -| 16000002 | Incorrect ability type. | | 16000004 | Can not start invisible component. | | 16000005 | The specified process does not have the permission. | | 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000009 | An ability cannot be started or stopped in Wukong mode. | -| 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | | 16000012 | The application is controlled. | | 16000013 | The application is controlled by EDM. | @@ -883,7 +881,7 @@ export default class EntryAbility extends extension { ## ServiceExtensionContext.startAbilityAsCaller10+ -startAbilityAsCaller(want: Want, options?: StartOptions): Promise; +startAbilityAsCaller(want: Want, options?: StartOptions): Promise\; 使用设置的caller信息启动一个Ability,caller信息由want携带,在系统服务层识别,Ability可以在onCreate生命周期的want参数中获取到caller信息。使用该接口启动一个Ability时,want的caller信息不会被当前自身的应用信息覆盖,系统服务层可获取到初始caller的信息。使用Promise异步回调。 @@ -901,7 +899,7 @@ startAbilityAsCaller(want: Want, options?: StartOptions): Promise; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | -| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 | +| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 | **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md index 0e0cc543271976b40f60ae7b5c4ad23e50ff2734..5ee5bb06f7185547e2bc37d254845875941fa7c2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md @@ -1529,6 +1529,7 @@ connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options | 16000001 | The specified ability does not exist. | | 16000002 | Incorrect ability type. | | 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | | 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000053 | The ability is not on the top of the UI. | @@ -2795,7 +2796,7 @@ startAbilityByCallWithAccount(want: Want, accountId: number): Promise<Caller& ## UIAbilityContext.startAbilityAsCaller10+ -starAbilityAsCaller(want: Want, callback: AsyncCallback): void; +starAbilityAsCaller(want: Want, callback: AsyncCallback\): void; 使用设置的caller信息启动一个Ability,caller信息由want携带,在系统服务层识别,Ability可以在onCreate生命周期的want参数中获取到caller信息。使用该接口启动一个Ability时,want的caller信息不会被当前自身的应用信息覆盖,系统服务层可获取到初始caller的信息。使用callback异步回调。 @@ -2806,6 +2807,8 @@ starAbilityAsCaller(want: Want, callback: AsyncCallback): void; **系统能力**:SystemCapability.Ability.AbilityRuntime.Core +**系统API**:此接口为系统接口,三方应用不支持调用。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2864,7 +2867,7 @@ export default class EntryAbility extends UIAbility { ## UIAbilityContext.startAbilityAsCaller10+ -startAbilityAsCaller(want: Want, options: StartOptions, callback: AsyncCallback): void; +startAbilityAsCaller(want: Want, options: StartOptions, callback: AsyncCallback\): void; 使用设置的caller信息启动一个Ability,caller信息由want携带,在系统服务层识别,Ability可以在onCreate生命周期的want参数中获取到caller信息。使用该接口启动一个Ability时,want的caller信息不会被当前自身的应用信息覆盖,系统服务层可获取到初始caller的信息。使用callback异步回调。 @@ -2875,6 +2878,8 @@ startAbilityAsCaller(want: Want, options: StartOptions, callback: AsyncCallback< **系统能力**:SystemCapability.Ability.AbilityRuntime.Core +**系统API**:此接口为系统接口,三方应用不支持调用。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2888,13 +2893,11 @@ startAbilityAsCaller(want: Want, options: StartOptions, callback: AsyncCallback< | 错误码ID | 错误信息 | | ------- | -------------------------------- | | 16000001 | The specified ability does not exist. | -| 16000002 | Incorrect ability type. | | 16000004 | Can not start invisible component. | | 16000005 | The specified process does not have the permission. | | 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000009 | An ability cannot be started or stopped in Wukong mode. | -| 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | | 16000012 | The application is controlled. | | 16000013 | The application is controlled by EDM. | @@ -2919,7 +2922,7 @@ export default class EntryAbility extends UIAbility { localWant.moduleName = 'entry'; localWant.abilityName = 'TestAbility'; - let option: StartOptions = { + let option = { displayId: 0 } @@ -2938,7 +2941,7 @@ export default class EntryAbility extends UIAbility { ## UIAbilityContext.startAbilityAsCaller10+ -startAbilityAsCaller(want: Want, options?: StartOptions): Promise; +startAbilityAsCaller(want: Want, options?: StartOptions): Promise\; 使用设置的caller信息启动一个Ability,caller信息由want携带,在系统服务层识别,Ability可以在onCreate生命周期的want参数中获取到caller信息。使用该接口启动一个Ability时,want的caller信息不会被当前自身的应用信息覆盖,系统服务层可获取到初始caller的信息。使用Promise异步回调。 @@ -2949,12 +2952,14 @@ startAbilityAsCaller(want: Want, options?: StartOptions): Promise; **系统能力**:SystemCapability.Ability.AbilityRuntime.Core +**系统API**:此接口为系统接口,三方应用不支持调用。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | -| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 | +| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 | **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md b/zh-cn/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md index caa6b850cd30c9ac9b7c331bef6c983ba33f5a23..8d8f07e3d614c0503b2a06647504bc0c85484124 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md @@ -10,15 +10,17 @@ ```ts import CommonEvent from '@ohos.commonEvent'; -let subscriber; // 用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 +import CommonEventManager from '@ohos.commonEventManager'; +import Base from '@ohos.base'; +let subscriber:CommonEventManager.CommonEventSubscriber; // 用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 // 订阅者信息 -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; // 创建订阅者回调 -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if (err.code) { console.error(`createSubscriber failed, code is ${err.code}`); } else { @@ -49,7 +51,7 @@ getCode(callback: AsyncCallback\): void ```ts //获取有序公共事件代码回调 -function getCodeCB(err, code) { +function getCodeCB(err:Base.BusinessError, code:number) { if (err.code) { console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); } else { @@ -76,9 +78,9 @@ getCode(): Promise\ **示例:** ```ts -subscriber.getCode().then((code) => { +subscriber.getCode().then((code:number) => { console.info("getCode " + JSON.stringify(code)); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -102,7 +104,7 @@ setCode(code: number, callback: AsyncCallback\): void ```ts //设置有序公共事件的代码回调 -function setCodeCB(err) { +function setCodeCB(err:Base.BusinessError) { if (err.code) { console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); } else { @@ -137,7 +139,7 @@ setCode(code: number): Promise\ ```ts subscriber.setCode(1).then(() => { console.info("setCode"); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -160,7 +162,7 @@ getData(callback: AsyncCallback\): void ```ts //获取有序公共事件代码数据回调 -function getDataCB(err, data) { +function getDataCB(err:Base.BusinessError, data:string) { if (err.code) { console.error(`getData failed, code is ${err.code}, message is ${err.message}`); } else { @@ -187,9 +189,9 @@ getData(): Promise\ **示例:** ```ts -subscriber.getData().then((data) => { +subscriber.getData().then((data:string) => { console.info("getData " + JSON.stringify(data)); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`getData failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -213,7 +215,7 @@ setData(data: string, callback: AsyncCallback\): void ```ts //设置有序公共事件的结果数据回调 -function setDataCB(err) { +function setDataCB(err:Base.BusinessError) { if (err.code) { console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); } else { @@ -248,7 +250,7 @@ setData(data: string): Promise\ ```ts subscriber.setData("publish_data_changed").then(() => { console.info("setData"); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -273,7 +275,7 @@ setCodeAndData(code: number, data: string, callback:AsyncCallback\): void ```ts //设置有序公共事件的代码和数据回调 -function setCodeDataCB(err) { +function setCodeDataCB(err:Base.BusinessError) { if (err.code) { console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); } else { @@ -309,7 +311,7 @@ setCodeAndData(code: number, data: string): Promise\ ```ts subscriber.setCodeAndData(1, "publish_data_changed").then(() => { console.info("setCodeAndData"); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -334,7 +336,7 @@ isOrderedCommonEvent(callback: AsyncCallback\): void ```ts //获取当前公共事件是否为有序事件的回调 -function isOrderedCB(err, isOrdered) { +function isOrderedCB(err:Base.BusinessError, isOrdered:boolean) { if (err.code) { console.error(`isOrderedCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { @@ -363,9 +365,9 @@ isOrderedCommonEvent(): Promise\ **示例:** ```ts -subscriber.isOrderedCommonEvent().then((isOrdered) => { +subscriber.isOrderedCommonEvent().then((isOrdered:boolean) => { console.info("isOrdered " + JSON.stringify(isOrdered)); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`isOrdered failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -390,7 +392,7 @@ isStickyCommonEvent(callback: AsyncCallback\): void ```ts //获取当前公共事件是否为粘性事件的回调 -function isStickyCB(err, isSticky) { +function isStickyCB(err:Base.BusinessError, isSticky:boolean) { if (err.code) { console.error(`isStickyCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { @@ -419,9 +421,9 @@ isStickyCommonEvent(): Promise\ **示例:** ```ts -subscriber.isStickyCommonEvent().then((isSticky) => { +subscriber.isStickyCommonEvent().then((isSticky:boolean) => { console.info("isSticky " + JSON.stringify(isSticky)); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`isSticky failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -444,7 +446,7 @@ abortCommonEvent(callback: AsyncCallback\): void ```ts //取消当前有序公共事件的回调 -function abortCB(err) { +function abortCB(err:Base.BusinessError) { if (err.code) { console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { @@ -473,7 +475,7 @@ abortCommonEvent(): Promise\ ```ts subscriber.abortCommonEvent().then(() => { console.info("abortCommonEvent"); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -496,7 +498,7 @@ clearAbortCommonEvent(callback: AsyncCallback\): void ```ts //清除当前公共事件取消状态的回调 -function clearAbortCB(err) { +function clearAbortCB(err:Base.BusinessError) { if (err.code) { console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { @@ -525,7 +527,7 @@ clearAbortCommonEvent(): Promise\ ```ts subscriber.clearAbortCommonEvent().then(() => { console.info("clearAbortCommonEvent"); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -548,7 +550,7 @@ getAbortCommonEvent(callback: AsyncCallback\): void ```ts //获取当前有序公共事件是否取消的回调 -function getAbortCB(err, abortEvent) { +function getAbortCB(err:Base.BusinessError, abortEvent:boolean) { if (err.code) { console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { @@ -575,9 +577,9 @@ getAbortCommonEvent(): Promise\ **示例:** ```ts -subscriber.getAbortCommonEvent().then((abortEvent) => { +subscriber.getAbortCommonEvent().then((abortEvent:boolean) => { console.info("abortCommonEvent " + JSON.stringify(abortEvent)); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -600,7 +602,7 @@ getSubscribeInfo(callback: AsyncCallback\): void ```ts //获取订阅者信息回调 -function getCB(err, subscribeInfo) { +function getCB(err:Base.BusinessError, subscribeInfo:CommonEventManager.CommonEventSubscribeInfo) { if (err.code) { console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); } else { @@ -627,9 +629,9 @@ getSubscribeInfo(): Promise\ **示例:** ```ts -subscriber.getSubscribeInfo().then((subscribeInfo) => { +subscriber.getSubscribeInfo().then((subscribeInfo:CommonEventManager.CommonEventSubscribeInfo) => { console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -652,7 +654,7 @@ finishCommonEvent(callback: AsyncCallback\): void ```ts //结束当前有序公共事件的回调 -function finishCB(err) { +function finishCB(err:Base.BusinessError) { if (err.code) { console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { @@ -682,7 +684,7 @@ finishCommonEvent(): Promise\ ```ts subscriber.finishCommonEvent().then(() => { console.info("FinishCommonEvent"); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); }); ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md index 51816f591c664cdb73d6a3c9bdf2fd88c543a857..6cf91a1a0efd19297b732f331ca2eefe69242d89 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md @@ -10,45 +10,45 @@ **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification -| 名称 | 类型 | 必填 | 说明 | -| --------------------- | --------------------------------------------- | --- |-----------------------------------------------------------------------| -| content | [NotificationContent](js-apis-inner-notification-notificationContent.md#notificationcontent) | 是 | 通知内容。 | -| id | number | 否 | 通知ID。 | -| slotType | [SlotType](js-apis-notificationManager.md#slottype) | 否 | 通道类型。 | -| isOngoing | boolean | 否 | 是否进行时通知。 | -| isUnremovable | boolean | 否 | 是否可移除(应用于长时间通知任务上,比如地图、音乐播放;点击通知下方删除按钮无法删除,左滑点击单个删除按钮可删除)。 | -| deliveryTime | number | 否 | 通知发送时间。 | -| tapDismissed | boolean | 否 | 通知是否自动清除。 | -| autoDeletedTime | number | 否 | 自动清除的时间。 | -| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | 否 | WantAgent封装了应用的行为意图,点击通知时触发该行为。 | -| extraInfo | {[key: string]: any} | 否 | 扩展参数。 | -| color | number | 否 | 通知背景颜色。预留能力,暂未支持。 | -| colorEnabled | boolean | 否 | 通知背景颜色是否使能。预留能力,暂未支持。 | -| isAlertOnce | boolean | 否 | 设置是否仅有一次此通知提醒。 | -| isStopwatch | boolean | 否 | 是否显示已用时间。 | -| isCountDown | boolean | 否 | 是否显示倒计时时间。 | -| isFloatingIcon | boolean | 否 | 是否显示状态栏图标。 | -| label | string | 否 | 通知标签。 | -| badgeIconStyle | number | 否 | 通知角标类型。预留能力,暂未支持。 | -| showDeliveryTime | boolean | 否 | 是否显示分发时间。 | -| actionButtons | Array\<[NotificationActionButton](js-apis-inner-notification-notificationActionButton.md)\> | 否 | 通知按钮,最多三个按钮。 | -| smallIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | 否 | 通知小图标。可选字段,大小不超过30KB。 | -| largeIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | 否 | 通知大图标。可选字段,大小不超过30KB。 | -| creatorBundleName | string | 否 | 创建通知的包名。 | -| creatorUid | number | 否 | 创建通知的UID。 | -| creatorPid | number | 否 | 创建通知的PID。 | -| creatorUserId8+ | number | 否 | 创建通知的UserId。 | -| hashCode | string | 否 | 通知唯一标识。 | -| classification | string | 否 | 通知分类。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | -| groupName8+ | string | 否 | 组通知名称。 | -| template8+ | [NotificationTemplate](./js-apis-inner-notification-notificationTemplate.md) | 否 | 通知模板。 | -| isRemoveAllowed10+ | boolean | 否 | 通知是否能被移除(点击通知下方删除按钮无法删除,左滑不出现删除按钮)。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | -| source8+ | number | 否 | 通知源。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | +| 名称 | 类型 | 必填 | 说明 | +|-------------------------------| --------------------------------------------- | --- |-----------------------------------------------------------------------| +| content | [NotificationContent](js-apis-inner-notification-notificationContent.md#notificationcontent) | 是 | 通知内容。 | +| id | number | 否 | 通知ID。 | +| slotType | [SlotType](js-apis-notificationManager.md#slottype) | 否 | 通道类型。 | +| isOngoing | boolean | 否 | 是否进行时通知。 | +| isUnremovable | boolean | 否 | 是否可移除(应用于长时间通知任务上,比如地图、音乐播放;点击通知下方删除按钮无法删除,左滑点击单个删除按钮可删除)。 | +| deliveryTime | number | 否 | 通知发送时间。 | +| tapDismissed | boolean | 否 | 通知是否自动清除。 | +| autoDeletedTime | number | 否 | 自动清除的时间。 | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | 否 | WantAgent封装了应用的行为意图,点击通知时触发该行为。 | +| extraInfo | {[key: string]: any} | 否 | 扩展参数。 | +| color | number | 否 | 通知背景颜色。预留能力,暂未支持。 | +| colorEnabled | boolean | 否 | 通知背景颜色是否使能。预留能力,暂未支持。 | +| isAlertOnce | boolean | 否 | 设置是否仅有一次此通知提醒。 | +| isStopwatch | boolean | 否 | 是否显示已用时间。 | +| isCountDown | boolean | 否 | 是否显示倒计时时间。 | +| isFloatingIcon | boolean | 否 | 是否显示状态栏图标。 | +| label | string | 否 | 通知标签。 | +| badgeIconStyle | number | 否 | 通知角标类型。预留能力,暂未支持。 | +| showDeliveryTime | boolean | 否 | 是否显示分发时间。 | +| actionButtons | Array\<[NotificationActionButton](js-apis-inner-notification-notificationActionButton.md)\> | 否 | 通知按钮,最多三个按钮。 | +| smallIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | 否 | 通知小图标。可选字段,大小不超过30KB。 | +| largeIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | 否 | 通知大图标。可选字段,大小不超过30KB。 | +| creatorBundleName | string | 否 | 创建通知的包名。 | +| creatorUid | number | 否 | 创建通知的UID。 | +| creatorPid | number | 否 | 创建通知的PID。 | +| creatorUserId8+ | number | 否 | 创建通知的UserId。 | +| hashCode | string | 否 | 通知唯一标识。 | +| classification | string | 否 | 通知分类。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | +| groupName8+ | string | 否 | 组通知名称。 | +| template8+ | [NotificationTemplate](./js-apis-inner-notification-notificationTemplate.md) | 否 | 通知模板。 | +| isRemoveAllowed8+ | boolean | 否 | 通知是否能被移除(点击通知下方删除按钮无法删除,左滑不出现删除按钮)。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | +| source8+ | number | 否 | 通知源。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | | distributedOption8+ | [DistributedOptions](#distributedoptions) | 否 | 分布式通知的选项。 | -| deviceId8+ | string | 否 | 通知源的deviceId。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | +| deviceId8+ | string | 否 | 通知源的deviceId。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | | notificationFlags8+ | [NotificationFlags](js-apis-inner-notification-notificationFlags.md#notificationflags) | 否 | 获取NotificationFlags。 | -| removalWantAgent9+ | [WantAgent](js-apis-app-ability-wantAgent.md) | 否 | 当移除通知时,通知将被重定向到的WantAgent实例。 | -| badgeNumber9+ | number | 否 | 应用程序图标上显示的通知数。 | +| removalWantAgent9+ | [WantAgent](js-apis-app-ability-wantAgent.md) | 否 | 当移除通知时,通知将被重定向到的WantAgent实例。 | +| badgeNumber9+ | number | 否 | 应用程序图标上显示的通知数。 | ## DistributedOptions diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationSorting.md b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationSorting.md index 70dd4d279f45fa861f30fd73251b789b0fa38d30..d1f94427360659e27da7b02f6eba9be967a30587 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationSorting.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationSorting.md @@ -12,8 +12,8 @@ **系统接口**: 以下为系统接口,三方应用不支持调用。 -| 名称 | 类型 | 必填 | 说明 | -| -------------------- | --------------------- | --- | ------------------------------------------ | -| slot | [NotificationSlot](js-apis-inner-notification-notificationSlot.md) | 是 | 通道类型。 | -| level | number | 是 | 通知级别,不设置则根据通知渠道类型有默认值。 | -| desc | string | 是 | 通知渠道描述信息。 | +| 名称 | 类型 | 必填 | 说明 | +|---------| --------------------- | --- |------------------------| +| slot | [NotificationSlot](js-apis-inner-notification-notificationSlot.md) | 是 | 通道类型。 | +| ranking | number | 是 | 通知级别,不设置则根据通知渠道类型有默认值。 | +| hashCode | string | 是 | 通知唯一标识。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-installer.md b/zh-cn/application-dev/reference/apis/js-apis-installer.md index e780af2ce6b5924416231b353e59aca25e76a7c6..95ea29e2378213b65cb0521c1aa99cdf72d5ff61 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-installer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-installer.md @@ -40,7 +40,7 @@ getBundleInstaller(callback: AsyncCallback\): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback\<[BundleInstaller](js-apis-installer.md#BundleInstaller)> | 是 | 回调函数,获取BundleInstaller对象,err为undefined,data为获取到的BundleInstaller对象;否则为错误对象。 | +| callback | AsyncCallback\<[BundleInstaller](js-apis-installer.md#BundleInstaller)> | 是 | 回调函数,获取BundleInstaller对象,err为null,data为获取到的BundleInstaller对象;否则为错误对象。 | **示例:** @@ -91,6 +91,34 @@ try { } ``` +## BundleInstaller.getBundleInstallerSync10+ + +getBundleInstallerSync(): BundleInstaller; + +获取并返回BundleInstaller对象。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**返回值:** +| 类型 | 说明 | +| ------------------------------------------------------------ | ------------------------------------ | +| [BundleInstaller](js-apis-installer.md#BundleInstaller) | 返回BundleInstaller对象。 | + +**示例:** + +```ts +import installer from '@ohos.bundle.installer'; + +try { + installer.getBundleInstallerSync(); + console.info('getBundleInstallerSync successfully.'); +} catch (error) { + console.error('getBundleInstallerSync failed. Cause: ' + error.message); +} +``` + ## BundleInstaller.install install(hapFilePaths: Array<string>, installParam: InstallParam, callback: AsyncCallback<void>): void; @@ -117,7 +145,7 @@ install(hapFilePaths: Array<string>, installParam: InstallParam, callback: | --------------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | | hapFilePaths | Array<string> | 是 | 存储应用程序包的路径。路径应该是当前应用程序中存放HAP的数据目录。当传入的路径是一个目录时, 该目录下只能放同一个应用的HAP,且这些HAP的签名需要保持一致。 | | installParam | [InstallParam](#installparam) | 是 | 指定安装所需的其他参数。 | -| callback | AsyncCallback<void> | 是 | 回调函数,安装应用成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数,安装应用成功,err为null,否则为错误对象。 | **错误码:** @@ -196,7 +224,7 @@ install(hapFilePaths: Array<string>, callback: AsyncCallback<void>): | 参数名 | 类型 | 必填 | 说明 | | --------------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | | hapFilePaths | Array<string> | 是 | 存储应用程序包的路径。路径应该是当前应用程序中存放HAP的数据目录。当传入的路径是一个目录时, 该目录下只能放同一个应用的HAP,且这些HAP的签名需要保持一致。 | -| callback | AsyncCallback<void> | 是 | 回调函数,安装应用成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数,安装应用成功,err为null,否则为错误对象。 | **错误码:** @@ -349,7 +377,7 @@ uninstall(bundleName: string, installParam: InstallParam, callback: AsyncCallbac | ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | | bundleName | string | 是 | 待卸载应用的包名。 | | installParam | [InstallParam](#installparam) | 是 | 指定安装所需的其他参数。 | -| callback | AsyncCallback<void> | 是 | 回调函数,卸载应用成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数,卸载应用成功,err为null,否则为错误对象。 | **错误码:** @@ -408,7 +436,7 @@ uninstall(bundleName: string, callback: AsyncCallback<void>): void; | 参数名 | 类型 | 必填 | 说明 | | ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | | bundleName | string | 是 | 待卸载应用的包名。 | -| callback | AsyncCallback<void> | 是 | 回调函数,卸载应用成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数,卸载应用成功,err为null,否则为错误对象。 | **错误码:** @@ -524,7 +552,7 @@ recover(bundleName: string, installParam: InstallParam, callback: AsyncCallback& | ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | | bundleName | string | 是 | 待恢复应用的包名。 | | installParam | [InstallParam](#installparam) | 是 | 指定安装所需的其他参数。 | -| callback | AsyncCallback<void> | 是 | 回调函数,回滚应用成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数,回滚应用成功,err为null,否则为错误对象。 | **错误码:** @@ -581,7 +609,7 @@ recover(bundleName: string, callback: AsyncCallback<void>): void; | 参数名 | 类型 | 必填 | 说明 | | ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | | bundleName | string | 是 | 待恢复应用的包名。 | -| callback | AsyncCallback<void> | 是 | 回调函数,回滚应用成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数,回滚应用成功,err为null,否则为错误对象。 | **错误码:** @@ -691,7 +719,7 @@ uninstall(uninstallParam: UninstallParam, callback : AsyncCallback\) : voi | 参数名 | 类型 | 必填 | 说明 | | -------------- | ----------------------------------- | ---- | -------------------------------------------------------- | | uninstallParam | [UninstallParam](#uninstallparam10) | 是 | 共享包卸载需指定的参数信息。 | -| callback | AsyncCallback<void> | 是 | 回调函数,卸载应用成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数,卸载应用成功,err为null,否则为错误对象。 | **错误码:** @@ -805,7 +833,7 @@ updateBundleForSelf(hapFilePaths: Array\, installParam: InstallParam, c | --------------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | | hapFilePaths | Array<string> | 是 | 存储应用程序包的路径。路径应该是当前应用程序中存放HAP的数据目录。当传入的路径是一个目录时, 该目录下只能放同一个应用的HAP,且这些HAP的签名需要保持一致。 | | installParam | [InstallParam](#installparam) | 是 | 指定安装所需的其他参数。 | -| callback | AsyncCallback<void> | 是 | 回调函数,安装应用成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数,安装应用成功,err为null,否则为错误对象。 | **错误码:** @@ -877,7 +905,7 @@ updateBundleForSelf(hapFilePaths: Array\, callback: AsyncCallback\10+ + +getLauncherAbilityInfoSync(bundleName: string, userId: number) : Array\<[LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md)>; + +查询指定bundleName及用户的[LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md)。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统接口:** 此接口为系统接口 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Launcher + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------ | ---- | -------------- | +| bundleName | string | 是 | 应用Bundle名称。 | +| userId | number | 是 | 被查询的用户id。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------- | -------------------------------------------------- | +| Array\<[LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md)> | Array形式返回bundle包含的[LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md)信息。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 17700001 | The specified bundle name is not found. | +| 17700004 | The specified user ID is not found. | + +**示例:** + +```typescript +import launcherBundleManager from '@ohos.bundle.launcherBundleManager'; + +try { + let data = launcherBundleManager.getLauncherAbilityInfoSync("com.example.demo", 100); + console.log("data is " + JSON.stringify(data)); +} catch (errData) { + console.error(`errData is errCode:${errData.code} message:${errData.message}`); +} +``` + ## launcherBundlemanager.getAllLauncherAbilityInfo9+ getAllLauncherAbilityInfo(userId: number, callback: AsyncCallback>) : void; @@ -305,3 +352,46 @@ try { console.error(`errData is errCode:${errData.code} message:${errData.message}`); } ``` + +## launcherBundlemanager.getShortcutInfoSync10+ + +getShortcutInfoSync(bundleName : string) : Array\<[ShortcutInfo](js-apis-bundleManager-shortcutInfo.md)>; + +查询当前用户下指定应用的[ShortcutInfo](js-apis-bundleManager-shortcutInfo.md)。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统接口:** 此接口为系统接口 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Launcher + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------ | ---- | -------------- | +| bundleName | string | 是 | 应用Bundle名称。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------- | ----------------------------------------------- | +| Array\<[ShortcutInfo](js-apis-bundleManager-shortcutInfo.md)> | Array形式返回当前用户下指定应用的[ShortcutInfo](js-apis-bundleManager-shortcutInfo.md)。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 17700001 | The specified bundle name is not found. | + +**示例:** + +```ts +import launcherBundleManager from '@ohos.bundle.launcherBundleManager'; + +try { + let data = launcherBundleManager.getShortcutInfoSync("com.example.demo"); + console.log("data is " + JSON.stringify(data)); +} catch (errData) { + console.error(`errData is errCode:${errData.code} message:${errData.message}`); +} +``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-media.md b/zh-cn/application-dev/reference/apis/js-apis-media.md index aa8d7827ae60f568260407a9fbcf17b06e615be4..6ead1b2144048a03a7acf751c7cf4785acecc76b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-media.md +++ b/zh-cn/application-dev/reference/apis/js-apis-media.md @@ -1689,6 +1689,10 @@ avPlayer.off('audioInterrupt') **系统能力:** SystemCapability.Multimedia.Media.Core +| 名称 | 类型 | 必填 | 说明 | +| ------------- | ------ | ---- | ------------------------------------------------------------ | +| [key: string] | Object | 是 | 该键值对支持的key取值范围,请参考[MediaDescriptionKey](#mediadescriptionkey8);每个key值的Object类型和范围,请参考[MediaDescriptionKey](#mediadescriptionkey8)对应Key值的说明 | + **示例:** ```js diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-connection.md b/zh-cn/application-dev/reference/apis/js-apis-net-connection.md index a89b8c5a154bd1924cbc8b3ab3d0d1808ab9a86f..f8a0134e8a27bb917fcda98fa0d10b1198e3b32d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-connection.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-connection.md @@ -847,7 +847,7 @@ connection.getDefaultNet().then(function (netHandle) { ## connection.getNetCapabilitiesSync10+ -getNetCapabilities(netHandle: NetHandle): NetCapabilities +getNetCapabilitiesSync(netHandle: NetHandle): NetCapabilities 获取netHandle对应的网络的能力信息,使用同步方式返回。 @@ -1614,7 +1614,7 @@ netCon.unregister(function (error) { ### on('netCapabilitiesChange')8+ -on(type: 'netCapabilitiesChange', callback: Callback): void +on(type: 'netCapabilitiesChange', callback: Callback\): void 订阅网络能力变化事件。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md b/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md index ca406ed0ae385ee789d4a43bd27ea0dd990809d3..51de9fbd339a58588184f48e623b0ecfa15c2a2e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md @@ -2808,7 +2808,76 @@ notificationManager.requestEnableNotification().then(() => { }); ``` +## notificationManager.requestEnableNotification10+ +requestEnableNotification(context: UIAbilityContext, callback: AsyncCallback\): void + +应用请求通知使能模态弹窗(Callback形式)。 + +**系统能力**:SystemCapability.Notification.Notification + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- |--------------------| +| context | UIAbilityContext | 是 | 通知弹窗绑定Ability的上下文。 | +| callback | AsyncCallback\ | 是 | 应用请求通知使能的回调函数。 | + +**错误码:** + +错误码详细介绍请参考[errcode-notification](../errorcodes/errorcode-notification.md)。 + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**示例:** + +```javascript +function requestEnableNotificationCallback(err) { + if (err) { + console.error(`requestEnableNotification failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("requestEnableNotification success"); + } +}; + +notificationManager.requestEnableNotification(globalThis.uicontext, requestEnableNotificationCallback); +``` + +## notificationManager.requestEnableNotification10+ + +requestEnableNotification(context: UIAbilityContext): Promise\ + +应用请求通知使能模态弹窗(Promise形式)。 + +**系统能力**:SystemCapability.Notification.Notification + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- |--------------------| +| context | UIAbilityContext | 是 | 通知弹窗绑定Ability的上下文。 | + +**错误码:** + +错误码详细介绍请参考[errcode-notification](../errorcodes/errorcode-notification.md)。 + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**示例:** + +```javascript +notificationManager.requestEnableNotification(globalThis.uicontext).then(() => { + console.info("requestEnableNotification success"); +}); +``` ## notificationManager.setDistributedEnable diff --git a/zh-cn/application-dev/reference/apis/js-apis-notificationSubscribe.md b/zh-cn/application-dev/reference/apis/js-apis-notificationSubscribe.md index 3969df3f2968d1a8226c360cb29b3e0b17c7d78b..f7dafa9c21bad13a6e0e6aad78b780089423413c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-notificationSubscribe.md +++ b/zh-cn/application-dev/reference/apis/js-apis-notificationSubscribe.md @@ -443,9 +443,9 @@ notificationSubscribe.remove(hashCode, reason).then(() => { console.info("remove success"); }); ``` -## NotificationSubscribe.remove +## NotificationSubscribe.remove10+ -remove(hashCodes: Array\, reason: RemoveReason, callback: AsyncCallback\): void +remove(hashCodes: Array\, reason: RemoveReason, callback: AsyncCallback\): void 批量删除指定通知(Callback形式)。 @@ -459,7 +459,7 @@ remove(hashCodes: Array\, reason: RemoveReason, callback: AsyncCallback | 参数名 | 类型 | 必填 | 说明 | |-----------|-------------------------------| ---- |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| hashCodes | Array\ | 是 | 通知唯一ID数组集合。可以通过[onConsume](js-apis-inner-notification-notificationSubscriber.md#onConsume)回调的入参[SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata)获取其内部[NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest)对象中的hashCode。 | +| hashCodes | Array\ | 是 | 通知唯一ID数组集合。可以通过[onConsume](js-apis-inner-notification-notificationSubscriber.md#onConsume)回调的入参[SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata)获取其内部[NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest)对象中的hashCode。 | | reason | [RemoveReason](#removereason) | 是 | 通知删除原因。 | | callback | AsyncCallback\ | 是 | 删除指定通知回调函数。 | @@ -489,9 +489,9 @@ let reason = notificationSubscribe.RemoveReason.CANCEL_REASON_REMOVE; notificationSubscribe.remove(hashCodes, reason, removeCallback); ``` -## NotificationSubscribe.remove +## NotificationSubscribe.remove10+ -remove(hashCodes: Array\, reason: RemoveReason): Promise\ +remove(hashCodes: Array\, reason: RemoveReason): Promise\ 批量删除指定通知(Promise形式)。 @@ -505,7 +505,7 @@ remove(hashCodes: Array\, reason: RemoveReason): Promise\ | 参数名 | 类型 | 必填 | 说明 | |-----------|-------------------------------| ---- |-------------| -| hashCodes | Array\ | 是 | 通知唯一ID数组集合。 | +| hashCodes | Array\ | 是 | 通知唯一ID数组集合。 | | reason | [RemoveReason](#removereason) | 是 | 通知删除原因。 | **错误码:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-osAccount.md b/zh-cn/application-dev/reference/apis/js-apis-osAccount.md index a2ea82af6c1ee082a1d1da7c06efe698e7417dc7..1cd072550c68993fef0603a419280d6eec78bc19 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-osAccount.md +++ b/zh-cn/application-dev/reference/apis/js-apis-osAccount.md @@ -79,10 +79,10 @@ activateOsAccount(localId: number, callback: AsyncCallback<void>): void **示例:** 激活ID为100的系统帐号 ```js - let accountManager = account_osAccount.getAccountManager(); - let localId = 100; + import { BusinessError } from '@ohos.base'; + let localId: number = 100; try { - accountManager.activateOsAccount(localId, (err)=>{ + accountManager.activateOsAccount(localId, (err: BusinessError)=>{ if (err) { console.error(`activateOsAccount failed, code is ${err.code}, message is ${err.message}`); } else { @@ -130,12 +130,13 @@ activateOsAccount(localId: number): Promise<void> **示例:** 激活ID为100的系统帐号 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; + let localId: number = 100; try { accountManager.activateOsAccount(localId).then(() => { console.log('activateOsAccount successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('activateOsAccount failed, err:' + JSON.stringify(err)); }); } catch (e) { @@ -166,9 +167,10 @@ checkMultiOsAccountEnabled(callback: AsyncCallback<boolean>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.checkMultiOsAccountEnabled((err, isEnabled) => { + accountManager.checkMultiOsAccountEnabled((err: BusinessError, isEnabled: boolean) => { if (err) { console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`); } else { @@ -203,11 +205,12 @@ checkMultiOsAccountEnabled(): Promise<boolean> **示例:** ```js + import { BusinessError } from '@ohos.base'; try { let accountManager = account_osAccount.getAccountManager(); - accountManager.checkMultiOsAccountEnabled().then((isEnabled) => { + accountManager.checkMultiOsAccountEnabled().then((isEnabled: boolean) => { console.log('checkMultiOsAccountEnabled successfully, isEnabled: ' + isEnabled); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`); }); } catch (err) { @@ -243,10 +246,11 @@ checkOsAccountActivated(localId: number, callback: AsyncCallback<boolean>) **示例:** 判断ID为100的系统帐号是否处于激活状态 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; + let localId: number = 100; try { - accountManager.checkOsAccountActivated(localId, (err, isActivated) => { + accountManager.checkOsAccountActivated(localId, (err: BusinessError, isActivated: boolean) => { if (err) { console.log('checkOsAccountActivated failed, error:' + JSON.stringify(err)); } else { @@ -291,12 +295,13 @@ checkOsAccountActivated(localId: number): Promise<boolean> **示例:** 判断ID为100的系统帐号是否处于激活状态 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; + let localId: number = 100; try { - accountManager.checkOsAccountActivated(localId).then((isActivated) => { + accountManager.checkOsAccountActivated(localId).then((isActivated: boolean) => { console.log('checkOsAccountActivated successfully, isActivated: ' + isActivated); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('checkOsAccountActivated failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -333,11 +338,12 @@ checkOsAccountConstraintEnabled(localId: number, constraint: string, callback: A **示例:** 判断ID为100的系统帐号是否有禁止使用Wi-Fi的约束 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; - let constraint = 'constraint.wifi'; + let localId: number = 100; + let constraint: string = 'constraint.wifi'; try { - accountManager.checkOsAccountConstraintEnabled(localId, constraint, (err, isEnabled)=>{ + accountManager.checkOsAccountConstraintEnabled(localId, constraint, (err: BusinessError, isEnabled: boolean)=>{ if (err) { console.log('checkOsAccountConstraintEnabled failed, error: ' + JSON.stringify(err)); } else { @@ -383,13 +389,14 @@ checkOsAccountConstraintEnabled(localId: number, constraint: string): Promise< **示例:** 判断ID为100的系统帐号是否有禁止使用Wi-Fi的约束 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; - let constraint = 'constraint.wifi'; + let localId: number = 100; + let constraint: string = 'constraint.wifi'; try { - accountManager.checkOsAccountConstraintEnabled(localId, constraint).then((isEnabled) => { + accountManager.checkOsAccountConstraintEnabled(localId, constraint).then((isEnabled: boolean) => { console.log('checkOsAccountConstraintEnabled successfully, isEnabled: ' + isEnabled); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('checkOsAccountConstraintEnabled failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -420,9 +427,10 @@ checkOsAccountTestable(callback: AsyncCallback<boolean>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.checkOsAccountTestable((err, isTestable) => { + accountManager.checkOsAccountTestable((err: BusinessError, isTestable: boolean) => { if (err) { console.log('checkOsAccountTestable failed, error: ' + JSON.stringify(err)); } else { @@ -457,11 +465,12 @@ checkOsAccountTestable(): Promise<boolean> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.checkOsAccountTestable().then((isTestable) => { + accountManager.checkOsAccountTestable().then((isTestable: boolean) => { console.log('checkOsAccountTestable successfully, isTestable: ' + isTestable); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('checkOsAccountTestable failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -492,9 +501,10 @@ checkOsAccountVerified(callback: AsyncCallback<boolean>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.checkOsAccountVerified((err, isVerified) => { + accountManager.checkOsAccountVerified((err: BusinessError, isVerified: boolean) => { if (err) { console.log('checkOsAccountVerified failed, error: ' + JSON.stringify(err)); } else { @@ -529,11 +539,12 @@ checkOsAccountVerified(): Promise<boolean> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.checkOsAccountVerified().then((isVerified) => { + accountManager.checkOsAccountVerified().then((isVerified: boolean) => { console.log('checkOsAccountVerified successfully, isVerified: ' + isVerified); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('checkOsAccountVerified failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -569,10 +580,11 @@ checkOsAccountVerified(localId: number, callback: AsyncCallback<boolean>): **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; + let localId: number = 100; try { - accountManager.checkOsAccountVerified(localId, (err, isVerified) => { + accountManager.checkOsAccountVerified(localId, (err: BusinessError, isVerified: boolean) => { if (err) { console.log('checkOsAccountVerified failed, error: ' + JSON.stringify(err)); } else { @@ -617,12 +629,13 @@ checkOsAccountVerified(localId: number): Promise<boolean> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; + let localId: number = 100; try { - accountManager.checkOsAccountVerified(localId).then((isVerified) => { + accountManager.checkOsAccountVerified(localId).then((isVerified: boolean) => { console.log('checkOsAccountVerified successfully, isVerified: ' + isVerified); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('checkOsAccountVerified failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -653,11 +666,12 @@ checkOsAccountVerified(): Promise<boolean> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.checkOsAccountVerified().then((isVerified) => { + accountManager.checkOsAccountVerified().then((isVerified: boolean) => { console.log('checkOsAccountVerified successfully, isVerified: ' + isVerified); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('checkOsAccountVerified failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -696,16 +710,18 @@ removeOsAccount(localId: number, callback: AsyncCallback<void>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let accountName = 'testAccountName'; + let accountName: string = 'testAccountName'; try { - accountManager.createOsAccount(accountName, account_osAccount.OsAccountType.NORMAL, (err, osAccountInfo) => { - accountManager.removeOsAccount(osAccountInfo.localId, (err)=>{ - if (err) { - console.log('removeOsAccount failed, error: ' + JSON.stringify(err)); - } else { - console.log('removeOsAccount successfully'); - } + accountManager.createOsAccount(accountName, account_osAccount.OsAccountType.NORMAL, + (err: BusinessError, osAccountInfo: account_osAccount.OsAccountInfo) => { + accountManager.removeOsAccount(osAccountInfo.localId, (err: BusinessError)=>{ + if (err) { + console.log('removeOsAccount failed, error: ' + JSON.stringify(err)); + } else { + console.log('removeOsAccount successfully'); + } }); }); } catch (err) { @@ -749,15 +765,17 @@ removeOsAccount(localId: number): Promise<void> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let accountName = 'testAccountName'; + let accountName: string = 'testAccountName'; try { - accountManager.createOsAccount(accountName, account_osAccount.OsAccountType.NORMAL, (err, osAccountInfo)=>{ - accountManager.removeOsAccount(osAccountInfo.localId).then(() => { - console.log('removeOsAccount successfully'); - }).catch((err) => { - console.log('removeOsAccount failed, error: ' + JSON.stringify(err)); - }); + accountManager.createOsAccount(accountName, account_osAccount.OsAccountType.NORMAL, + (err: BusinessError, osAccountInfo: account_osAccount.OsAccountInfo)=>{ + accountManager.removeOsAccount(osAccountInfo.localId).then(() => { + console.log('removeOsAccount successfully'); + }).catch((err: BusinessError) => { + console.log('removeOsAccount failed, error: ' + JSON.stringify(err)); + }); }); } catch (err) { console.log('removeOsAccount exception: ' + JSON.stringify(err)); @@ -797,11 +815,12 @@ setOsAccountConstraints(localId: number, constraints: Array<string>, enabl **示例:** 给ID为100的系统帐号设置禁止使用Wi-Fi的约束 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; - let constraint = 'constraint.wifi'; + let localId: number = 100; + let constraint: string = 'constraint.wifi'; try { - accountManager.setOsAccountConstraints(localId, [constraint], true, (err) => { + accountManager.setOsAccountConstraints(localId, [constraint], true, (err: BusinessError) => { if (err) { console.log('setOsAccountConstraints failed, error: ' + JSON.stringify(err)); } else { @@ -851,12 +870,13 @@ setOsAccountConstraints(localId: number, constraints: Array<string>, enabl **示例:** 删除ID为100的系统帐号的禁止使用Wi-Fi的约束 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; + let localId: number = 100; try { accountManager.setOsAccountConstraints(localId, ['constraint.location.set'], false).then(() => { console.log('setOsAccountConstraints succsuccessfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('setOsAccountConstraints failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -896,11 +916,12 @@ setOsAccountName(localId: number, localName: string, callback: AsyncCallback< **示例:** 将ID为100的系统帐号的帐号名设置成demoName ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; - let name = 'demoName'; + let localId: number = 100; + let name: string = 'demoName'; try { - accountManager.setOsAccountName(localId, name, (err) => { + accountManager.setOsAccountName(localId, name, (err: BusinessError) => { if (err) { console.log('setOsAccountName failed, error: ' + JSON.stringify(err)); } else { @@ -949,13 +970,14 @@ setOsAccountName(localId: number, localName: string): Promise<void> **示例:** 将ID为100的系统帐号的帐号名设置成demoName ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; - let name = 'testName'; + let localId: number = 100; + let name: string = 'testName'; try { accountManager.setOsAccountName(localId, name).then(() => { console.log('setOsAccountName successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('setOsAccountName failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -988,9 +1010,10 @@ getOsAccountCount(callback: AsyncCallback<number>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.getOsAccountCount((err, count) => { + accountManager.getOsAccountCount((err: BusinessError, count: number) => { if (err) { console.log('getOsAccountCount failed, error: ' + JSON.stringify(err)); } else { @@ -1027,11 +1050,12 @@ getOsAccountCount(): Promise<number> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.getOsAccountCount().then((count) => { + accountManager.getOsAccountCount().then((count: number) => { console.log('getOsAccountCount successfully, count: ' + count); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getOsAccountCount failed, error: ' + JSON.stringify(err)); }); } catch(err) { @@ -1062,9 +1086,10 @@ getOsAccountLocalId(callback: AsyncCallback<number>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.getOsAccountLocalId((err, localId) => { + accountManager.getOsAccountLocalId((err: BusinessError, localId: number) => { if (err) { console.log('getOsAccountLocalId failed, error: ' + JSON.stringify(err)); } else { @@ -1099,11 +1124,12 @@ getOsAccountLocalId(): Promise<number> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.getOsAccountLocalId().then((localId) => { + accountManager.getOsAccountLocalId().then((localId: number) => { console.log('getOsAccountLocalId successfully, localId: ' + localId); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getOsAccountLocalId failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -1136,10 +1162,11 @@ getOsAccountLocalIdForUid(uid: number, callback: AsyncCallback<number>): v **示例:** 查询值为12345678的uid所属的系统帐号的帐号ID ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let uid = 12345678; + let uid: number = 12345678; try { - accountManager.getOsAccountLocalIdForUid(uid, (err, localId) => { + accountManager.getOsAccountLocalIdForUid(uid, (err: BusinessError, localId: number) => { if (err) { console.log('getOsAccountLocalIdForUid failed, error: ' + JSON.stringify(err)); } @@ -1180,12 +1207,13 @@ getOsAccountLocalIdForUid(uid: number): Promise<number> **示例:** 查询值为12345678的uid所属的系统帐号ID ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let uid = 12345678; + let uid: number = 12345678; try { - accountManager.getOsAccountLocalIdForUid(uid).then((localId) => { + accountManager.getOsAccountLocalIdForUid(uid).then((localId: number) => { console.log('getOsAccountLocalIdForUid successfully, localId: ' + localId); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getOsAccountLocalIdForUid failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -1220,10 +1248,11 @@ getOsAccountLocalIdForDomain(domainInfo: DomainAccountInfo, callback: AsyncCallb **示例:** ```js + import { BusinessError } from '@ohos.base'; let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.getOsAccountLocalIdForDomain(domainInfo, (err, localId) => { + accountManager.getOsAccountLocalIdForDomain(domainInfo, (err: BusinessError, localId: number) => { if (err) { console.log('getOsAccountLocalIdForDomain failed, error: ' + JSON.stringify(err)); } else { @@ -1267,12 +1296,13 @@ getOsAccountLocalIdForDomain(domainInfo: DomainAccountInfo): Promise<number&g **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; try { - accountManager.getOsAccountLocalIdForDomain(domainInfo).then((localId) => { + accountManager.getOsAccountLocalIdForDomain(domainInfo).then((localId: number) => { console.log('getOsAccountLocalIdForDomain successfully, localId: ' + localId); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getOsAccountLocalIdForDomain failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -1305,9 +1335,10 @@ queryMaxOsAccountNumber(callback: AsyncCallback<number>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.queryMaxOsAccountNumber((err, maxCnt) => { + accountManager.queryMaxOsAccountNumber((err: BusinessError, maxCnt: number) => { if (err) { console.log('queryMaxOsAccountNumber failed, error:' + JSON.stringify(err)); } else { @@ -1344,11 +1375,12 @@ queryMaxOsAccountNumber(): Promise<number> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.queryMaxOsAccountNumber().then((maxCnt) => { + accountManager.queryMaxOsAccountNumber().then((maxCnt: number) => { console.log('queryMaxOsAccountNumber successfully, maxCnt: ' + maxCnt); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('queryMaxOsAccountNumber failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -1384,10 +1416,11 @@ getOsAccountConstraints(localId: number, callback: AsyncCallback<Array<str **示例:** 获取ID为100的系统帐号的全部约束 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; + let localId: number = 100; try { - accountManager.getOsAccountConstraints(localId, (err, constraints) => { + accountManager.getOsAccountConstraints(localId, (err: BusinessError, constraints: string[]) => { if (err) { console.log('getOsAccountConstraints failed, err: ' + JSON.stringify(err)); } else { @@ -1432,12 +1465,13 @@ getOsAccountConstraints(localId: number): Promise<Array<string>> **示例:** 获取ID为100的系统帐号的全部约束 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; + let localId: number = 100; try { - accountManager.getOsAccountConstraints(localId).then((constraints) => { + accountManager.getOsAccountConstraints(localId).then((constraints: string[]) => { console.log('getOsAccountConstraints, constraints: ' + constraints); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getOsAccountConstraints err: ' + JSON.stringify(err)); }); } catch (e) { @@ -1472,9 +1506,10 @@ queryAllCreatedOsAccounts(callback: AsyncCallback<Array<OsAccountInfo>& **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.queryAllCreatedOsAccounts((err, accountArr)=>{ + accountManager.queryAllCreatedOsAccounts((err: BusinessError, accountArr: account_osAccount.OsAccountInfo[])=>{ console.log('queryAllCreatedOsAccounts err:' + JSON.stringify(err)); console.log('queryAllCreatedOsAccounts accountArr:' + JSON.stringify(accountArr)); }); @@ -1510,11 +1545,12 @@ queryAllCreatedOsAccounts(): Promise<Array<OsAccountInfo>> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.queryAllCreatedOsAccounts().then((accountArr) => { + accountManager.queryAllCreatedOsAccounts().then((accountArr: account_osAccount.OsAccountInfo[]) => { console.log('queryAllCreatedOsAccounts, accountArr: ' + JSON.stringify(accountArr)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('queryAllCreatedOsAccounts err: ' + JSON.stringify(err)); }); } catch (e) { @@ -1545,9 +1581,10 @@ getActivatedOsAccountLocalIds(callback: AsyncCallback<Array<number>> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.getActivatedOsAccountLocalIds((err, idArray)=>{ + accountManager.getActivatedOsAccountLocalIds((err: BusinessError, idArray: number[])=>{ console.log('getActivatedOsAccountLocalIds err:' + JSON.stringify(err)); console.log('getActivatedOsAccountLocalIds idArray length:' + idArray.length); for(let i=0;i { + accountManager.getActivatedOsAccountLocalIds().then((idArray: number[]) => { console.log('getActivatedOsAccountLocalIds, idArray: ' + idArray); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getActivatedOsAccountLocalIds err: ' + JSON.stringify(err)); }); } catch (e) { @@ -1627,9 +1665,11 @@ createOsAccount(localName: string, type: OsAccountType, callback: AsyncCallback& **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.createOsAccount('testName', account_osAccount.OsAccountType.NORMAL, (err, osAccountInfo)=>{ + accountManager.createOsAccount('testName', account_osAccount.OsAccountType.NORMAL, + (err: BusinessError, osAccountInfo: account_osAccount.OsAccountInfo)=>{ console.log('createOsAccount err:' + JSON.stringify(err)); console.log('createOsAccount osAccountInfo:' + JSON.stringify(osAccountInfo)); }); @@ -1676,11 +1716,13 @@ createOsAccount(localName: string, type: OsAccountType): Promise<OsAccountInf **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.createOsAccount('testAccountName', account_osAccount.OsAccountType.NORMAL).then((accountInfo) => { + accountManager.createOsAccount('testAccountName', account_osAccount.OsAccountType.NORMAL).then( + (accountInfo: account_osAccount.OsAccountInfo) => { console.log('createOsAccount, accountInfo: ' + JSON.stringify(accountInfo)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('createOsAccount err: ' + JSON.stringify(err)); }); } catch (e) { @@ -1721,10 +1763,12 @@ createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo, cal **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; try { - accountManager.createOsAccountForDomain(account_osAccount.OsAccountType.NORMAL, domainInfo, (err, osAccountInfo)=>{ + accountManager.createOsAccountForDomain(account_osAccount.OsAccountType.NORMAL, domainInfo, + (err: BusinessError, osAccountInfo: account_osAccount.OsAccountInfo)=>{ console.log('createOsAccountForDomain err:' + JSON.stringify(err)); console.log('createOsAccountForDomain osAccountInfo:' + JSON.stringify(osAccountInfo)); }); @@ -1771,12 +1815,14 @@ createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo): Pr **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; try { - accountManager.createOsAccountForDomain(account_osAccount.OsAccountType.NORMAL, domainInfo).then((accountInfo) => { + accountManager.createOsAccountForDomain(account_osAccount.OsAccountType.NORMAL, domainInfo).then( + (accountInfo: account_osAccount.OsAccountInfo) => { console.log('createOsAccountForDomain, account info: ' + JSON.stringify(accountInfo)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('createOsAccountForDomain err: ' + JSON.stringify(err)); }); } catch (e) { @@ -1809,9 +1855,10 @@ getCurrentOsAccount(callback: AsyncCallback<OsAccountInfo>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.getCurrentOsAccount((err, curAccountInfo)=>{ + accountManager.getCurrentOsAccount((err: BusinessError, curAccountInfo: account_osAccount.OsAccountInfo)=>{ console.log('getCurrentOsAccount err:' + JSON.stringify(err)); console.log('getCurrentOsAccount curAccountInfo:' + JSON.stringify(curAccountInfo)); }); @@ -1845,11 +1892,12 @@ getCurrentOsAccount(): Promise<OsAccountInfo> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.getCurrentOsAccount().then((accountInfo) => { + accountManager.getCurrentOsAccount().then((accountInfo: account_osAccount.OsAccountInfo) => { console.log('getCurrentOsAccount, accountInfo: ' + JSON.stringify(accountInfo)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getCurrentOsAccount err: ' + JSON.stringify(err)); }); } catch (e) { @@ -1887,10 +1935,11 @@ queryOsAccountById(localId: number, callback: AsyncCallback<OsAccountInfo> **示例:** 查询ID为100的系统帐号信息 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; + let localId: number = 100; try { - accountManager.queryOsAccountById(localId, (err, accountInfo)=>{ + accountManager.queryOsAccountById(localId, (err: BusinessError, accountInfo: account_osAccount.OsAccountInfo)=>{ console.log('queryOsAccountById err:' + JSON.stringify(err)); console.log('queryOsAccountById accountInfo:' + JSON.stringify(accountInfo)); }); @@ -1934,12 +1983,13 @@ queryOsAccountById(localId: number): Promise<OsAccountInfo> **示例:** 查询ID为100的系统帐号信息 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; + let localId: number = 100; try { - accountManager.queryOsAccountById(localId).then((accountInfo) => { + accountManager.queryOsAccountById(localId).then((accountInfo: account_osAccount.OsAccountInfo) => { console.log('queryOsAccountById, accountInfo: ' + JSON.stringify(accountInfo)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('queryOsAccountById err: ' + JSON.stringify(err)); }); } catch (e) { @@ -1970,9 +2020,10 @@ getOsAccountType(callback: AsyncCallback<OsAccountType>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.getOsAccountType((err, accountType) => { + accountManager.getOsAccountType((err: BusinessError, accountType: account_osAccount.OsAccountType) => { console.log('getOsAccountType err: ' + JSON.stringify(err)); console.log('getOsAccountType accountType: ' + accountType); }); @@ -2004,11 +2055,12 @@ getOsAccountType(): Promise<OsAccountType> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.getOsAccountType().then((accountType) => { + accountManager.getOsAccountType().then((accountType: account_osAccount.OsAccountType) => { console.log('getOsAccountType, accountType: ' + accountType); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getOsAccountType err: ' + JSON.stringify(err)); }); } catch (e) { @@ -2041,9 +2093,10 @@ queryDistributedVirtualDeviceId(callback: AsyncCallback<string>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.queryDistributedVirtualDeviceId((err, virtualID) => { + accountManager.queryDistributedVirtualDeviceId((err: BusinessError, virtualID: string) => { console.log('queryDistributedVirtualDeviceId err: ' + JSON.stringify(err)); console.log('queryDistributedVirtualDeviceId virtualID: ' + virtualID); }); @@ -2077,11 +2130,12 @@ queryDistributedVirtualDeviceId(): Promise<string> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.queryDistributedVirtualDeviceId().then((virtualID) => { + accountManager.queryDistributedVirtualDeviceId().then((virtualID: string) => { console.log('queryDistributedVirtualDeviceId, virtualID: ' + virtualID); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('queryDistributedVirtualDeviceId err: ' + JSON.stringify(err)); }); } catch (e) { @@ -2119,10 +2173,11 @@ getOsAccountProfilePhoto(localId: number, callback: AsyncCallback<string>) **示例:** 获取ID为100的系统帐号的头像 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; + let localId: number = 100; try { - accountManager.getOsAccountProfilePhoto(localId, (err, photo)=>{ + accountManager.getOsAccountProfilePhoto(localId, (err: BusinessError, photo: string)=>{ console.log('getOsAccountProfilePhoto err:' + JSON.stringify(err)); console.log('get photo:' + photo + ' by localId: ' + localId); }); @@ -2166,12 +2221,13 @@ getOsAccountProfilePhoto(localId: number): Promise<string> **示例:** 获取ID为100的系统帐号的头像 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; + let localId: number = 100; try { - accountManager.getOsAccountProfilePhoto(localId).then((photo) => { + accountManager.getOsAccountProfilePhoto(localId).then((photo: string) => { console.log('getOsAccountProfilePhoto: ' + photo); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getOsAccountProfilePhoto err: ' + JSON.stringify(err)); }); } catch (e) { @@ -2211,14 +2267,15 @@ setOsAccountProfilePhoto(localId: number, photo: string, callback: AsyncCallback **示例:** 给ID为100的系统帐号设置头像 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; - let photo = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAPCAYAAAA/I0V3AAAAAXNSR0IArs4c6QAAAARnQU1BAA'+ + let localId: number = 100; + let photo: string = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAPCAYAAAA/I0V3AAAAAXNSR0IArs4c6QAAAARnQU1BAA'+ 'Cxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACwSURBVDhPvZLBDYMwDEV/ugsXRjAT0EHCOuFIBwkbdIRewi6unbiAyoGgSn1SFH85+Y'+ 'q/4ljARW62X+LHS8uIzjm4dXUYF+utzBikB52Jo5e5iEPKqpACk7R9NM2RvWm5tIkD2czLCUFNKLD6IjdMHFHDzws285MgGrT0xCtp3WOKHo'+ '+7q0mP0DZW9pNmoEFUzrQjp5cCnaen2kSJXLFD8ghbXyZCMQf/8e8Ns1XVAG/XAgqKzVnJFAAAAABJRU5ErkJggg==' try { - accountManager.setOsAccountProfilePhoto(localId, photo, (err)=>{ + accountManager.setOsAccountProfilePhoto(localId, photo, (err: BusinessError)=>{ console.log('setOsAccountProfilePhoto err:' + JSON.stringify(err)); }); } catch (e) { @@ -2263,16 +2320,17 @@ setOsAccountProfilePhoto(localId: number, photo: string): Promise<void> **示例:** 给ID为100的系统帐号设置头像 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; - let photo = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAPCAYAAAA/I0V3AAAAAXNSR0IArs4c6QAAAARnQU1BAA'+ + let localId: number = 100; + let photo: string = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAPCAYAAAA/I0V3AAAAAXNSR0IArs4c6QAAAARnQU1BAA'+ 'Cxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACwSURBVDhPvZLBDYMwDEV/ugsXRjAT0EHCOuFIBwkbdIRewi6unbiAyoGgSn1SFH85+Y'+ 'q/4ljARW62X+LHS8uIzjm4dXUYF+utzBikB52Jo5e5iEPKqpACk7R9NM2RvWm5tIkD2czLCUFNKLD6IjdMHFHDzws285MgGrT0xCtp3WOKHo'+ '+7q0mP0DZW9pNmoEFUzrQjp5cCnaen2kSJXLFD8ghbXyZCMQf/8e8Ns1XVAG/XAgqKzVnJFAAAAABJRU5ErkJggg==' try { accountManager.setOsAccountProfilePhoto(localId, photo).then(() => { console.log('setOsAccountProfilePhoto success'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('setOsAccountProfilePhoto err: ' + JSON.stringify(err)); }); } catch (e) { @@ -2306,10 +2364,11 @@ getOsAccountLocalIdForSerialNumber(serialNumber: number, callback: AsyncCallback **示例:** 查询与SN码12345关联的系统帐号的ID ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let serialNumber = 12345; + let serialNumber: number = 12345; try { - accountManager.getOsAccountLocalIdForSerialNumber(serialNumber, (err, localId)=>{ + accountManager.getOsAccountLocalIdForSerialNumber(serialNumber, (err: BusinessError, localId: number)=>{ console.log('ger localId err:' + JSON.stringify(err)); console.log('get localId:' + localId + ' by serialNumber: ' + serialNumber); }); @@ -2349,12 +2408,13 @@ getOsAccountLocalIdForSerialNumber(serialNumber: number): Promise<number> **示例:** 查询与SN码12345关联的系统帐号的ID ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let serialNumber = 12345; + let serialNumber: number = 12345; try { - accountManager.getOsAccountLocalIdForSerialNumber(serialNumber).then((localId) => { + accountManager.getOsAccountLocalIdForSerialNumber(serialNumber).then((localId: number) => { console.log('getOsAccountLocalIdForSerialNumber localId: ' + localId); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getOsAccountLocalIdForSerialNumber err: ' + JSON.stringify(err)); }); } catch (e) { @@ -2388,10 +2448,11 @@ getSerialNumberForOsAccountLocalId(localId: number, callback: AsyncCallback<n **示例:** 获取ID为100的系统帐号关联的SN码 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; + let localId: number = 100; try { - accountManager.getSerialNumberForOsAccountLocalId(localId, (err, serialNumber)=>{ + accountManager.getSerialNumberForOsAccountLocalId(localId, (err: BusinessError, serialNumber: number)=>{ console.log('ger serialNumber err:' + JSON.stringify(err)); console.log('get serialNumber:' + serialNumber + ' by localId: ' + localId); }); @@ -2431,12 +2492,13 @@ getSerialNumberForOsAccountLocalId(localId: number): Promise<number> **示例:** 获取ID为100的系统帐号关联的SN码 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; + let localId: number = 100; try { - accountManager.getSerialNumberForOsAccountLocalId(localId).then((serialNumber) => { + accountManager.getSerialNumberForOsAccountLocalId(localId).then((serialNumber: number) => { console.log('getSerialNumberForOsAccountLocalId serialNumber: ' + serialNumber); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getSerialNumberForOsAccountLocalId err: ' + JSON.stringify(err)); }); } catch (e) { @@ -2475,7 +2537,7 @@ on(type: 'activate' | 'activating', name: string, callback: Callback<number&g ```js let accountManager = account_osAccount.getAccountManager(); - function onCallback(receiveLocalId){ + function onCallback(receiveLocalId: number){ console.log('receive localId:' + receiveLocalId); } try { @@ -2553,10 +2615,11 @@ getBundleIdForUid(uid: number, callback: AsyncCallback<number>): void; **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let testUid = 1000000; + let testUid: number = 1000000; try { - accountManager.getBundleIdForUid(testUid, (err, bundleId) => { + accountManager.getBundleIdForUid(testUid, (err: BusinessError, bundleId: number) => { console.info('getBundleIdForUid errInfo:' + JSON.stringify(err)); console.info('getBundleIdForUid bundleId:' + JSON.stringify(bundleId)); }); @@ -2596,12 +2659,13 @@ getBundleIdForUid(uid: number): Promise<number>; **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let testUid = 1000000; + let testUid: number = 1000000; try { - accountManager.getBundleIdForUid(testUid).then((result) => { + accountManager.getBundleIdForUid(testUid).then((result: number) => { console.info('getBundleIdForUid bundleId:' + JSON.stringify(result)); - }).catch((err)=>{ + }).catch((err: BusinessError) => { console.info('getBundleIdForUid errInfo:' + JSON.stringify(err)); }); } catch (e) { @@ -2636,9 +2700,10 @@ isMainOsAccount(callback: AsyncCallback<boolean>): void; **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.isMainOsAccount((err,result)=>{ + accountManager.isMainOsAccount((err: BusinessError,result: boolean)=>{ console.info('isMainOsAccount errInfo:' + JSON.stringify(err)); console.info('isMainOsAccount result:' + JSON.stringify(result)); }); @@ -2673,11 +2738,12 @@ isMainOsAccount(): Promise<boolean>; **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.isMainOsAccount().then((result) => { + accountManager.isMainOsAccount().then((result: boolean) => { console.info('isMainOsAccount result:' + JSON.stringify(result)); - }).catch((err)=>{ + }).catch((err: BusinessError) => { console.info('isMainOsAccount errInfo:' + JSON.stringify(err)); }); } catch (e) { @@ -2715,9 +2781,11 @@ getOsAccountConstraintSourceTypes(localId: number, constraint: string, callback: **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.getOsAccountConstraintSourceTypes(100, 'constraint.wifi',(err,sourceTypeInfos)=>{ + accountManager.getOsAccountConstraintSourceTypes(100, 'constraint.wifi', + (err: BusinessError,sourceTypeInfos: account_osAccount.ConstraintSourceTypeInfo[])=>{ console.info('getOsAccountConstraintSourceTypes errInfo:' + JSON.stringify(err)); console.info('getOsAccountConstraintSourceTypes sourceTypeInfos:' + JSON.stringify(sourceTypeInfos)); }); @@ -2762,11 +2830,13 @@ getOsAccountConstraintSourceTypes(localId: number, constraint: string): Promise& **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); try { - accountManager.getOsAccountConstraintSourceTypes(100, 'constraint.wifi').then((result) => { + accountManager.getOsAccountConstraintSourceTypes(100, 'constraint.wifi').then( + (result: account_osAccount.ConstraintSourceTypeInfo[]) => { console.info('getOsAccountConstraintSourceTypes sourceTypeInfos:' + JSON.stringify(result)); - }).catch((err)=>{ + }).catch((err: BusinessError) => { console.info('getOsAccountConstraintSourceTypes errInfo:' + JSON.stringify(err)); }); } catch (e) { @@ -2795,8 +2865,9 @@ isMultiOsAccountEnable(callback: AsyncCallback<boolean>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - accountManager.isMultiOsAccountEnable((err, isEnabled) => { + accountManager.isMultiOsAccountEnable((err: BusinessError, isEnabled: boolean) => { if (err) { console.log('isMultiOsAccountEnable failed, error: ' + JSON.stringify(err)); } else { @@ -2826,10 +2897,11 @@ isMultiOsAccountEnable(): Promise<boolean> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - accountManager.isMultiOsAccountEnable().then((isEnabled) => { + accountManager.isMultiOsAccountEnable().then((isEnabled: boolean) => { console.log('isMultiOsAccountEnable successfully, isEnabled: ' + isEnabled); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('isMultiOsAccountEnable failed, error: ' + JSON.stringify(err)); }); ``` @@ -2859,9 +2931,10 @@ isOsAccountActived(localId: number, callback: AsyncCallback<boolean>): voi **示例:** 判断ID为100的系统帐号是否处于激活状态 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; - accountManager.isOsAccountActived(localId, (err, isActived) => { + let localId: number = 100; + accountManager.isOsAccountActived(localId, (err: BusinessError, isActived: boolean) => { if (err) { console.log('isOsAccountActived failed, err:' + JSON.stringify(err)); } else { @@ -2899,11 +2972,12 @@ isOsAccountActived(localId: number): Promise<boolean> **示例:** 判断ID为100的系统帐号是否处于激活状态 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; - accountManager.isOsAccountActived(localId).then((isActived) => { + let localId: number = 100; + accountManager.isOsAccountActived(localId).then((isActived: boolean) => { console.log('isOsAccountActived successfully, isActived: ' + isActived); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('isOsAccountActived failed, error: ' + JSON.stringify(err)); }); ``` @@ -2933,10 +3007,11 @@ isOsAccountConstraintEnable(localId: number, constraint: string, callback: Async **示例:** 判断ID为100的系统帐号是否有禁止使用Wi-Fi的约束 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; - let constraint = 'constraint.wifi'; - accountManager.isOsAccountConstraintEnable(localId, constraint, (err, isEnabled) => { + let localId: number = 100; + let constraint: string = 'constraint.wifi'; + accountManager.isOsAccountConstraintEnable(localId, constraint, (err: BusinessError, isEnabled: boolean) => { if (err) { console.log('isOsAccountConstraintEnable failed, error: ' + JSON.stringify(err)); } else { @@ -2975,12 +3050,13 @@ isOsAccountConstraintEnable(localId: number, constraint: string): Promise<boo **示例:** 判断ID为100的系统帐号是否有禁止使用Wi-Fi的约束 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; - let constraint = 'constraint.wifi'; - accountManager.isOsAccountConstraintEnable(localId, constraint).then((isEnabled) => { + let localId: number = 100; + let constraint: string = 'constraint.wifi'; + accountManager.isOsAccountConstraintEnable(localId, constraint).then((isEnabled: boolean) => { console.log('isOsAccountConstraintEnable successfully, isEnabled: ' + isEnabled); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('isOsAccountConstraintEnable err: ' + JSON.stringify(err)); }); ``` @@ -3006,8 +3082,9 @@ isTestOsAccount(callback: AsyncCallback<boolean>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - accountManager.isTestOsAccount((err, isTestable) => { + accountManager.isTestOsAccount((err: BusinessError, isTestable: boolean) => { if (err) { console.log('isTestOsAccount failed, error: ' + JSON.stringify(err)); } else { @@ -3037,10 +3114,11 @@ isTestOsAccount(): Promise<boolean> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - accountManager.isTestOsAccount().then((isTestable) => { + accountManager.isTestOsAccount().then((isTestable: boolean) => { console.log('isTestOsAccount successfully, isTestable: ' + isTestable); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('isTestOsAccount failed, error: ' + JSON.stringify(err)); }); ``` @@ -3068,8 +3146,9 @@ isOsAccountVerified(callback: AsyncCallback<boolean>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - accountManager.isOsAccountVerified((err, isVerified) => { + accountManager.isOsAccountVerified((err: BusinessError, isVerified: boolean) => { if (err) { console.log('isOsAccountVerified failed, error: ' + JSON.stringify(err)); } else { @@ -3102,9 +3181,10 @@ isOsAccountVerified(localId: number, callback: AsyncCallback<boolean>): vo **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; - accountManager.isOsAccountVerified(localId, (err, isVerified) => { + let localId: number = 100; + accountManager.isOsAccountVerified(localId, (err: BusinessError, isVerified: boolean) => { if (err) { console.log('isOsAccountVerified failed, error: ' + JSON.stringify(err)); } else { @@ -3142,10 +3222,11 @@ isOsAccountVerified(localId?: number): Promise<boolean> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - accountManager.isOsAccountVerified(localId).then((isVerified) => { + accountManager.isOsAccountVerified(localId).then((isVerified: boolean) => { console.log('isOsAccountVerified successfully, isVerified: ' + isVerified); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('isOsAccountVerified failed, error: ' + JSON.stringify(err)); }); ``` @@ -3173,8 +3254,9 @@ getCreatedOsAccountsCount(callback: AsyncCallback<number>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - accountManager.getCreatedOsAccountsCount((err, count)=>{ + accountManager.getCreatedOsAccountsCount((err: BusinessError, count: number)=>{ if (err) { console.log('getCreatedOsAccountsCount failed, error: ' + JSON.stringify(err)); } else { @@ -3206,10 +3288,11 @@ getCreatedOsAccountsCount(): Promise<number> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - accountManager.getCreatedOsAccountsCount().then((count) => { + accountManager.getCreatedOsAccountsCount().then((count: number) => { console.log('getCreatedOsAccountsCount successfully, count: ' + count); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getCreatedOsAccountsCount failed, error: ' + JSON.stringify(err)); }); ``` @@ -3235,8 +3318,9 @@ getOsAccountLocalIdFromProcess(callback: AsyncCallback<number>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - accountManager.getOsAccountLocalIdFromProcess((err, localId) => { + accountManager.getOsAccountLocalIdFromProcess((err: BusinessError, localId: number) => { if (err) { console.log('getOsAccountLocalIdFromProcess failed, error: ' + JSON.stringify(err)); } else { @@ -3266,10 +3350,11 @@ getOsAccountLocalIdFromProcess(): Promise<number> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - accountManager.getOsAccountLocalIdFromProcess().then((localId) => { + accountManager.getOsAccountLocalIdFromProcess().then((localId: number) => { console.log('getOsAccountLocalIdFromProcess successfully, localId: ' + localId); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getOsAccountLocalIdFromProcess failed, error: ' + JSON.stringify(err)); }); ``` @@ -3296,9 +3381,10 @@ getOsAccountLocalIdFromUid(uid: number, callback: AsyncCallback<number>): **示例:** 查询值为12345678的uid所属的系统帐号ID ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let uid = 12345678; - accountManager.getOsAccountLocalIdFromUid(uid, (err, localId) => { + let uid: number = 12345678; + accountManager.getOsAccountLocalIdFromUid(uid, (err: BusinessError, localId: number) => { if (err) { console.log('getOsAccountLocalIdFromUid failed, error: ' + JSON.stringify(err)); } else { @@ -3334,11 +3420,12 @@ getOsAccountLocalIdFromUid(uid: number): Promise<number> **示例:** 查询值为12345678的uid所属的系统帐号ID ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let uid = 12345678; - accountManager.getOsAccountLocalIdFromUid(uid).then((localId) => { + let uid: number = 12345678; + accountManager.getOsAccountLocalIdFromUid(uid).then((localId: number) => { console.log('getOsAccountLocalIdFromUid successfully, localId: ' + localId); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getOsAccountLocalIdFromUid failed, error: ' + JSON.stringify(err)); }); ``` @@ -3367,9 +3454,10 @@ getOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo, callback: AsyncCall **示例:** ```js + import { BusinessError } from '@ohos.base'; let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; let accountManager = account_osAccount.getAccountManager(); - accountManager.getOsAccountLocalIdFromDomain(domainInfo, (err, localId) => { + accountManager.getOsAccountLocalIdFromDomain(domainInfo, (err: BusinessError, localId: number) => { if (err) { console.log('getOsAccountLocalIdFromDomain failed, error: ' + JSON.stringify(err)); } else { @@ -3407,11 +3495,12 @@ getOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo): Promise<number& **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; - accountManager.getOsAccountLocalIdFromDomain(domainInfo).then((localId) => { + accountManager.getOsAccountLocalIdFromDomain(domainInfo).then((localId: number) => { console.log('getOsAccountLocalIdFromDomain successfully, localId: ' + localId); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getOsAccountLocalIdFromDomain failed, error: ' + JSON.stringify(err)); }); ``` @@ -3440,9 +3529,10 @@ getOsAccountAllConstraints(localId: number, callback: AsyncCallback<Array< **示例:** 获取ID为100的系统帐号的全部约束 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; - accountManager.getOsAccountAllConstraints(localId, (err, constraints)=>{ + let localId: number = 100; + accountManager.getOsAccountAllConstraints(localId, (err: BusinessError, constraints: string[])=>{ console.log('getOsAccountAllConstraints err:' + JSON.stringify(err)); console.log('getOsAccountAllConstraints:' + JSON.stringify(constraints)); }); @@ -3477,11 +3567,12 @@ getOsAccountAllConstraints(localId: number): Promise<Array<string>> **示例:** 获取ID为100的系统帐号的全部约束 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; - accountManager.getOsAccountAllConstraints(localId).then((constraints) => { + let localId: number = 100; + accountManager.getOsAccountAllConstraints(localId).then((constraints: string[]) => { console.log('getOsAccountAllConstraints, constraints: ' + constraints); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getOsAccountAllConstraints err: ' + JSON.stringify(err)); }); ``` @@ -3507,8 +3598,9 @@ queryActivatedOsAccountIds(callback: AsyncCallback<Array<number>>): **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - accountManager.queryActivatedOsAccountIds((err, idArray)=>{ + accountManager.queryActivatedOsAccountIds((err: BusinessError, idArray: number[])=>{ console.log('queryActivatedOsAccountIds err:' + JSON.stringify(err)); console.log('queryActivatedOsAccountIds idArray length:' + idArray.length); for(let i=0;i { + accountManager.queryActivatedOsAccountIds().then((idArray: number[]) => { console.log('queryActivatedOsAccountIds, idArray: ' + idArray); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('queryActivatedOsAccountIds err: ' + JSON.stringify(err)); }); ``` @@ -3569,8 +3662,9 @@ queryCurrentOsAccount(callback: AsyncCallback<OsAccountInfo>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - accountManager.queryCurrentOsAccount((err, curAccountInfo)=>{ + accountManager.queryCurrentOsAccount((err: BusinessError, curAccountInfo: account_osAccount.OsAccountInfo)=>{ console.log('queryCurrentOsAccount err:' + JSON.stringify(err)); console.log('queryCurrentOsAccount curAccountInfo:' + JSON.stringify(curAccountInfo)); }); @@ -3599,10 +3693,11 @@ queryCurrentOsAccount(): Promise<OsAccountInfo> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - accountManager.queryCurrentOsAccount().then((accountInfo) => { + accountManager.queryCurrentOsAccount().then((accountInfo: account_osAccount.OsAccountInfo) => { console.log('queryCurrentOsAccount, accountInfo: ' + JSON.stringify(accountInfo)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('queryCurrentOsAccount err: ' + JSON.stringify(err)); }); ``` @@ -3628,8 +3723,9 @@ getOsAccountTypeFromProcess(callback: AsyncCallback<OsAccountType>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - accountManager.getOsAccountTypeFromProcess((err, accountType) => { + accountManager.getOsAccountTypeFromProcess((err: BusinessError, accountType: account_osAccount.OsAccountType) => { console.log('getOsAccountTypeFromProcess err: ' + JSON.stringify(err)); console.log('getOsAccountTypeFromProcess accountType: ' + accountType); }); @@ -3656,10 +3752,11 @@ getOsAccountTypeFromProcess(): Promise<OsAccountType> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - accountManager.getOsAccountTypeFromProcess().then((accountType) => { + accountManager.getOsAccountTypeFromProcess().then((accountType: account_osAccount.OsAccountType) => { console.log('getOsAccountTypeFromProcess, accountType: ' + accountType); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getOsAccountTypeFromProcess err: ' + JSON.stringify(err)); }); ``` @@ -3687,8 +3784,9 @@ getDistributedVirtualDeviceId(callback: AsyncCallback<string>): void **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - accountManager.getDistributedVirtualDeviceId((err, virtualID) => { + accountManager.getDistributedVirtualDeviceId((err: BusinessError, virtualID: string) => { console.log('getDistributedVirtualDeviceId err: ' + JSON.stringify(err)); console.log('getDistributedVirtualDeviceId virtualID: ' + virtualID); }); @@ -3717,10 +3815,11 @@ getDistributedVirtualDeviceId(): Promise<string> **示例:** ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - accountManager.getDistributedVirtualDeviceId().then((virtualID) => { + accountManager.getDistributedVirtualDeviceId().then((virtualID: string) => { console.log('getDistributedVirtualDeviceId, virtualID: ' + virtualID); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getDistributedVirtualDeviceId err: ' + JSON.stringify(err)); }); ``` @@ -3747,9 +3846,10 @@ getOsAccountLocalIdBySerialNumber(serialNumber: number, callback: AsyncCallback& **示例:** 查询与SN码12345关联的系统帐号的ID ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let serialNumber = 12345; - accountManager.getOsAccountLocalIdBySerialNumber(serialNumber, (err, localId)=>{ + let serialNumber: number = 12345; + accountManager.getOsAccountLocalIdBySerialNumber(serialNumber, (err: BusinessError, localId: number)=>{ console.log('ger localId err:' + JSON.stringify(err)); console.log('get localId:' + localId + ' by serialNumber: ' + serialNumber); }); @@ -3782,11 +3882,12 @@ getOsAccountLocalIdBySerialNumber(serialNumber: number): Promise<number> **示例:** 查询与SN码12345关联的系统帐号的ID ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let serialNumber = 12345; - accountManager.getOsAccountLocalIdBySerialNumber(serialNumber).then((localId) => { + let serialNumber: number = 12345; + accountManager.getOsAccountLocalIdBySerialNumber(serialNumber).then((localId: number) => { console.log('getOsAccountLocalIdBySerialNumber localId: ' + localId); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getOsAccountLocalIdBySerialNumber err: ' + JSON.stringify(err)); }); ``` @@ -3813,9 +3914,10 @@ getSerialNumberByOsAccountLocalId(localId: number, callback: AsyncCallback<nu **示例:** 获取ID为100的系统帐号关联的SN码 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; - accountManager.getSerialNumberByOsAccountLocalId(localId, (err, serialNumber)=>{ + let localId: number = 100; + accountManager.getSerialNumberByOsAccountLocalId(localId, (err: BusinessError, serialNumber: number)=>{ console.log('ger serialNumber err:' + JSON.stringify(err)); console.log('get serialNumber:' + serialNumber + ' by localId: ' + localId); }); @@ -3848,11 +3950,12 @@ getSerialNumberByOsAccountLocalId(localId: number): Promise<number> **示例:** 获取ID为100的系统帐号关联的SN码 ```js + import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let localId = 100; - accountManager.getSerialNumberByOsAccountLocalId(localId).then((serialNumber) => { + let localId: number = 100; + accountManager.getSerialNumberByOsAccountLocalId(localId).then((serialNumber: number) => { console.log('getSerialNumberByOsAccountLocalId serialNumber: ' + serialNumber); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getSerialNumberByOsAccountLocalId err: ' + JSON.stringify(err)); }); ``` @@ -3897,7 +4000,7 @@ getVersion(): number; **示例:** ```js let userAuth = new account_osAccount.UserAuth(); - let version = userAuth.getVersion(); + let version: number = userAuth.getVersion(); console.log('getVersion version = ' + version); ``` @@ -3974,9 +4077,10 @@ getProperty(request: GetPropertyRequest, callback: AsyncCallback<ExecutorProp **示例:** ```js + import { BusinessError } from '@ohos.base'; let userAuth = new account_osAccount.UserAuth(); let keys = [ - account_osAccount.GetPropertyType.AUTH_SUB_TYPE, + account_osAccount.GetPropertyType.AUTH_SUB_TYPE, account_osAccount.GetPropertyType.REMAIN_TIMES, account_osAccount.GetPropertyType.FREEZING_TIME ]; @@ -3985,7 +4089,7 @@ getProperty(request: GetPropertyRequest, callback: AsyncCallback<ExecutorProp keys: keys }; try { - userAuth.getProperty(request, (err, result) => { + userAuth.getProperty(request, (err: BusinessError, result: account_osAccount.ExecutorProperty) => { console.log('getProperty err = ' + JSON.stringify(err)); console.log('getProperty result = ' + JSON.stringify(result)); }); @@ -4027,6 +4131,7 @@ getProperty(request: GetPropertyRequest): Promise<ExecutorProperty>; **示例:** ```js + import { BusinessError } from '@ohos.base'; let userAuth = new account_osAccount.UserAuth(); let keys = [ account_osAccount.GetPropertyType.AUTH_SUB_TYPE, @@ -4038,9 +4143,9 @@ getProperty(request: GetPropertyRequest): Promise<ExecutorProperty>; keys: keys }; try { - userAuth.getProperty(request).then((result) => { + userAuth.getProperty(request).then((result: account_osAccount.ExecutorProperty) => { console.log('getProperty result = ' + JSON.stringify(result)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getProperty error = ' + JSON.stringify(err)); }); } catch (e) { @@ -4076,6 +4181,7 @@ setProperty(request: SetPropertyRequest, callback: AsyncCallback<void>): v **示例:** ```js + import { BusinessError } from '@ohos.base'; let userAuth = new account_osAccount.UserAuth(); let request = { authType: account_osAccount.AuthType.PIN, @@ -4083,7 +4189,7 @@ setProperty(request: SetPropertyRequest, callback: AsyncCallback<void>): v setInfo: new Uint8Array([0]) }; try { - userAuth.setProperty(request, (err) => { + userAuth.setProperty(request, (err: BusinessError) => { if (err) { console.log('setProperty failed, error = ' + JSON.stringify(err)); } else { @@ -4128,16 +4234,17 @@ setProperty(request: SetPropertyRequest): Promise<void>; **示例:** ```js + import { BusinessError } from '@ohos.base'; let userAuth = new account_osAccount.UserAuth(); - let request = { + let request2 = { authType: account_osAccount.AuthType.PIN, key: account_osAccount.SetPropertyType.INIT_ALGORITHM, setInfo: new Uint8Array([0]) }; try { - userAuth.setProperty(request).then(() => { + userAuth.setProperty(request2).then(() => { console.log('setProperty successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('setProperty failed, error = ' + JSON.stringify(err)); }); } catch (e) { @@ -4195,7 +4302,7 @@ auth(challenge: Uint8Array, authType: AuthType, authTrustLevel: AuthTrustLevel, let authTrustLevel = account_osAccount.AuthTrustLevel.ATL1; try { userAuth.auth(challenge, authType, authTrustLevel, { - onResult: function(result,extraInfo){ + onResult: (result,extraInfo) => { console.log('auth result = ' + result); console.log('auth extraInfo = ' + JSON.stringify(extraInfo)); } @@ -4251,13 +4358,13 @@ authUser(userId: number, challenge: Uint8Array, authType: AuthType, authTrustLev **示例:** ```js let userAuth = new account_osAccount.UserAuth(); - let userID = 100; + let userID: number = 100; let challenge = new Uint8Array([0]); let authType = account_osAccount.AuthType.PIN; let authTrustLevel = account_osAccount.AuthTrustLevel.ATL1; try { userAuth.authUser(userID, challenge, authType, authTrustLevel, { - onResult: function(result,extraInfo){ + onResult: (result,extraInfo) => { console.log('authUser result = ' + result); console.log('authUser extraInfo = ' + JSON.stringify(extraInfo)); } @@ -4295,10 +4402,10 @@ cancelAuth(contextID: Uint8Array): void; **示例:** ```js let userAuth = new account_osAccount.UserAuth(); - let pinAuth = new account_osAccount.PINAuth(); + let pinAuth: account_osAccount.PINAuth = new account_osAccount.PINAuth(); let challenge = new Uint8Array([0]); let contextId = userAuth.auth(challenge, account_osAccount.AuthType.PIN, account_osAccount.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { + onResult: (result: number, extraInfo: account_osAccount.AuthResult) => { console.log('auth result = ' + result); console.log('auth extraInfo = ' + JSON.stringify(extraInfo)); } @@ -4328,7 +4435,7 @@ constructor() **示例:** ```js - let pinAuth = new account_osAccount.PINAuth(); + let pinAuth: account_osAccount.PINAuth = new account_osAccount.PINAuth(); ``` ### registerInputer8+ @@ -4359,11 +4466,11 @@ registerInputer(inputer: IInputer): void; **示例:** ```js - let pinAuth = new account_osAccount.PINAuth(); + let pinAuth: account_osAccount.PINAuth = new account_osAccount.PINAuth(); let password = new Uint8Array([0, 0, 0, 0, 0]); try { let result = pinAuth.registerInputer({ - onGetData: (authSubType, callback) => { + onGetData: (authSubType: account_osAccount.AuthSubType, callback: account_osAccount.IInputData) => { callback.onSetData(authSubType, password); } }); @@ -4387,7 +4494,7 @@ unregisterInputer(): void; **示例:** ```js - let pinAuth = new account_osAccount.PINAuth(); + let pinAuth: account_osAccount.PINAuth = new account_osAccount.PINAuth(); pinAuth.unregisterInputer(); ``` @@ -4426,10 +4533,10 @@ static registerInputer(authType: AuthType, inputer: IInputer): void **示例:** ```js let authType = account_osAccount.AuthType.DOMAIN; - let password = new Uint8Array([0, 0, 0, 0, 0]); + let password: Uint8Array = new Uint8Array([0, 0, 0, 0, 0]); try { account_osAccount.InputerManager.registerInputer(authType, { - onGetData: (authSubType, callback) => { + onGetData: (authSubType: account_osAccount.AuthSubType, callback: account_osAccount.IInputData) => { callback.onSetData(authSubType, password); } }); @@ -4500,8 +4607,10 @@ auth(domainAccountInfo: DomainAccountInfo, credential: Uint8Array, callback: IUs **示例:** ```js + import { AsyncCallback } from './@ohos.base'; let plugin = { - auth: (domainAccountInfo, credential, callback) => { + auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => { // mock authentication // notify authentication result callback.onResult(0, { @@ -4510,14 +4619,20 @@ auth(domainAccountInfo: DomainAccountInfo, credential: Uint8Array, callback: IUs freezingTime: 0 }); }, - authWithPopup: (domainAccountInfo, callback) => {}, - authWithToken: (domainAccountInfo, token, callback) => {}, - getAccountInfo: (domain, accountName, callback) => {}, - getAuthStatusInfo: (domainAccountInfo, callback) => {}, - bindAccount: (domainAccountInfo, localId, callback) => {}, - unbindAccount: (domainAccountInfo, callback) => {}, - isAccountTokenValid: (domainAccountInfo, token, callback) => {}, - getAccessToken: (options, callback) => {} + authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: account_osAccount.IUserAuthCallback) => {}, + authWithToken: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => {}, + getAccountInfo: (domain: string, accountName: string, + callback: AsyncCallback) => {}, + getAuthStatusInfo: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: AsyncCallback) => {}, + bindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, localId: number, + callback: AsyncCallback) => {}, + unbindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, callback: AsyncCallback) => {}, + isAccountTokenValid: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: AsyncCallback) => {}, + getAccessToken: (options: account_osAccount.GetDomainAccessTokenOptions, callback: AsyncCallback) => {} } account_osAccount.DomainAccountManager.registerPlugin(plugin); let userAuth = new account_osAccount.UserAuth(); @@ -4526,7 +4641,7 @@ auth(domainAccountInfo: DomainAccountInfo, credential: Uint8Array, callback: IUs let authTrustLevel = account_osAccount.AuthTrustLevel.ATL1; try { userAuth.auth(challenge, authType, authTrustLevel, { - onResult: (resultCode, authResult) => { + onResult: (resultCode: number, authResult: account_osAccount.AuthResult) => { console.log('auth resultCode = ' + resultCode); console.log('auth authResult = ' + JSON.stringify(authResult)); } @@ -4555,9 +4670,12 @@ authWithPopup(domainAccountInfo: DomainAccountInfo, callback: IUserAuthCallback) **示例:** ```js + import { AsyncCallback } from './@ohos.base'; let plugin = { - auth: (domainAccountInfo, credential, callback) => {}, - authWithPopup: (domainAccountInfo, callback) => { + auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => {}, + authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: account_osAccount.IUserAuthCallback) => { // mock authentication // notify authentication result callback.onResult(0, { @@ -4566,13 +4684,18 @@ authWithPopup(domainAccountInfo: DomainAccountInfo, callback: IUserAuthCallback) freezingTime: 0 }); }, - authWithToken: (domainAccountInfo, token, callback) => {}, - getAccountInfo: (domain, accountName, callback) => {}, - getAuthStatusInfo: (domainAccountInfo, callback) => {}, - bindAccount: (domainAccountInfo, localId, callback) => {}, - unbindAccount: (domainAccountInfo, callback) => {}, - isAccountTokenValid: (domainAccountInfo, token, callback) => {}, - getAccessToken: (options, callback) => {} + authWithToken: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => {}, + getAccountInfo: (domain: string, accountName: string, + callback: AsyncCallback) => {}, + getAuthStatusInfo: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: AsyncCallback) => {}, + bindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, localId: number, + callback: AsyncCallback) => {}, + unbindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, callback: AsyncCallback) => {}, + isAccountTokenValid: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: AsyncCallback) => {}, + getAccessToken: (options: account_osAccount.GetDomainAccessTokenOptions, callback: AsyncCallback) => {} } account_osAccount.DomainAccountManager.registerPlugin(plugin) ``` @@ -4597,10 +4720,14 @@ authWithToken(domainAccountInfo: DomainAccountInfo, token: Uint8Array, callback: **示例:** ```js + import { AsyncCallback } from './@ohos.base'; let plugin = { - auth: (domainAccountInfo, credential, callback) => {}, - authWithPopup: (domainAccountInfo, callback) => {}, - authWithToken: (domainAccountInfo, token, callback) => { + auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => {}, + authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: account_osAccount.IUserAuthCallback) => {}, + authWithToken: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => { // mock authentication // notify authentication result callback.onResult(0, { @@ -4609,12 +4736,16 @@ authWithToken(domainAccountInfo: DomainAccountInfo, token: Uint8Array, callback: freezingTime: 0 }); }, - getAccountInfo: (domain, accountName, callback) => {}, - getAuthStatusInfo: (domainAccountInfo, callback) => {}, - bindAccount: (domainAccountInfo, localId, callback) => {}, - unbindAccount: (domainAccountInfo, callback) => {}, - isAccountTokenValid: (domainAccountInfo, token, callback) => {}, - getAccessToken: (options, callback) => {} + getAccountInfo: (domain: string, accountName: string, + callback: AsyncCallback) => {}, + getAuthStatusInfo: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: AsyncCallback) => {}, + bindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, localId: number, + callback: AsyncCallback) => {}, + unbindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, callback: AsyncCallback) => {}, + isAccountTokenValid: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: AsyncCallback) => {}, + getAccessToken: (options: account_osAccount.GetDomainAccessTokenOptions, callback: AsyncCallback) => {} } account_osAccount.DomainAccountManager.registerPlugin(plugin) ``` @@ -4639,26 +4770,33 @@ getAccountInfo(domain: string, accountName: string, callback: AsyncCallback<D **示例:** ```js + import { AsyncCallback, BusinessError } from '@ohos.base'; let plugin = { - auth: (domainAccountInfo, credential, callback) => {}, - authWithPopup: (domainAccountInfo, callback) => {}, - authWithToken: (domainAccountInfo, token, callback) => {}, - getAccountInfo: (domain, accountName, callback) => { + auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => {}, + authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: account_osAccount.IUserAuthCallback) => {}, + authWithToken: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => {}, + getAccountInfo: (domain: string, accountName: string, + callback: AsyncCallback) => { // mock getting account information // notify result - callback({ - code: 0 - }, { + let code: BusinessError + callback(code, { domain: domain, accountName: accountName, accountId: 'xxxx' }) }, - getAuthStatusInfo: (domainAccountInfo, callback) => {}, - bindAccount: (domainAccountInfo, localId, callback) => {}, - unbindAccount: (domainAccountInfo, callback) => {}, - isAccountTokenValid: (domainAccountInfo, token, callback) => {}, - getAccessToken: (options, callback) => {} + getAuthStatusInfo: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: AsyncCallback) => {}, + bindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, localId: number, + callback: AsyncCallback) => {}, + unbindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, callback: AsyncCallback) => {}, + isAccountTokenValid: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: AsyncCallback) => {}, + getAccessToken: (options: account_osAccount.GetDomainAccessTokenOptions, callback: AsyncCallback) => {} } account_osAccount.DomainAccountManager.registerPlugin(plugin) ``` @@ -4682,23 +4820,30 @@ getAuthStatusInfo(domainAccountInfo: DomainAccountInfo, callback: AsyncCallback& **示例:** ```js + import { AsyncCallback, BusinessError } from '@ohos.base'; let plugin = { - auth: (domainAccountInfo, credential, callback) => {}, - authWithPopup: (domainAccountInfo, callback) => {}, - authWithToken: (domainAccountInfo, token, callback) => {}, - getAccountInfo: (domain, accountName, callback) => {}, - getAuthStatusInfo: (domainAccountInfo, callback) => { - callback({ - code: 0 - }, { + auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => {}, + authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: account_osAccount.IUserAuthCallback) => {}, + authWithToken: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => {}, + getAccountInfo: (domain: string, accountName: string, + callback: AsyncCallback) => {}, + getAuthStatusInfo: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: AsyncCallback) => { + let code: BusinessError; + callback(code, { remainTimes: 5, freezingTime: 0 }) }, - bindAccount: (domainAccountInfo, localId, callback) => {}, - unbindAccount: (domainAccountInfo, callback) => {}, - isAccountTokenValid: (domainAccountInfo, token, callback) => {}, - getAccessToken: (options, callback) => {} + bindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, localId: number, + callback: AsyncCallback) => {}, + unbindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, callback: AsyncCallback) => {}, + isAccountTokenValid: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: AsyncCallback) => {}, + getAccessToken: (options: account_osAccount.GetDomainAccessTokenOptions, callback: AsyncCallback) => {} } account_osAccount.DomainAccountManager.registerPlugin(plugin) ``` @@ -4722,20 +4867,29 @@ bindAccount(domainAccountInfo: DomainAccountInfo, localId: number, callback: Asy **示例:** ```js + import { AsyncCallback, BusinessError } from './@ohos.base'; let plugin = { - auth: (domainAccountInfo, credential, callback) => {}, - authWithPopup: (domainAccountInfo, callback) => {}, - authWithToken: (domainAccountInfo, token, callback) => {}, - getAccountInfo: (domain, accountName, callback) => {}, - getAuthStatusInfo: (domainAccountInfo, callback) => {}, - bindAccount: (domainAccountInfo, localId, callback) => { + auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => {}, + authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: account_osAccount.IUserAuthCallback) => {}, + authWithToken: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => {}, + getAccountInfo: (domain: string, accountName: string, + callback: AsyncCallback) => {}, + getAuthStatusInfo: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: AsyncCallback) => {}, + bindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, localId: number, + callback: AsyncCallback) => { // mock unbinding operation // notify binding result - callback({code: 0}) + let code: BusinessError; + callback(code) }, - unbindAccount: (domainAccountInfo, callback) => {}, - isAccountTokenValid: (domainAccountInfo, token, callback) => {}, - getAccessToken: (options, callback) => {} + unbindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, callback: AsyncCallback) => {}, + isAccountTokenValid: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: AsyncCallback) => {}, + getAccessToken: (options: account_osAccount.GetDomainAccessTokenOptions, callback: AsyncCallback) => {} } account_osAccount.DomainAccountManager.registerPlugin(plugin) ``` @@ -4759,20 +4913,29 @@ unbindAccount(domainAccountInfo: DomainAccountInfo, callback: AsyncCallback<v **示例:** ```js + import { AsyncCallback, BusinessError } from './@ohos.base'; let plugin = { - auth: (domainAccountInfo, credential, callback) => {}, - authWithPopup: (domainAccountInfo, callback) => {}, - authWithToken: (domainAccountInfo, token, callback) => {}, - getAccountInfo: (domain, accountName, callback) => {}, - getAuthStatusInfo: (domainAccountInfo, callback) => {}, - bindAccount: (domainAccountInfo, localId, callback) => {}, - unbindAccount: (domainAccountInfo, callback) => { + auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => {}, + authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: account_osAccount.IUserAuthCallback) => {}, + authWithToken: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => {}, + getAccountInfo: (domain: string, accountName: string, + callback: AsyncCallback) => {}, + getAuthStatusInfo: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: AsyncCallback) => {}, + bindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, localId: number, + callback: AsyncCallback) => {}, + unbindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, callback: AsyncCallback) => { // mock unbinding operation // notify unbinding result - callback({code: 0}) + let code: BusinessError; + callback(code) }, - isAccountTokenValid: (domainAccountInfo, token, callback) => {}, - getAccessToken: (options, callback) => {} + isAccountTokenValid: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: AsyncCallback) => {}, + getAccessToken: (options: account_osAccount.GetDomainAccessTokenOptions, callback: AsyncCallback) => {} } account_osAccount.DomainAccountManager.registerPlugin(plugin) ``` @@ -4797,20 +4960,29 @@ isAccountTokenValid(domainAccountInfo: DomainAccountInfo, token: Uint8Array, cal **示例:** ```js + import { AsyncCallback, BusinessError } from './@ohos.base'; let plugin = { - auth: (domainAccountInfo, credential, callback) => {}, - authWithPopup: (domainAccountInfo, callback) => {}, - authWithToken: (domainAccountInfo, token, callback) => {}, - getAccountInfo: (domain, accountName, callback) => {}, - getAuthStatusInfo: (domainAccountInfo, callback) => {}, - bindAccount: (domainAccountInfo, localId, callback) => {}, - unbindAccount: (domainAccountInfo, callback) => {}, - isAccountTokenValid: (domainAccountInfo, token, callback) => { + auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => {}, + authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: account_osAccount.IUserAuthCallback) => {}, + authWithToken: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => {}, + getAccountInfo: (domain: string, accountName: string, + callback: AsyncCallback) => {}, + getAuthStatusInfo: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: AsyncCallback) => {}, + bindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, localId: number, + callback: AsyncCallback) => {}, + unbindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, callback: AsyncCallback) => {}, + isAccountTokenValid: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: AsyncCallback) => { // mock checking operation // notify checking result - callback({code: 0}, true); + let code: BusinessError + callback(code, true); }, - getAccessToken: (options, callback) => {} + getAccessToken: (options: account_osAccount.GetDomainAccessTokenOptions, callback: AsyncCallback) => {} } account_osAccount.DomainAccountManager.registerPlugin(plugin) ``` @@ -4834,20 +5006,29 @@ getAccessToken(options: GetDomainAccessTokenOptions, callback: AsyncCallback< **示例:** ```js + import { AsyncCallback, BusinessError } from './@ohos.base'; let plugin = { - auth: (domainAccountInfo, credential, callback) => {}, - authWithPopup: (domainAccountInfo, callback) => {}, - authWithToken: (domainAccountInfo, token, callback) => {}, - getAccountInfo: (domain, accountName, callback) => {}, - getAuthStatusInfo: (domainAccountInfo, callback) => {}, - bindAccount: (domainAccountInfo, localId, callback) => {}, - unbindAccount: (domainAccountInfo, callback) => {}, - isAccountTokenValid: (domainAccountInfo, token, callback) => {}, - getAccessToken: (options, callback) => { + auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => {}, + authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: account_osAccount.IUserAuthCallback) => {}, + authWithToken: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => {}, + getAccountInfo: (domain: string, accountName: string, + callback: AsyncCallback) => {}, + getAuthStatusInfo: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: AsyncCallback) => {}, + bindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, localId: number, + callback: AsyncCallback) => {}, + unbindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, callback: AsyncCallback) => {}, + isAccountTokenValid: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: AsyncCallback) => {}, + getAccessToken: (options: account_osAccount.GetDomainAccessTokenOptions, callback: AsyncCallback) => { // mock getting operation - let token = new Uint8Array([0]); + //let token = new Uint8Array([0]); // notify result - callback({code: 0}, token); + let code: BusinessError + callback(code, token); } } account_osAccount.DomainAccountManager.registerPlugin(plugin) @@ -4882,16 +5063,24 @@ static registerPlugin(plugin: DomainPlugin): void **示例:** ```js + import { AsyncCallback } from './@ohos.base'; let plugin = { - auth: (domainAccountInfo, credential, callback) => {}, - authWithPopup: (domainAccountInfo, callback) => {}, - authWithToken: (domainAccountInfo, token, callback) => {}, - getAccountInfo: (domain, accountName, callback) => {}, - getAuthStatusInfo: (domainAccountInfo, callback) => {}, - bindAccount: (domainAccountInfo, localId, callback) => {}, - unbindAccount: (domainAccountInfo, callback) => {}, - isAccountTokenValid: (domainAccountInfo, token, callback) => {}, - getAccessToken: (options, callback) => {} + auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => {}, + authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: account_osAccount.IUserAuthCallback) => {}, + authWithToken: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: account_osAccount.IUserAuthCallback) => {}, + getAccountInfo: (domain: string, accountName: string, + callback: AsyncCallback) => {}, + getAuthStatusInfo: (domainAccountInfo: account_osAccount.DomainAccountInfo, + callback: AsyncCallback) => {}, + bindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, localId: number, + callback: AsyncCallback) => {}, + unbindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, callback: AsyncCallback) => {}, + isAccountTokenValid: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, + callback: AsyncCallback) => {}, + getAccessToken: (options: account_osAccount.GetDomainAccessTokenOptions, callback: AsyncCallback) => {} } try { account_osAccount.DomainAccountManager.registerPlugin(plugin); @@ -4968,7 +5157,7 @@ auth(domainAccountInfo: DomainAccountInfo, credential: Uint8Array, callback: IUs let credential = new Uint8Array([0]) try { account_osAccount.DomainAccountManager.auth(domainAccountInfo, credential, { - onResult: (resultCode, authResult) => { + onResult: (resultCode: number, authResult: account_osAccount.AuthResult) => { console.log('auth resultCode = ' + resultCode); console.log('auth authResult = ' + JSON.stringify(authResult)); } @@ -5015,7 +5204,7 @@ authWithPopup(callback: IUserAuthCallback): void ```js try { account_osAccount.DomainAccountManager.authWithPopup({ - onResult: (resultCode, authResult) => { + onResult: (resultCode: number, authResult: account_osAccount.AuthResult) => { console.log('auth resultCode = ' + resultCode); console.log('auth authResult = ' + JSON.stringify(authResult)); } @@ -5064,7 +5253,7 @@ authWithPopup(localId: number, callback: IUserAuthCallback): void ```js try { account_osAccount.DomainAccountManager.authWithPopup(100, { - onResult: (resultCode, authResult) => { + onResult: (resultCode: number, authResult: account_osAccount.AuthResult) => { console.log('authWithPopup resultCode = ' + resultCode); console.log('authWithPopup authResult = ' + JSON.stringify(authResult)); } @@ -5100,15 +5289,17 @@ hasAccount(domainAccountInfo: DomainAccountInfo, callback: AsyncCallback<bool | 12300001 | System service exception. | | 12300002 | Invalid domainAccountInfo. | | 12300013 | Network exception. | +| 12300111 | Operation timeout. | **示例:** ```js + import { BusinessError } from '@ohos.base'; let domainAccountInfo = { domain: 'CHINA', accountName: 'zhangsan' } try { - account_osAccount.DomainAccountManager.hasAccount(domainAccountInfo, (err, result) => { + account_osAccount.DomainAccountManager.hasAccount(domainAccountInfo, (err: BusinessError, result: boolean) => { if (err) { console.log('call hasAccount failed, error: ' + JSON.stringify(err)); } else { @@ -5151,17 +5342,19 @@ hasAccount(domainAccountInfo: DomainAccountInfo): Promise<boolean> | 12300001 | System service exception. | | 12300002 | Invalid domainAccountInfo. | | 12300013 | Network exception. | +| 12300111 | Operation timeout. | **示例:** ```js + import { BusinessError } from '@ohos.base'; let domainAccountInfo = { domain: 'CHINA', accountName: 'zhangsan' } try { - account_osAccount.DomainAccountManager.hasAccount(domainAccountInfo).then((result) => { + account_osAccount.DomainAccountManager.hasAccount(domainAccountInfo).then((result: boolean) => { console.log('hasAccount result: ' + result); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('call hasAccount failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -5199,6 +5392,7 @@ updateAccountToken(domainAccountInfo: DomainAccountInfo, token: Uint8Array, call **示例:** ```js + import { BusinessError } from '@ohos.base'; let domainAccountInfo = { domain: 'CHINA', accountName: 'zhangsan', @@ -5206,7 +5400,7 @@ updateAccountToken(domainAccountInfo: DomainAccountInfo, token: Uint8Array, call } let token = new Uint8Array([0]) try { - account_osAccount.DomainAccountManager.updateAccountToken(domainAccountInfo, token, (err) => { + account_osAccount.DomainAccountManager.updateAccountToken(domainAccountInfo, token, (err: BusinessError) => { if (err != null) { console.log('updateAccountToken failed, error: ' + JSON.stringify(err)); } else { @@ -5253,6 +5447,7 @@ updateAccountToken(domainAccountInfo: DomainAccountInfo, token: Uint8Array): Pro **示例:** ```js + import { BusinessError } from '@ohos.base'; let domainAccountInfo = { domain: 'CHINA', accountName: 'zhangsan', @@ -5262,7 +5457,7 @@ updateAccountToken(domainAccountInfo: DomainAccountInfo, token: Uint8Array): Pro try { account_osAccount.DomainAccountManager.updateAccountToken(domainAccountInfo, token).then(() => { console.log('updateAccountToken successfully'); - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('updateAccountToken failed, error: ' + JSON.stringify(err)); }); } catch (err) { @@ -5317,9 +5512,10 @@ openSession(callback: AsyncCallback<Uint8Array>): void; **示例:** ```js + import { BusinessError } from '@ohos.base'; let userIDM = new account_osAccount.UserIdentityManager(); try { - userIDM.openSession((err, challenge) => { + userIDM.openSession((err: BusinessError, challenge: Uint8Array) => { console.log('openSession error = ' + JSON.stringify(err)); console.log('openSession challenge = ' + JSON.stringify(challenge)); }); @@ -5354,11 +5550,12 @@ openSession(): Promise<Uint8Array>; **示例:** ```js + import { BusinessError } from '@ohos.base'; let userIDM = new account_osAccount.UserIdentityManager(); try { - userIDM.openSession().then((challenge) => { + userIDM.openSession().then((challengechallenge: Uint8Array) => { console.info('openSession challenge = ' + JSON.stringify(challenge)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.info('openSession error = ' + JSON.stringify(err)); }); } catch (e) { @@ -5399,23 +5596,24 @@ addCredential(credentialInfo: CredentialInfo, callback: IIdmCallback): void; **示例:** ```js - let password = new Uint8Array([0, 0, 0, 0, 0, 0]); - let pinAuth = new account_osAccount.PINAuth(); + import { BusinessError } from '@ohos.base'; + let password: Uint8Array = new Uint8Array([0, 0, 0, 0, 0, 0]); + let pinAuth: account_osAccount.PINAuth = new account_osAccount.PINAuth(); pinAuth.registerInputer({ - onGetData: (authSubType, callback) => { + onGetData: (authSubType: account_osAccount.AuthSubType, callback: account_osAccount.IInputData) => { callback.onSetData(authSubType, password); } }); - let credentialInfo = { + let credentialInfo: account_osAccount.CredentialInfo = { credType: account_osAccount.AuthType.PIN, credSubType: account_osAccount.AuthSubType.PIN_SIX, token: null }; let userIDM = new account_osAccount.UserIdentityManager(); - userIDM.openSession((err, challenge) => { + userIDM.openSession((err: BusinessError, challenge: Uint8Array) => { try { userIDM.addCredential(credentialInfo, { - onResult: (result, extraInfo) => { + onResult: (result: number, extraInfo: account_osAccount.RequestResult) => { console.log('addCredential result = ' + result); console.log('addCredential extraInfo = ' + extraInfo); } @@ -5459,30 +5657,31 @@ updateCredential(credentialInfo: CredentialInfo, callback: IIdmCallback): void; **示例:** ```js + import { BusinessError } from '@ohos.base'; let userIDM = new account_osAccount.UserIdentityManager(); - let userAuth = new account_osAccount.UserAuth(); - let pinAuth = new account_osAccount.PINAuth(); - let password = new Uint8Array([0, 0, 0, 0, 0, 0]); + let userAuth: account_osAccount.UserAuth = new account_osAccount.UserAuth(); + let pinAuth: account_osAccount.PINAuth = new account_osAccount.PINAuth(); + let password: Uint8Array = new Uint8Array([0, 0, 0, 0, 0, 0]); let credentialInfo = { credType: account_osAccount.AuthType.PIN, credSubType: account_osAccount.AuthSubType.PIN_SIX, token: null }; pinAuth.registerInputer({ - onGetData: (authSubType, callback) => { + onGetData: (authSubType: account_osAccount.AuthSubType, callback: account_osAccount.IInputData) => { callback.onSetData(authSubType, password); } }); - userIDM.openSession((err, challenge) => { + userIDM.openSession((err: BusinessError, challenge: Uint8Array) => { userAuth.auth(challenge, credentialInfo.credType, account_osAccount.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { + onResult: (result: number, extraInfo: account_osAccount.AuthResult) => { if (result != account_osAccount.ResultCode.SUCCESS) { return; } credentialInfo.token = extraInfo.token; try { userIDM.updateCredential(credentialInfo, { - onResult: (result, extraInfo) => { + onResult: (result: number, extraInfo: account_osAccount.RequestResult) => { console.log('updateCredential result = ' + result); console.log('updateCredential extraInfo = ' + extraInfo); } @@ -5541,7 +5740,7 @@ cancel(challenge: Uint8Array): void; **示例:** ```js let userIDM = new account_osAccount.UserIdentityManager(); - let challenge = new Uint8Array([0]); + let challenge: Uint8Array = new Uint8Array([0]); try { userIDM.cancel(challenge); } catch(err) { @@ -5578,10 +5777,10 @@ delUser(token: Uint8Array, callback: IIdmCallback): void; **示例:** ```js let userIDM = new account_osAccount.UserIdentityManager(); - let token = new Uint8Array([0]); + let token: Uint8Array = new Uint8Array([0]); try { userIDM.delUser(token, { - onResult: (result, extraInfo) => { + onResult: (result: number, extraInfo: account_osAccount.RequestResult) => { console.log('delUser result = ' + result); console.log('delUser extraInfo = ' + JSON.stringify(extraInfo)); } @@ -5623,11 +5822,11 @@ delCred(credentialId: Uint8Array, token: Uint8Array, callback: IIdmCallback): vo **示例:** ```js let userIDM = new account_osAccount.UserIdentityManager(); - let credentialId = new Uint8Array([0]); - let token = new Uint8Array([0]); + let credentialId: Uint8Array = new Uint8Array([0]); + let token: Uint8Array = new Uint8Array([0]); try { userIDM.delCred(credentialId, token, { - onResult: (result, extraInfo) => { + onResult: (result: number, extraInfo: account_osAccount.RequestResult) => { console.log('delCred result = ' + result); console.log('delCred extraInfo = ' + JSON.stringify(extraInfo)); } @@ -5664,9 +5863,10 @@ getAuthInfo(callback: AsyncCallback<Array<EnrolledCredInfo>>): void; **示例:** ```js + import { BusinessError } from '@ohos.base'; let userIDM = new account_osAccount.UserIdentityManager(); try { - userIDM.getAuthInfo((err, result) => { + userIDM.getAuthInfo((err: BusinessError, result: account_osAccount.EnrolledCredInfo[]) => { console.log('getAuthInfo err = ' + JSON.stringify(err)); console.log('getAuthInfo result = ' + JSON.stringify(result)); }); @@ -5704,9 +5904,11 @@ getAuthInfo(authType: AuthType, callback: AsyncCallback<Array<EnrolledCred **示例:** ```js + import { BusinessError } from '@ohos.base'; let userIDM = new account_osAccount.UserIdentityManager(); try { - userIDM.getAuthInfo(account_osAccount.AuthType.PIN, (err, result) => { + userIDM.getAuthInfo(account_osAccount.AuthType.PIN, + (err: BusinessError, result: account_osAccount.EnrolledCredInfo[]) => { console.log('getAuthInfo err = ' + JSON.stringify(err)); console.log('getAuthInfo result = ' + JSON.stringify(result)); }); @@ -5749,11 +5951,12 @@ getAuthInfo(authType?: AuthType): Promise<Array<EnrolledCredInfo>>; **示例:** ```js + import { BusinessError } from '@ohos.base'; let userIDM = new account_osAccount.UserIdentityManager(); try { - userIDM.getAuthInfo(account_osAccount.AuthType.PIN).then((result) => { + userIDM.getAuthInfo(account_osAccount.AuthType.PIN).then((result: account_osAccount.EnrolledCredInfo[]) => { console.log('getAuthInfo result = ' + JSON.stringify(result)) - }).catch((err) => { + }).catch((err: BusinessError) => { console.log('getAuthInfo error = ' + JSON.stringify(err)); }); } catch (e) { @@ -5792,10 +5995,10 @@ onSetData: (authSubType: AuthSubType, data: Uint8Array) => void; **示例:** ```js - let password = new Uint8Array([0, 0, 0, 0, 0, 0]); - let passwordNumber = new Uint8Array([1, 2, 3, 4]); + let password: Uint8Array = new Uint8Array([0, 0, 0, 0, 0, 0]); + let passwordNumber: Uint8Array = new Uint8Array([1, 2, 3, 4]); let inputer = { - onGetData: (authSubType, callback) => { + onGetData: (authSubType: account_osAccount.AuthSubType, callback: account_osAccount.IInputData) => { if (authSubType == account_osAccount.AuthSubType.PIN_NUMBER) { callback.onSetData(authSubType, passwordNumber); } else { @@ -5829,10 +6032,10 @@ onGetData: (authSubType: AuthSubType, callback: IInputData) => void; **示例:** ```js - let password = new Uint8Array([0, 0, 0, 0, 0, 0]); - let passwordNumber = new Uint8Array([1, 2, 3, 4]); + let password: Uint8Array = new Uint8Array([0, 0, 0, 0, 0, 0]); + let passwordNumber: Uint8Array = new Uint8Array([1, 2, 3, 4]); let inputer = { - onGetData: (authSubType, callback) => { + onGetData: (authSubType: account_osAccount.AuthSubType, callback: account_osAccount.IInputData) => { if (authSubType == account_osAccount.AuthSubType.PIN_NUMBER) { callback.onSetData(authSubType, passwordNumber); } else { @@ -5840,7 +6043,7 @@ onGetData: (authSubType: AuthSubType, callback: IInputData) => void; } } }; - let pinAuth = new account_osAccount.PINAuth(); + let pinAuth: account_osAccount.PINAuth = new account_osAccount.PINAuth(); let result = pinAuth.registerInputer(inputer); console.log('registerInputer result: ' + result); ``` @@ -5871,7 +6074,7 @@ onResult: (result: number, extraInfo: AuthResult) => void; **示例:** ```js let authCallback = { - onResult: (result, extraInfo) => { + onResult: (result: account_osAccount.AuthSubType, extraInfo: account_osAccount.IInputData) => { console.log('auth result = ' + result); console.log('auth extraInfo = ' + JSON.stringify(extraInfo)); } @@ -5899,11 +6102,11 @@ onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; **示例:** ```js let authCallback = { - onResult: (result, extraInfo) => { + onResult: (result: account_osAccount.AuthSubType, extraInfo: account_osAccount.IInputData) => { console.log('auth result = ' + result) console.log('auth extraInfo = ' + JSON.stringify(extraInfo)); }, - onAcquireInfo: (module, acquire, extraInfo) => { + onAcquireInfo: (module: number, acquire: number, extraInfo: account_osAccount.RequestResult) => { console.log('auth module = ' + module); console.log('auth acquire = ' + acquire); console.info('auth extraInfo = ' + JSON.stringify(extraInfo)); @@ -5937,7 +6140,7 @@ onResult: (result: number, extraInfo: RequestResult) => void; **示例:** ```js let idmCallback = { - onResult: (result, extraInfo) => { + onResult: (result: number, extraInfo: account_osAccount.RequestResult) => { console.log('callback result = ' + result) console.info('callback extraInfo = ' + JSON.stringify(extraInfo)); } @@ -5965,11 +6168,11 @@ onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; **示例:** ```js let idmCallback = { - onResult: (result, extraInfo) => { + onResult: (result: number, extraInfo: Object) => { console.log('callback result = ' + result) console.log('callback onResult = ' + JSON.stringify(extraInfo)); }, - onAcquireInfo: (module, acquire, extraInfo) => { + onAcquireInfo: (module: number, acquire: number, extraInfo: Object) => { console.log('callback module = ' + module); console.log('callback acquire = ' + acquire); console.log('callback onacquireinfo = ' + JSON.stringify(extraInfo)); diff --git a/zh-cn/application-dev/reference/apis/js-apis-overlay.md b/zh-cn/application-dev/reference/apis/js-apis-overlay.md index 26c956b547cd0685f62b5e0b8079dc4eb106a446..443442ccd92a8c956cd49ae197425e8ea9aa804e 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-overlay.md +++ b/zh-cn/application-dev/reference/apis/js-apis-overlay.md @@ -74,7 +74,7 @@ setOverlayEnabled(moduleName:string, isEnabled: boolean, callback: AsyncCallback | ----------- | ------ | ---- | --------------------------------------- | | moduleName | string | 是 | overlay特征module的HAP名称。 | | isEnabled | boolean | 是 | 值为true表示使能,值为false表示禁用。| -| callback | AsyncCallback\ | 是 | 回调函数,当设置指定module的overlay禁用使能状态成功时,err为undefined,否则为错误对象。 | +| callback | AsyncCallback\ | 是 | 回调函数,当设置指定module的overlay禁用使能状态成功时,err为null,否则为错误对象。 | **错误码:** @@ -179,7 +179,7 @@ setOverlayEnabledByBundleName(bundleName:string, moduleName:string, isEnabled: b | bundleName | string | 是 | 指定应用的bundle名称。 | | moduleName | string | 是 | 指定应用的overlay特征module的HAP名称。 | | isEnabled | boolean | 是 | 值为true表示使能,值为false表示禁用。 | -| callback | AsyncCallback\ | 是 | 回调函数。当设置指定应用的overlay module的禁用使能状态成功时,err为undefined,data为获取到的处置状态;否则为错误对象。 | +| callback | AsyncCallback\ | 是 | 回调函数。当设置指定应用的overlay module的禁用使能状态成功时,err为null,data为获取到的处置状态;否则为错误对象。 | **错误码:** @@ -270,7 +270,7 @@ getOverlayModuleInfo(moduleName: string, callback: AsyncCallback\ | 是 | 回调函数,当获取当前应用中指定的module的overlayModuleInfo信息成功时,err返回undefined。否则回调函数返回具体错误对象。 | +| callback | AsyncCallback\ | 是 | 回调函数,当获取当前应用中指定的module的overlayModuleInfo信息成功时,err返回null。否则回调函数返回具体错误对象。 | **错误码:** @@ -356,7 +356,7 @@ getTargetOverlayModuleInfos(targetModuleName: string, callback: AsyncCallback\> | 是 | 回调函数,当获取指定的目标module的OverlayModuleInfo成功时,err返回undefined。否则回调函数返回具体错误对象。 | +| callback | AsyncCallback\> | 是 | 回调函数,当获取指定的目标module的OverlayModuleInfo成功时,err返回null。否则回调函数返回具体错误对象。 | **错误码:** @@ -454,7 +454,7 @@ getOverlayModuleInfoByBundleName(bundleName: string, moduleName: string, callbac | ----------- | ------ | ---- | --------------------------------------- | | bundleName | string | 是 | 指定应用的bundle名称。 | | moduleName | string | 是 | 指定应用中的overlay module的HAP名称。缺省该字段时,查询接口将查询指定应用中所有module的OverlayModuleInfo信息。 | -| callback | AsyncCallback\> | 是 | 回调函数,当获取指定应用中指定module的OverlayModuleInfo信息成功时,err返回undefined。否则回调函数返回具体错误对象。 | +| callback | AsyncCallback\> | 是 | 回调函数,当获取指定应用中指定module的OverlayModuleInfo信息成功时,err返回null。否则回调函数返回具体错误对象。 | **错误码:** @@ -503,7 +503,7 @@ getOverlayModuleInfoByBundleName(bundleName: string, callback: AsyncCallback\> | 是 | 回调函数,当获取指定应用中所有module的OverlayModuleInfo信息成功时,err返回undefined。否则回调函数返回具体错误对象。 | +| callback | AsyncCallback\> | 是 | 回调函数,当获取指定应用中所有module的OverlayModuleInfo信息成功时,err返回null。否则回调函数返回具体错误对象。 | **错误码:** @@ -602,7 +602,7 @@ getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName: st | ----------- | ------ | ---- | --------------------------------------- | | targetBundleName | string | 是 | 指定目标应用的bundle名称。 | | moduleName | string | 是 | 指定应用中的目标module的HAP名称。缺省该字段时,查询接口将查询指定应用中所有module所关联的OverlayModuleInfo信息。 | -| callback | AsyncCallback\> | 是 | 回调函数,当获取指定应用中指定module关联的所有OverlayModuleInfo信息成功时,err返回undefined。否则回调函数返回具体错误对象。 | +| callback | AsyncCallback\> | 是 | 回调函数,当获取指定应用中指定module关联的所有OverlayModuleInfo信息成功时,err返回null。否则回调函数返回具体错误对象。 | **错误码:** @@ -651,7 +651,7 @@ getTargetOverlayModuleInfosByBundleName(targetBundleName: string, callback: Asyn | 参数名 | 类型 | 必填 | 说明 | | ----------- | ------ | ---- | --------------------------------------- | | targetBundleName | string | 是 | 指定目标应用的bundle名称。 | -| callback | AsyncCallback\> | 是 | 回调函数,当获取指定应用中所有module关联的所有OverlayModuleInfo信息成功时,err返回undefined。否则回调函数返回具体错误对象。 | +| callback | AsyncCallback\> | 是 | 回调函数,当获取指定应用中所有module关联的所有OverlayModuleInfo信息成功时,err返回null。否则回调函数返回具体错误对象。 | **错误码:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-promptAction.md b/zh-cn/application-dev/reference/apis/js-apis-promptAction.md index 26cc142354973d6bfb8dfc08680c207ae17f9227..4ee77a52fcc27050be976b1323040e8719076234 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-promptAction.md +++ b/zh-cn/application-dev/reference/apis/js-apis-promptAction.md @@ -191,7 +191,7 @@ try { | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | title | string\| [Resource](../arkui-ts/ts-types.md#resource类型)9+ | 否 | 标题文本。 | | message | string\| [Resource](../arkui-ts/ts-types.md#resource类型)9+ | 否 | 内容文本。 | -| buttons | [[Button](#button),[Button](#button)?,[Button](#button)?] | 否 | 对话框中按钮的数组,结构为:{text:'button', color: '\#666666'},支持1-3个按钮。其中第一个为positiveButton;第二个为negativeButton;第三个为neutralButton。 | +| buttons | Array<[Button](#button)> | 否 | 对话框中按钮的数组,结构为:{text:'button', color: '\#666666'},支持大于1个按钮。 | alignment10+ | [DialogAlignment](../arkui-ts/ts-methods-alert-dialog-box.md#dialogalignment枚举说明) | 否 | 弹窗在竖直方向上的对齐方式。
默认值:DialogAlignment.Default | | offset10+ | [Offset](../arkui-ts/ts-types.md#offset) | 否 | 弹窗相对alignment所在位置的偏移量。
默认值:{ dx: 0 , dy: 0 } | | maskRect10+| [Rectangle](../arkui-ts/ts-methods-alert-dialog-box.md#rectangle10类型说明) | 否 | 弹窗遮蔽层区域,在遮蔽层区域内的事件不透传,在遮蔽层区域外的事件透传。
默认值:{ x: 0, y: 0, width: '100%', height: '100%' } | diff --git a/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md b/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md index b8079e1e159ce94269bc25edaf7fa1cc8d8bf92c..fa26befc17777d0612517e4a3b4132dafa17a541 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @@ -40,14 +40,14 @@ publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback\): **示例**: ```ts - let timer = { - reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, - triggerTimeInSeconds: 10 - } +let timer:reminderAgent.ReminderRequestTimer = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 10 +} - reminderAgent.publishReminder(timer, (err, reminderId) => { - console.log("callback, reminderId = " + reminderId); - }); +reminderAgent.publishReminder(timer, (err: BusinessError, reminderId: number) => { + console.log("callback, reminderId = " + reminderId); +}); ``` @@ -76,14 +76,14 @@ publishReminder(reminderReq: ReminderRequest): Promise\ **示例**: ```ts - let timer = { - reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, - triggerTimeInSeconds: 10 - } +let timer:reminderAgent.ReminderRequestTimer = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 10 +} - reminderAgent.publishReminder(timer).then((reminderId) => { - console.log("promise, reminderId = " + reminderId); - }); +reminderAgent.publishReminder(timer).then((reminderId: number) => { + console.log("promise, reminderId = " + reminderId); +}); ``` @@ -108,8 +108,8 @@ cancelReminder(reminderId: number, callback: AsyncCallback\): void **示例**: ```ts -reminderAgent.cancelReminder(1, (err, data) => { - console.log("cancelReminder callback"); +reminderAgent.cancelReminder(1, (err: BusinessError, data: void) => { + console.log("cancelReminder callback"); }); ``` @@ -165,29 +165,29 @@ getValidReminders(callback: AsyncCallback\>): void **示例**: ```ts -reminderAgent.getValidReminders((err, reminders) => { - console.log("callback, getValidReminders length = " + reminders.length); - for (let i = 0; i < reminders.length; i++) { - console.log("getValidReminders = " + reminders[i]); - console.log("getValidReminders, reminderType = " + reminders[i].reminderType); - for (let j = 0; j < reminders[i].actionButton.length; j++) { - console.log("getValidReminders, actionButton.title = " + reminders[i].actionButton[j].title); - console.log("getValidReminders, actionButton.type = " + reminders[i].actionButton[j].type); - } - console.log("getValidReminders, wantAgent.pkgName = " + reminders[i].wantAgent.pkgName); - console.log("getValidReminders, wantAgent.abilityName = " + reminders[i].wantAgent.abilityName); - console.log("getValidReminders, maxScreenWantAgent.pkgName = " + reminders[i].maxScreenWantAgent.pkgName); - console.log("getValidReminders, maxScreenWantAgent.abilityName = " + reminders[i].maxScreenWantAgent.abilityName); - console.log("getValidReminders, ringDuration = " + reminders[i].ringDuration); - console.log("getValidReminders, snoozeTimes = " + reminders[i].snoozeTimes); - console.log("getValidReminders, timeInterval = " + reminders[i].timeInterval); - console.log("getValidReminders, title = " + reminders[i].title); - console.log("getValidReminders, content = " + reminders[i].content); - console.log("getValidReminders, expiredContent = " + reminders[i].expiredContent); - console.log("getValidReminders, snoozeContent = " + reminders[i].snoozeContent); - console.log("getValidReminders, notificationId = " + reminders[i].notificationId); - console.log("getValidReminders, slotType = " + reminders[i].slotType); +reminderAgent.getValidReminders((err: BusinessError, reminders: Array) => { + console.log("callback, getValidReminders length = " + reminders.length); + for (let i = 0; i < reminders.length; i++) { + console.log("getValidReminders = " + reminders[i]); + console.log("getValidReminders, reminderType = " + reminders[i].reminderType); + for (let j = 0; j < reminders[i].actionButton.length; j++) { + console.log("getValidReminders, actionButton.title = " + reminders[i].actionButton[j].title); + console.log("getValidReminders, actionButton.type = " + reminders[i].actionButton[j].type); } + console.log("getValidReminders, wantAgent.pkgName = " + reminders[i].wantAgent.pkgName); + console.log("getValidReminders, wantAgent.abilityName = " + reminders[i].wantAgent.abilityName); + console.log("getValidReminders, maxScreenWantAgent.pkgName = " + reminders[i].maxScreenWantAgent.pkgName); + console.log("getValidReminders, maxScreenWantAgent.abilityName = " + reminders[i].maxScreenWantAgent.abilityName); + console.log("getValidReminders, ringDuration = " + reminders[i].ringDuration); + console.log("getValidReminders, snoozeTimes = " + reminders[i].snoozeTimes); + console.log("getValidReminders, timeInterval = " + reminders[i].timeInterval); + console.log("getValidReminders, title = " + reminders[i].title); + console.log("getValidReminders, content = " + reminders[i].content); + console.log("getValidReminders, expiredContent = " + reminders[i].expiredContent); + console.log("getValidReminders, snoozeContent = " + reminders[i].snoozeContent); + console.log("getValidReminders, notificationId = " + reminders[i].notificationId); + console.log("getValidReminders, slotType = " + reminders[i].slotType); + } }) ``` @@ -212,30 +212,31 @@ getValidReminders(): Promise\> **示例**: ```ts -reminderAgent.getValidReminders().then((reminders) => { - console.log("promise, getValidReminders length = " + reminders.length); - for (let i = 0; i < reminders.length; i++) { - console.log("getValidReminders = " + reminders[i]); - console.log("getValidReminders, reminderType = " + reminders[i].reminderType); - for (let j = 0; j < reminders[i].actionButton.length; j++) { - console.log("getValidReminders, actionButton.title = " + reminders[i].actionButton[j].title); - console.log("getValidReminders, actionButton.type = " + reminders[i].actionButton[j].type); - } - console.log("getValidReminders, wantAgent.pkgName = " + reminders[i].wantAgent.pkgName); - console.log("getValidReminders, wantAgent.abilityName = " + reminders[i].wantAgent.abilityName); - console.log("getValidReminders, maxScreenWantAgent.pkgName = " + reminders[i].maxScreenWantAgent.pkgName); - console.log("getValidReminders, maxScreenWantAgent.abilityName = " + reminders[i].maxScreenWantAgent.abilityName); - console.log("getValidReminders, ringDuration = " + reminders[i].ringDuration); - console.log("getValidReminders, snoozeTimes = " + reminders[i].snoozeTimes); - console.log("getValidReminders, timeInterval = " + reminders[i].timeInterval); - console.log("getValidReminders, title = " + reminders[i].title); - console.log("getValidReminders, content = " + reminders[i].content); - console.log("getValidReminders, expiredContent = " + reminders[i].expiredContent); - console.log("getValidReminders, snoozeContent = " + reminders[i].snoozeContent); - console.log("getValidReminders, notificationId = " + reminders[i].notificationId); - console.log("getValidReminders, slotType = " + reminders[i].slotType); +reminderAgent.getValidReminders().then((reminders: Array) => { + console.log("promise, getValidReminders length = " + reminders.length); + for (let i = 0; i < reminders.length; i++) { + console.log("getValidReminders = " + reminders[i]); + console.log("getValidReminders, reminderType = " + reminders[i].reminderType); + for (let j = 0; j < reminders[i].actionButton.length; j++) { + console.log("getValidReminders, actionButton.title = " + reminders[i].actionButton[j].title); + console.log("getValidReminders, actionButton.type = " + reminders[i].actionButton[j].type); } + console.log("getValidReminders, wantAgent.pkgName = " + reminders[i].wantAgent.pkgName); + console.log("getValidReminders, wantAgent.abilityName = " + reminders[i].wantAgent.abilityName); + console.log("getValidReminders, maxScreenWantAgent.pkgName = " + reminders[i].maxScreenWantAgent.pkgName); + console.log("getValidReminders, maxScreenWantAgent.abilityName = " + reminders[i].maxScreenWantAgent.abilityName); + console.log("getValidReminders, ringDuration = " + reminders[i].ringDuration); + console.log("getValidReminders, snoozeTimes = " + reminders[i].snoozeTimes); + console.log("getValidReminders, timeInterval = " + reminders[i].timeInterval); + console.log("getValidReminders, title = " + reminders[i].title); + console.log("getValidReminders, content = " + reminders[i].content); + console.log("getValidReminders, expiredContent = " + reminders[i].expiredContent); + console.log("getValidReminders, snoozeContent = " + reminders[i].snoozeContent); + console.log("getValidReminders, notificationId = " + reminders[i].notificationId); + console.log("getValidReminders, slotType = " + reminders[i].slotType); + } }) + ``` @@ -259,8 +260,8 @@ cancelAllReminders(callback: AsyncCallback\): void **示例**: ```ts -reminderAgent.cancelAllReminders((err, data) =>{ - console.log("cancelAllReminders callback") +reminderAgent.cancelAllReminders((err: BusinessError, data: void) =>{ + console.log("cancelAllReminders callback") }) ``` @@ -311,13 +312,13 @@ addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback\): voi **示例**: ```ts -import notification from '@ohos.notification' +import notification from '@ohos.notificationManager' -let mySlot = { - type: notification.SlotType.SOCIAL_COMMUNICATION +let mySlot:notification.NotificationSlot = { + type: notification.SlotType.SOCIAL_COMMUNICATION } -reminderAgent.addNotificationSlot(mySlot, (err, data) => { - console.log("addNotificationSlot callback"); +reminderAgent.addNotificationSlot(mySlot, (err: BusinessError, data: void) => { + console.log("addNotificationSlot callback"); }); ``` @@ -348,13 +349,13 @@ addNotificationSlot(slot: NotificationSlot): Promise\ **示例**: ```ts -import notification from '@ohos.notification' +import notification from '@ohos.notificationManager' -let mySlot = { - type: notification.SlotType.SOCIAL_COMMUNICATION +let mySlot:notification.NotificationSlot = { + type: notification.SlotType.SOCIAL_COMMUNICATION } reminderAgent.addNotificationSlot(mySlot).then(() => { - console.log("addNotificationSlot promise"); + console.log("addNotificationSlot promise"); }); ``` @@ -382,8 +383,8 @@ removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback\ ```ts import notification from '@ohos.notification' -reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, (err, data) => { - console.log("removeNotificationSlot callback"); +reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, (err: BusinessError, data: void) => { + console.log("removeNotificationSlot callback"); }); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md b/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md index edf8484c4c3665e03c2818d40a7e13eda695683f..28ed005288246e57e76b77785a0a1e917314acbe 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @@ -45,22 +45,18 @@ publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback\): **示例**: ```ts -let timer = { - reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, - triggerTimeInSeconds: 10 +let timer: reminderAgentManager.ReminderRequestTimer = { + reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 10 } -try { - reminderAgentManager.publishReminder(timer, (err, reminderId) => { - if (err) { - console.log("callback err code:" + err.code + " message:" + err.message); - } else { - console.log("callback, reminderId = " + reminderId); - } - }); -} catch (error) { - console.log("publishReminder code:" + error.code + " message:" + error.message); -}; +reminderAgentManager.publishReminder(timer, (err: BusinessError, reminderId: number) => { + if (err) { + console.log("callback err code:" + err.code + " message:" + err.message); + } else { + console.log("callback, reminderId = " + reminderId); + } +}); ``` ## reminderAgentManager.publishReminder @@ -98,20 +94,16 @@ publishReminder(reminderReq: ReminderRequest): Promise\ **示例**: ```ts -let timer = { - reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, - triggerTimeInSeconds: 10 +let timer: reminderAgentManager.ReminderRequestTimer = { + reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 10 } -try { - reminderAgentManager.publishReminder(timer).then((reminderId) => { - console.log("promise, reminderId = " + reminderId); - }).catch(err => { - console.log("promise err code:" + err.code + " message:" + err.message); - }); -} catch (error) { - console.log("publishReminder code:" + error.code + " message:" + error.message); -}; +reminderAgentManager.publishReminder(timer).then((reminderId: number) => { + console.log("promise, reminderId = " + reminderId); +}).catch((err: BusinessError) => { + console.log("promise err code:" + err.code + " message:" + err.message); +}); ``` @@ -142,17 +134,14 @@ cancelReminder(reminderId: number, callback: AsyncCallback\): void **示例**: ```ts -try { - reminderAgentManager.cancelReminder(1, (err, data) => { - if (err) { - console.log("callback err code:" + err.code + " message:" + err.message); - } else { - console.log("cancelReminder callback"); - } - }); -} catch (error) { - console.log("cancelReminder code:" + error.code + " message:" + error.message); -}; +let reminderId: number = 1; +reminderAgentManager.cancelReminder(reminderId, (err: BusinessError, data: void) => { + if (err) { + console.log("callback err code:" + err.code + " message:" + err.message); + } else { + console.log("cancelReminder callback"); + } +}); ``` ## reminderAgentManager.cancelReminder @@ -187,15 +176,12 @@ cancelReminder(reminderId: number): Promise\ **示例**: ```ts -try { - reminderAgentManager.cancelReminder(1).then(() => { - console.log("cancelReminder promise"); - }).catch(err => { - console.log("promise err code:" + err.code + " message:" + err.message); - }); -} catch (error) { - console.log("cancelReminder code:" + error.code + " message:" + error.message); -}; +let reminderId: number = 1; +reminderAgentManager.cancelReminder(reminderId).then(() => { + console.log("cancelReminder promise"); +}).catch((err: BusinessError) => { + console.log("promise err code:" + err.code + " message:" + err.message); +}); ``` ## reminderAgentManager.getValidReminders @@ -223,38 +209,34 @@ getValidReminders(callback: AsyncCallback>): void **示例**: ```ts -try { - reminderAgentManager.getValidReminders((err, reminders) => { - if (err) { - console.log("callback err code:" + err.code + " message:" + err.message); - } else { - console.log("callback, getValidReminders length = " + reminders.length); - for (let i = 0; i < reminders.length; i++) { - console.log("getValidReminders = " + reminders[i]); - console.log("getValidReminders, reminderType = " + reminders[i].reminderType); - for (let j = 0; j < reminders[i].actionButton.length; j++) { - console.log("getValidReminders, actionButton.title = " + reminders[i].actionButton[j].title); - console.log("getValidReminders, actionButton.type = " + reminders[i].actionButton[j].type); - } - console.log("getValidReminders, wantAgent.pkgName = " + reminders[i].wantAgent.pkgName); - console.log("getValidReminders, wantAgent.abilityName = " + reminders[i].wantAgent.abilityName); - console.log("getValidReminders, maxScreenWantAgent.pkgName = " + reminders[i].maxScreenWantAgent.pkgName); - console.log("getValidReminders, maxScreenWantAgent.abilityName = " + reminders[i].maxScreenWantAgent.abilityName); - console.log("getValidReminders, ringDuration = " + reminders[i].ringDuration); - console.log("getValidReminders, snoozeTimes = " + reminders[i].snoozeTimes); - console.log("getValidReminders, timeInterval = " + reminders[i].timeInterval); - console.log("getValidReminders, title = " + reminders[i].title); - console.log("getValidReminders, content = " + reminders[i].content); - console.log("getValidReminders, expiredContent = " + reminders[i].expiredContent); - console.log("getValidReminders, snoozeContent = " + reminders[i].snoozeContent); - console.log("getValidReminders, notificationId = " + reminders[i].notificationId); - console.log("getValidReminders, slotType = " + reminders[i].slotType); - } - } - }) -} catch (error) { - console.log("getValidReminders code:" + error.code + " message:" + error.message); -}; +reminderAgentManager.getValidReminders((err: BusinessError, reminders: Array) => { + if (err) { + console.log("callback err code:" + err.code + " message:" + err.message); + } else { + console.log("callback, getValidReminders length = " + reminders.length); + for (let i = 0; i < reminders.length; i++) { + console.log("getValidReminders = " + reminders[i]); + console.log("getValidReminders, reminderType = " + reminders[i].reminderType); + for (let j = 0; j < reminders[i].actionButton.length; j++) { + console.log("getValidReminders, actionButton.title = " + reminders[i].actionButton[j].title); + console.log("getValidReminders, actionButton.type = " + reminders[i].actionButton[j].type); + } + console.log("getValidReminders, wantAgent.pkgName = " + reminders[i].wantAgent.pkgName); + console.log("getValidReminders, wantAgent.abilityName = " + reminders[i].wantAgent.abilityName); + console.log("getValidReminders, maxScreenWantAgent.pkgName = " + reminders[i].maxScreenWantAgent.pkgName); + console.log("getValidReminders, maxScreenWantAgent.abilityName = " + reminders[i].maxScreenWantAgent.abilityName); + console.log("getValidReminders, ringDuration = " + reminders[i].ringDuration); + console.log("getValidReminders, snoozeTimes = " + reminders[i].snoozeTimes); + console.log("getValidReminders, timeInterval = " + reminders[i].timeInterval); + console.log("getValidReminders, title = " + reminders[i].title); + console.log("getValidReminders, content = " + reminders[i].content); + console.log("getValidReminders, expiredContent = " + reminders[i].expiredContent); + console.log("getValidReminders, snoozeContent = " + reminders[i].snoozeContent); + console.log("getValidReminders, notificationId = " + reminders[i].notificationId); + console.log("getValidReminders, slotType = " + reminders[i].slotType); + } + } +}); ``` ## reminderAgentManager.getValidReminders @@ -282,36 +264,32 @@ getValidReminders(): Promise\> **示例**: ```ts -try { - reminderAgentManager.getValidReminders().then((reminders) => { - console.log("promise, getValidReminders length = " + reminders.length); - for (let i = 0; i < reminders.length; i++) { - console.log("getValidReminders = " + reminders[i]); - console.log("getValidReminders, reminderType = " + reminders[i].reminderType); - for (let j = 0; j < reminders[i].actionButton.length; j++) { - console.log("getValidReminders, actionButton.title = " + reminders[i].actionButton[j].title); - console.log("getValidReminders, actionButton.type = " + reminders[i].actionButton[j].type); - } - console.log("getValidReminders, wantAgent.pkgName = " + reminders[i].wantAgent.pkgName); - console.log("getValidReminders, wantAgent.abilityName = " + reminders[i].wantAgent.abilityName); - console.log("getValidReminders, maxScreenWantAgent.pkgName = " + reminders[i].maxScreenWantAgent.pkgName); - console.log("getValidReminders, maxScreenWantAgent.abilityName = " + reminders[i].maxScreenWantAgent.abilityName); - console.log("getValidReminders, ringDuration = " + reminders[i].ringDuration); - console.log("getValidReminders, snoozeTimes = " + reminders[i].snoozeTimes); - console.log("getValidReminders, timeInterval = " + reminders[i].timeInterval); - console.log("getValidReminders, title = " + reminders[i].title); - console.log("getValidReminders, content = " + reminders[i].content); - console.log("getValidReminders, expiredContent = " + reminders[i].expiredContent); - console.log("getValidReminders, snoozeContent = " + reminders[i].snoozeContent); - console.log("getValidReminders, notificationId = " + reminders[i].notificationId); - console.log("getValidReminders, slotType = " + reminders[i].slotType); - } - }).catch(err => { - console.log("promise err code:" + err.code + " message:" + err.message); - }); -} catch (error) { - console.log("getValidReminders code:" + error.code + " message:" + error.message); -}; +reminderAgentManager.getValidReminders().then((reminders: Array) => { + console.log("promise, getValidReminders length = " + reminders.length); + for (let i = 0; i < reminders.length; i++) { + console.log("getValidReminders = " + reminders[i]); + console.log("getValidReminders, reminderType = " + reminders[i].reminderType); + for (let j = 0; j < reminders[i].actionButton.length; j++) { + console.log("getValidReminders, actionButton.title = " + reminders[i].actionButton[j].title); + console.log("getValidReminders, actionButton.type = " + reminders[i].actionButton[j].type); + } + console.log("getValidReminders, wantAgent.pkgName = " + reminders[i].wantAgent.pkgName); + console.log("getValidReminders, wantAgent.abilityName = " + reminders[i].wantAgent.abilityName); + console.log("getValidReminders, maxScreenWantAgent.pkgName = " + reminders[i].maxScreenWantAgent.pkgName); + console.log("getValidReminders, maxScreenWantAgent.abilityName = " + reminders[i].maxScreenWantAgent.abilityName); + console.log("getValidReminders, ringDuration = " + reminders[i].ringDuration); + console.log("getValidReminders, snoozeTimes = " + reminders[i].snoozeTimes); + console.log("getValidReminders, timeInterval = " + reminders[i].timeInterval); + console.log("getValidReminders, title = " + reminders[i].title); + console.log("getValidReminders, content = " + reminders[i].content); + console.log("getValidReminders, expiredContent = " + reminders[i].expiredContent); + console.log("getValidReminders, snoozeContent = " + reminders[i].snoozeContent); + console.log("getValidReminders, notificationId = " + reminders[i].notificationId); + console.log("getValidReminders, slotType = " + reminders[i].slotType); + } +}).catch((err: BusinessError) => { + console.log("promise err code:" + err.code + " message:" + err.message); +}); ``` ## reminderAgentManager.cancelAllReminders @@ -339,17 +317,13 @@ cancelAllReminders(callback: AsyncCallback\): void **示例**: ```ts -try { - reminderAgentManager.cancelAllReminders((err, data) =>{ - if (err) { - console.log("callback err code:" + err.code + " message:" + err.message); - } else { - console.log("cancelAllReminders callback") - } - }) -} catch (error) { - console.log("cancelAllReminders code:" + error.code + " message:" + error.message); -}; +reminderAgentManager.cancelAllReminders((err: BusinessError, data: void) =>{ + if (err) { + console.log("callback err code:" + err.code + " message:" + err.message); + } else { + console.log("cancelAllReminders callback") + } +}); ``` ## reminderAgentManager.cancelAllReminders @@ -377,15 +351,11 @@ cancelAllReminders(): Promise\ **示例**: ```ts -try { - reminderAgentManager.cancelAllReminders().then(() => { - console.log("cancelAllReminders promise") - }).catch(err => { - console.log("promise err code:" + err.code + " message:" + err.message); - }); -} catch (error) { - console.log("cancelAllReminders code:" + error.code + " message:" + error.message); -}; +reminderAgentManager.cancelAllReminders().then(() => { + console.log("cancelAllReminders promise") +}).catch((err: BusinessError) => { + console.log("promise err code:" + err.code + " message:" + err.message); +}); ``` @@ -407,22 +377,19 @@ addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback\): voi **示例**: ```ts -import notification from '@ohos.notification' +import notification from '@ohos.notificationManager' -let mySlot = { - type: notification.SlotType.SOCIAL_COMMUNICATION +let mySlot: notification.NotificationSlot = { + type: notification.SlotType.SOCIAL_COMMUNICATION } -try { - reminderAgentManager.addNotificationSlot(mySlot, (err, data) => { - if (err) { - console.log("callback err code:" + err.code + " message:" + err.message); - } else { - console.log("addNotificationSlot callback"); - } - }); -} catch (error) { - console.log("addNotificationSlot code:" + error.code + " message:" + error.message); -}; + +reminderAgentManager.addNotificationSlot(mySlot, (err: BusinessError, data: void) => { + if (err) { + console.log("callback err code:" + err.code + " message:" + err.message); + } else { + console.log("addNotificationSlot callback"); + } +}); ``` @@ -449,20 +416,16 @@ addNotificationSlot(slot: NotificationSlot): Promise\ **示例**: ```ts -import notification from '@ohos.notification' +import notification from '@ohos.notificationManager' -let mySlot = { - type: notification.SlotType.SOCIAL_COMMUNICATION +let mySlot: notification.NotificationSlot = { + type: notification.SlotType.SOCIAL_COMMUNICATION } -try { - reminderAgentManager.addNotificationSlot(mySlot).then(() => { - console.log("addNotificationSlot promise"); - }).catch(err => { - console.log("promise err code:" + err.code + " message:" + err.message); - }); -} catch (error) { - console.log("addNotificationSlot code:" + error.code + " message:" + error.message); -}; +reminderAgentManager.addNotificationSlot(mySlot).then(() => { + console.log("addNotificationSlot promise"); +}).catch((err: BusinessError) => { + console.log("promise err code:" + err.code + " message:" + err.message); +}); ``` @@ -484,19 +447,16 @@ removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback\ **示例**: ```ts -import notification from '@ohos.notification' - -try { - reminderAgentManager.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, (err, data) => { - if (err) { - console.log("callback err code:" + err.code + " message:" + err.message); - } else { - console.log("removeNotificationSlot callback"); - } - }); -} catch (error) { - console.log("removeNotificationSlot code:" + error.code + " message:" + error.message); -}; +import notification from '@ohos.notificationManager' + +reminderAgentManager.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, + (err: BusinessError, data: void) => { + if (err) { + console.log("callback err code:" + err.code + " message:" + err.message); + } else { + console.log("removeNotificationSlot callback"); + } +}); ``` @@ -523,17 +483,13 @@ removeNotificationSlot(slotType: notification.SlotType): Promise\ **示例**: ```ts -import notification from '@ohos.notification' - -try { - reminderAgentManager.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION).then(() => { - console.log("removeNotificationSlot promise"); - }).catch(err => { - console.log("promise err code:" + err.code + " message:" + err.message); - }); -} catch (error) { - console.log("removeNotificationSlot code:" + error.code + " message:" + error.message); -}; +import notification from '@ohos.notificationManager' + +reminderAgentManager.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION).then(() => { + console.log("removeNotificationSlot promise"); +}).catch((err: BusinessError) => { + console.log("promise err code:" + err.code + " message:" + err.message); +}); ``` ## ActionButtonType diff --git a/zh-cn/application-dev/reference/apis/js-apis-request.md b/zh-cn/application-dev/reference/apis/js-apis-request.md index eec7af90de0a05030997618f7915a077aeba3580..0955476d7c94a657f242b0aa49d0c8ca9d34a376 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-request.md +++ b/zh-cn/application-dev/reference/apis/js-apis-request.md @@ -1853,7 +1853,7 @@ resume(callback: AsyncCallback<void>): void on(event: 'progress', callback: (progress: Progress) => void): void -订阅任务进度的监听。 +订阅前端任务进度的监听。 **系统能力**: SystemCapability.Request.FileTransferAgent @@ -1889,7 +1889,7 @@ on(event: 'progress', callback: (progress: Progress) => void): void url: 'http://127.0.0.1', title: 'taskOnTest', description: 'Sample code for event listening', - mode: request.agent.Mode.BACKGROUND, + mode: request.agent.Mode.FOREGROUND, overwrite: false, method: "PUT", data: attachments, @@ -1925,7 +1925,7 @@ on(event: 'progress', callback: (progress: Progress) => void): void on(event: 'completed', callback: (progress: Progress) => void): void -订阅任务完成的监听。 +订阅前端任务完成的监听。 **系统能力**: SystemCapability.Request.FileTransferAgent @@ -1961,7 +1961,7 @@ on(event: 'completed', callback: (progress: Progress) => void): void url: 'http://127.0.0.1', title: 'taskOnTest', description: 'Sample code for event listening', - mode: request.agent.Mode.BACKGROUND, + mode: request.agent.Mode.FOREGROUND, overwrite: false, method: "PUT", data: attachments, @@ -1997,7 +1997,7 @@ on(event: 'completed', callback: (progress: Progress) => void): void on(event: 'failed', callback: (progress: Progress) => void): void -订阅任务失败的监听。 +订阅前端任务失败的监听。 **系统能力**: SystemCapability.Request.FileTransferAgent @@ -2033,7 +2033,7 @@ on(event: 'failed', callback: (progress: Progress) => void): void url: 'http://127.0.0.1', title: 'taskOnTest', description: 'Sample code for event listening', - mode: request.agent.Mode.BACKGROUND, + mode: request.agent.Mode.FOREGROUND, overwrite: false, method: "PUT", data: attachments, @@ -2070,7 +2070,7 @@ on(event: 'failed', callback: (progress: Progress) => void): void off(event: 'progress', callback?: (progress: Progress) => void): void -取消订阅任务进度的监听。 +取消订阅前端任务进度的监听。 **系统能力**: SystemCapability.Request.FileTransferAgent @@ -2106,7 +2106,7 @@ off(event: 'progress', callback?: (progress: Progress) => void): void url: 'http://127.0.0.1', title: 'taskOffTest', description: 'Sample code for event listening', - mode: request.agent.Mode.BACKGROUND, + mode: request.agent.Mode.FOREGROUND, overwrite: false, method: "PUT", data: attachments, @@ -2143,7 +2143,7 @@ off(event: 'progress', callback?: (progress: Progress) => void): void off(event: 'completed', callback?: (progress: Progress) => void): void -取消订阅任务完成的监听。 +取消订阅前端任务完成的监听。 **系统能力**: SystemCapability.Request.FileTransferAgent @@ -2179,7 +2179,7 @@ off(event: 'completed', callback?: (progress: Progress) => void): void url: 'http://127.0.0.1', title: 'taskOffTest', description: 'Sample code for event listening', - mode: request.agent.Mode.BACKGROUND, + mode: request.agent.Mode.FOREGROUND, overwrite: false, method: "PUT", data: attachments, @@ -2216,7 +2216,7 @@ off(event: 'completed', callback?: (progress: Progress) => void): void off(event: 'failed', callback?: (progress: Progress) => void): void -取消订阅任务失败的监听。 +取消订阅前端任务失败的监听。 **系统能力**: SystemCapability.Request.FileTransferAgent @@ -2252,7 +2252,7 @@ off(event: 'failed', callback?: (progress: Progress) => void): void url: 'http://127.0.0.1', title: 'taskOffTest', description: 'Sample code for event listening', - mode: request.agent.Mode.BACKGROUND, + mode: request.agent.Mode.FOREGROUND, overwrite: false, method: "PUT", data: attachments, diff --git a/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md b/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md index 5d29a95caa6064494c7e46818d38cf5cbdd2f5ad..e156afefb76d594adb9ada0da83bb3fcc3cd87ef 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @@ -106,7 +106,10 @@ getResourceManager(): Promise<ResourceManager> **示例:** ```js - resourceManager.getResourceManager().then(mgr => { + import resourceManager from '@ohos.resourceManager'; + import { BusinessError } from '@ohos.base'; + + resourceManager.getResourceManager().then((mgr: resourceManager.ResourceManager) => { mgr.getStringValue(0x1000000, (error, value) => { if (error != null) { console.log("error is " + error); @@ -114,7 +117,7 @@ getResourceManager(): Promise<ResourceManager> let str = value; } }); - }).catch(error => { + }).catch((error: BusinessError) => { console.log("error is " + error); }); ``` @@ -145,8 +148,11 @@ getResourceManager(bundleName: string): Promise<ResourceManager> **示例:** ```js - resourceManager.getResourceManager("com.example.myapplication").then(mgr => { - }).catch(error => { + import resourceManager from '@ohos.resourceManager'; + import { BusinessError } from '@ohos.base'; + + resourceManager.getResourceManager("com.example.myapplication").then((mgr: resourceManager.ResourceManager) => { + }).catch((error: BusinessError) => { }); ``` @@ -175,12 +181,13 @@ getSystemResourceManager(): ResourceManager **示例:** ```js import resourceManager from '@ohos.resourceManager'; +import { BusinessError } from '@ohos.base'; try { let systemResourceManager = resourceManager.getSystemResourceManager(); - systemResourceManager.getStringValue($r('sys.string.ohos_lab_vibrate').id).then(value => { + systemResourceManager.getStringValue($r('sys.string.ohos_lab_vibrate').id).then((value: string) => { let str = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("systemResourceManager getStringValue promise error is " + error); }); } catch (error) { @@ -414,7 +421,9 @@ getStringSync(resource: Resource): string **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.string.test').id @@ -462,7 +471,9 @@ getStringSync(resource: Resource, ...args: Array): string **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.string.test').id @@ -626,10 +637,12 @@ getStringValue(resId: number): Promise<string> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getStringValue($r('app.string.test').id).then(value => { + this.context.resourceManager.getStringValue($r('app.string.test').id).then((value: string) => { let str = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getStringValue promise error is " + error); }); } catch (error) { @@ -666,7 +679,9 @@ getStringValue(resource: Resource, callback: AsyncCallback<string>): void **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.string.test').id @@ -718,15 +733,18 @@ getStringValue(resource: Resource): Promise<string> **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + import { BusinessError } from '@ohos.base'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.string.test').id }; try { - this.context.resourceManager.getStringValue(resource).then(value => { + this.context.resourceManager.getStringValue(resource).then((value: string) => { let str = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getStringValue promise error is " + error); }); } catch (error) { @@ -806,10 +824,12 @@ getStringByName(resName: string): Promise<string> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getStringByName("test").then(value => { + this.context.resourceManager.getStringByName("test").then((value: string) => { let str = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getStringByName promise error is " + error); }); } catch (error) { @@ -890,7 +910,9 @@ getStringArrayValueSync(resource: Resource): Array<string> **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.strarray.test').id @@ -902,6 +924,45 @@ getStringArrayValueSync(resource: Resource): Array<string> } ``` +### getStringArrayByNameSync10+ + +getStringArrayByNameSync(resName: string): Array<string> + +用户获取指定资源名称对应的字符串数组,使用同步方式返回字符串数组。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----- | +| resName | string | 是 | 资源名称 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ----------- | +| Array<string> | 对应资源名称的字符串数组 | + +**错误码:** + +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | + +**示例:** + ```ts + try { + this.context.resourceManager.getStringArrayByNameSync("test"); + } catch (error) { + console.error(`getStringArrayByNameSync failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + ### getStringArrayValue9+ getStringArrayValue(resId: number, callback: AsyncCallback<Array<string>>): void @@ -974,10 +1035,12 @@ getStringArrayValue(resId: number): Promise<Array<string>> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id).then(value => { + this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id).then((value: Array) => { let strArray = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getStringArrayValue promise error is " + error); }); } catch (error) { @@ -1014,7 +1077,9 @@ getStringArrayValue(resource: Resource, callback: AsyncCallback<Array<stri **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.strarray.test').id @@ -1066,15 +1131,18 @@ getStringArrayValue(resource: Resource): Promise<Array<string>> **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + import { BusinessError } from '@ohos.base'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.strarray.test').id }; try { - this.context.resourceManager.getStringArrayValue(resource).then(value => { + this.context.resourceManager.getStringArrayValue(resource).then((value: Array) => { let strArray = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getStringArray promise error is " + error); }); } catch (error) { @@ -1154,10 +1222,12 @@ getStringArrayByName(resName: string): Promise<Array<string>> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getStringArrayByName("test").then(value => { + this.context.resourceManager.getStringArrayByName("test").then((value: Array) => { let strArray = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getStringArrayByName promise error is " + error); }); } catch (error) { @@ -1240,7 +1310,9 @@ getPluralStringValueSync(resource: Resource, num: number): string **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.plural.test').id @@ -1252,6 +1324,46 @@ getPluralStringValueSync(resource: Resource, num: number): string } ``` +### getPluralStringByNameSync10+ + +getPluralStringByNameSync(resName: string, num: number): string + +根据指定数量获取指定资源名称表示的单复数字符串,使用同步方式返回字符串。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----- | +| resName | string | 是 | 资源名称 | +| num | number | 是 | 数量值 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ----------- | +| string | 根据指定数量获取指定资源名称表示的单复数字符串 | + +**错误码:** + +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | + +**示例:** + ```ts + try { + this.context.resourceManager.getPluralStringByNameSync("test", 1); + } catch (error) { + console.error(`getPluralStringByNameSync failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + ### getPluralStringValue9+ getPluralStringValue(resId: number, num: number, callback: AsyncCallback<string>): void @@ -1326,10 +1438,12 @@ getPluralStringValue(resId: number, num: number): Promise<string> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1).then(value => { + this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1).then((value: string) => { let str = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getPluralStringValue promise error is " + error); }); } catch (error) { @@ -1367,7 +1481,9 @@ getPluralStringValue(resource: Resource, num: number, callback: AsyncCallback< **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.plural.test').id @@ -1420,15 +1536,18 @@ getPluralStringValue(resource: Resource, num: number): Promise<string> **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + import { BusinessError } from '@ohos.base'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.plural.test').id }; try { - this.context.resourceManager.getPluralStringValue(resource, 1).then(value => { + this.context.resourceManager.getPluralStringValue(resource, 1).then((value: string) => { let str = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getPluralStringValue promise error is " + error); }); } catch (error) { @@ -1510,10 +1629,12 @@ getPluralStringByName(resName: string, num: number): Promise<string> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getPluralStringByName("test", 1).then(value => { + this.context.resourceManager.getPluralStringByName("test", 1).then((value: string) => { let str = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getPluralStringByName promise error is " + error); }); } catch (error) { @@ -1600,7 +1721,9 @@ getMediaContentSync(resource: Resource, density?: number): Uint8Array **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.media.test').id @@ -1618,6 +1741,51 @@ getMediaContentSync(resource: Resource, density?: number): Uint8Array } ``` +### getMediaByNameSync10+ + +getMediaByNameSync(resName: string, density?: number): Uint8Array + +用户获取指定资源名称对应的默认或指定的屏幕密度媒体文件内容,使用同步方式返回字节数组。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----- | +| resName | string | 是 | 资源名称 | +| [density](#screendensity) | number | 否 | 资源获取需要的屏幕密度,0或缺省表示默认屏幕密度 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ----------- | +| Uint8Array | 对应资源名称的媒体文件内容 | + +**错误码:** + +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | + +**示例:** + ```ts + try { + this.context.resourceManager.getMediaByNameSync("test"); // 默认屏幕密度 + } catch (error) { + console.error(`getMediaByNameSync failed, error code: ${error.code}, message: ${error.message}.`); + } + + try { + this.context.resourceManager.getMediaByNameSync("test", 120); // 指定屏幕密度 + } catch (error) { + console.error(`getMediaByNameSync failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + ### getMediaContent9+ getMediaContent(resId: number, callback: AsyncCallback<Uint8Array>): void @@ -1728,10 +1896,12 @@ getMediaContent(resId: number): Promise<Uint8Array> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getMediaContent($r('app.media.test').id).then(value => { + this.context.resourceManager.getMediaContent($r('app.media.test').id).then((value: Uint8Array) => { let media = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getMediaContent promise error is " + error); }); } catch (error) { @@ -1771,10 +1941,12 @@ getMediaContent(resId: number, density: number): Promise<Uint8Array> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getMediaContent($r('app.media.test').id, 120).then(value => { + this.context.resourceManager.getMediaContent($r('app.media.test').id, 120).then((value: Uint8Array) => { let media = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); }); } catch (error) { @@ -1810,7 +1982,9 @@ getMediaContent(resource: Resource, callback: AsyncCallback<Uint8Array>): **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.media.test').id @@ -1857,7 +2031,9 @@ getMediaContent(resource: Resource, density: number, callback: AsyncCallback< **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.media.test').id @@ -1908,15 +2084,18 @@ getMediaContent(resource: Resource): Promise<Uint8Array> **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + import { BusinessError } from '@ohos.base'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.media.test').id }; try { - this.context.resourceManager.getMediaContent(resource).then(value => { + this.context.resourceManager.getMediaContent(resource).then((value: Uint8Array) => { let media = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getMediaContent promise error is " + error); }); } catch (error) { @@ -1958,15 +2137,18 @@ getMediaContent(resource: Resource, density: number): Promise<Uint8Array> **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + import { BusinessError } from '@ohos.base'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.media.test').id }; try { - this.context.resourceManager.getMediaContent(resource, 120).then(value => { + this.context.resourceManager.getMediaContent(resource, 120).then((value: Uint8Array) => { let media = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); }); } catch (error) { @@ -2084,10 +2266,12 @@ getMediaByName(resName: string): Promise<Uint8Array> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getMediaByName("test").then(value => { + this.context.resourceManager.getMediaByName("test").then((value: Uint8Array) => { let media = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getMediaByName promise error is " + error); }); } catch (error) { @@ -2127,10 +2311,12 @@ getMediaByName(resName: string, density: number): Promise<Uint8Array> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getMediaByName("test", 120).then(value => { + this.context.resourceManager.getMediaByName("test", 120).then((value: Uint8Array) => { let media = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`); }); } catch (error) { @@ -2217,7 +2403,9 @@ getMediaContentBase64Sync(resource: Resource, density?: number): string **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.media.test').id @@ -2235,6 +2423,51 @@ getMediaContentBase64Sync(resource: Resource, density?: number): string } ``` +### getMediaBase64ByNameSync10+ + +getMediaBase64ByNameSync(resName: string, density?: number): string + +用户获取指定资源名称对应的默认或指定的屏幕密度图片资源Base64编码,使用同步方式返回字符串。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----- | +| resName | string | 是 | 资源名称 | +| [density](#screendensity) | number | 否 | 资源获取需要的屏幕密度,0或缺省表示默认屏幕密度 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ----------- | +| string | 资源名称对应的图片资源Base64编码 | + +**错误码:** + +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | + +**示例:** + ```ts + try { + this.context.resourceManager.getMediaBase64ByNameSync("test"); // 默认屏幕密度 + } catch (error) { + console.error(`getMediaBase64ByNameSync failed, error code: ${error.code}, message: ${error.message}.`); + } + + try { + this.context.resourceManager.getMediaBase64ByNameSync("test", 120); // 指定屏幕密度 + } catch (error) { + console.error(`getMediaBase64ByNameSync failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + ### getMediaContentBase649+ getMediaContentBase64(resId: number, callback: AsyncCallback<string>): void @@ -2345,10 +2578,12 @@ getMediaContentBase64(resId: number): Promise<string> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getMediaContentBase64($r('app.media.test').id).then(value => { + this.context.resourceManager.getMediaContentBase64($r('app.media.test').id).then((value: string) => { let media = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getMediaContentBase64 promise error is " + error); }); } catch (error) { @@ -2388,10 +2623,12 @@ getMediaContentBase64(resId: number, density: number): Promise<string> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120).then(value => { + this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120).then((value: string) => { let media = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); }); } catch (error) { @@ -2427,7 +2664,9 @@ getMediaContentBase64(resource: Resource, callback: AsyncCallback<string>) **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.media.test').id @@ -2474,7 +2713,9 @@ getMediaContentBase64(resource: Resource, density: number, callback: AsyncCallba **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.media.test').id @@ -2525,15 +2766,18 @@ getMediaContentBase64(resource: Resource): Promise<string> **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + import { BusinessError } from '@ohos.base'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.media.test').id }; try { - this.context.resourceManager.getMediaContentBase64(resource).then(value => { + this.context.resourceManager.getMediaContentBase64(resource).then((value: string) => { let media = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getMediaContentBase64 promise error is " + error); }); } catch (error) { @@ -2575,15 +2819,18 @@ getMediaContentBase64(resource: Resource, density: number): Promise<string> **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + import { BusinessError } from '@ohos.base'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.media.test').id }; try { - this.context.resourceManager.getMediaContentBase64(resource, 120).then(value => { + this.context.resourceManager.getMediaContentBase64(resource, 120).then((value: string) => { let media = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); }); } catch (error) { @@ -2701,10 +2948,12 @@ getMediaBase64ByName(resName: string): Promise<string> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getMediaBase64ByName("test").then(value => { + this.context.resourceManager.getMediaBase64ByName("test").then((value: string) => { let media = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getMediaBase64ByName promise error is " + error); }); } catch (error) { @@ -2744,10 +2993,12 @@ getMediaBase64ByName(resName: string, density: number): Promise<string> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getMediaBase64ByName("test", 120).then(value => { + this.context.resourceManager.getMediaBase64ByName("test", 120).then((value: string) => { let media = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); }); } catch (error) { @@ -2833,7 +3084,9 @@ getDrawableDescriptor(resource: Resource, density?: number): DrawableDescriptor; **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.media.icon').id @@ -2966,7 +3219,9 @@ getBoolean(resource: Resource): boolean **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.boolean.boolean_test').id @@ -3096,7 +3351,9 @@ getNumber(resource: Resource): number **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.integer.integer_test').id @@ -3226,7 +3483,9 @@ getColorSync(resource: Resource): number **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.color.test').id @@ -3349,10 +3608,12 @@ getColor(resId: number): Promise<number> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getColor($r('app.color.test').id).then(value => { + this.context.resourceManager.getColor($r('app.color.test').id).then((value: number) => { let str = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getColor promise error is " + error); }); } catch (error) { @@ -3389,7 +3650,9 @@ getColor(resource: Resource, callback: AsyncCallback<number>): void; **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.color.test').id @@ -3441,15 +3704,18 @@ getColor(resource: Resource): Promise<number>; **示例:** ```ts - let resource = { + import resourceManager from '@ohos.resourceManager'; + import { BusinessError } from '@ohos.base'; + + let resource: resourceManager.Resource = { bundleName: "com.example.myapplication", moduleName: "entry", id: $r('app.color.test').id }; try { - this.context.resourceManager.getColor(resource).then(value => { + this.context.resourceManager.getColor(resource).then((value: number) => { let str = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getColor promise error is " + error); }); } catch (error) { @@ -3529,10 +3795,12 @@ getColorByName(resName: string): Promise<number> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getColorByName("test").then(value => { + this.context.resourceManager.getColorByName("test").then((value: number) => { let string = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getColorByName promise error is " + error); }); } catch (error) { @@ -3603,7 +3871,7 @@ getRawFileContent(path: string, callback: AsyncCallback<Uint8Array>): void **示例:** ```ts try { - this.context.resourceManager.getRawFileContent("test.xml", (error, value) => { + this.context.resourceManager.getRawFileContent("test.txt", (error, value) => { if (error != null) { console.log("error is " + error); } else { @@ -3645,10 +3913,12 @@ getRawFileContent(path: string): Promise<Uint8Array> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getRawFileContent("test.xml").then(value => { + this.context.resourceManager.getRawFileContent("test.txt").then((value: Uint8Array) => { let rawFile = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getRawFileContent promise error is " + error); }); } catch (error) { @@ -3761,10 +4031,12 @@ getRawFileList(path: string): Promise<Array\> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { // 传入""表示获取rawfile根目录下的文件列表 - this.context.resourceManager.getRawFileList("").then(value => { + this.context.resourceManager.getRawFileList("").then((value: Array) => { let rawFile = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.error(`promise getRawFileList failed, error code: ${error.code}, message: ${error.message}.`); }); } catch (error) { @@ -3835,7 +4107,7 @@ getRawFd(path: string, callback: AsyncCallback<RawFileDescriptor>): void **示例:** ```ts try { - this.context.resourceManager.getRawFd("test.xml", (error, value) => { + this.context.resourceManager.getRawFd("test.txt", (error, value) => { if (error != null) { console.log(`callback getRawFd failed error code: ${error.code}, message: ${error.message}.`); } else { @@ -3879,12 +4151,14 @@ getRawFd(path: string): Promise<RawFileDescriptor> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getRawFd("test.xml").then(value => { + this.context.resourceManager.getRawFd("test.txt").then((value: resourceManager.RawFileDescriptor) => { let fd = value.fd; let offset = value.offset; let length = value.length; - }).catch(error => { + }).catch((error: BusinessError) => { console.log(`promise getRawFd error error code: ${error.code}, message: ${error.message}.`); }); } catch (error) { @@ -3949,7 +4223,7 @@ closeRawFd(path: string, callback: AsyncCallback<void>): void **示例:** ```ts try { - this.context.resourceManager.closeRawFd("test.xml", (error, value) => { + this.context.resourceManager.closeRawFd("test.txt", (error, value) => { if (error != null) { console.log("error is " + error); } @@ -3990,16 +4264,37 @@ closeRawFd(path: string): Promise<void> **示例:** ```ts try { - this.context.resourceManager.closeRawFd("test.xml").then(value => { - let result = value; - }).catch(error => { - console.log("closeRawFd promise error is " + error); - }); + this.context.resourceManager.closeRawFd("test.txt"); } catch (error) { console.error(`promise closeRawFd failed, error code: ${error.code}, message: ${error.message}.`); } ``` +### getConfigurationSync + +getConfigurationSync(): Configuration + +用户获取设备的Configuration,使用同步形式返回Configuration对象。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**返回值:** + +| 类型 | 说明 | +| ---------------------------------------- | ---------------- | +| Promise<[Configuration](#configuration)> | 设备的Configuration | + +**示例:** + ```ts + try { + let value = this.context.resourceManager.getConfigurationSync(); + let direction = value.direction; + let locale = value.locale; + } catch (error) { + console.error("getConfigurationSync error is " + error); + } + ``` + ### getConfiguration getConfiguration(callback: AsyncCallback<Configuration>): void @@ -4046,11 +4341,13 @@ getConfiguration(): Promise<Configuration> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getConfiguration().then(value => { + this.context.resourceManager.getConfiguration().then((value: resourceManager.Configuration) => { let direction = value.direction; let locale = value.locale; - }).catch(error => { + }).catch((error: BusinessError) => { console.error("getConfiguration promise error is " + error); }); } catch (error) { @@ -4058,6 +4355,31 @@ getConfiguration(): Promise<Configuration> } ``` +### getDeviceCapabilitySync + +getDeviceCapabilitySync(): DeviceCapability + +用户获取设备的DeviceCapability,使用同步形式返回DeviceCapability对象。 + +**系统能力**:SystemCapability.Global.ResourceManager + +**返回值:** + +| 类型 | 说明 | +| ---------------------------------------- | ------------------- | +| DeviceCapability | 设备的DeviceCapability | + +**示例:** + ```ts + try { + let value = this.context.resourceManager.getDeviceCapabilitySync(); + let screenDensity = value.screenDensity; + let deviceType = value.deviceType; + } catch (error) { + console.error("getDeviceCapabilitySync error is " + error); + } + ``` + ### getDeviceCapability getDeviceCapability(callback: AsyncCallback<DeviceCapability>): void @@ -4104,11 +4426,13 @@ getDeviceCapability(): Promise<DeviceCapability> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { - this.context.resourceManager.getDeviceCapability().then(value => { + this.context.resourceManager.getDeviceCapability().then((value: resourceManager.DeviceCapability) => { let screenDensity = value.screenDensity; let deviceType = value.deviceType; - }).catch(error => { + }).catch((error: BusinessError) => { console.error("getDeviceCapability promise error is " + error); }); } catch (error) { @@ -4191,7 +4515,7 @@ removeResource(path: string) : void; ```ts let path = getContext().bundleCodeDir + "/library1-default-signed.hsp"; try { - this.resmgr.removeResource(path); + this.context.resourceManager.removeResource(path); } catch (error) { console.error(`removeResource failed, error code: ${error.code}, message: ${error.message}.`); } @@ -4252,10 +4576,12 @@ getString(resId: number): Promise<string> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + resourceManager.getResourceManager((error, mgr) => { - mgr.getString($r('app.string.test').id).then(value => { + mgr.getString($r('app.string.test').id).then((value: string) => { let str = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getstring promise error is " + error); }); }); @@ -4317,10 +4643,12 @@ getStringArray(resId: number): Promise<Array<string>> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + resourceManager.getResourceManager((error, mgr) => { - mgr.getStringArray($r('app.strarray.test').id).then(value => { + mgr.getStringArray($r('app.strarray.test').id).then((value: Array) => { let strArray = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getStringArray promise error is " + error); }); }); @@ -4382,10 +4710,12 @@ getMedia(resId: number): Promise<Uint8Array> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + resourceManager.getResourceManager((error, mgr) => { - mgr.getMedia($r('app.media.test').id).then(value => { + mgr.getMedia($r('app.media.test').id).then((value: Uint8Array) => { let media = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getMedia promise error is " + error); }); }); @@ -4447,10 +4777,12 @@ getMediaBase64(resId: number): Promise<string> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + resourceManager.getResourceManager((error, mgr) => { - mgr.getMediaBase64($r('app.media.test').id).then(value => { + mgr.getMediaBase64($r('app.media.test').id).then((value: string) => { let media = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getMediaBase64 promise error is " + error); }); }); @@ -4482,10 +4814,12 @@ getPluralString(resId: number, num: number): Promise<string> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + resourceManager.getResourceManager((error, mgr) => { - mgr.getPluralString($r("app.plural.test").id, 1).then(value => { + mgr.getPluralString($r("app.plural.test").id, 1).then((value: string) => { let str = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getPluralString promise error is " + error); }); }); @@ -4544,7 +4878,7 @@ getRawFile(path: string, callback: AsyncCallback<Uint8Array>): void **示例:** ```ts resourceManager.getResourceManager((error, mgr) => { - mgr.getRawFile("test.xml", (error, value) => { + mgr.getRawFile("test.txt", (error, value) => { if (error != null) { console.log("error is " + error); } else { @@ -4579,10 +4913,12 @@ getRawFile(path: string): Promise<Uint8Array> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + resourceManager.getResourceManager((error, mgr) => { - mgr.getRawFile("test.xml").then(value => { + mgr.getRawFile("test.txt").then((value: Uint8Array) => { let rawFile = value; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getRawFile promise error is " + error); }); }); @@ -4609,7 +4945,7 @@ getRawFileDescriptor(path: string, callback: AsyncCallback<RawFileDescriptor& **示例:** ```ts resourceManager.getResourceManager((error, mgr) => { - mgr.getRawFileDescriptor("test.xml", (error, value) => { + mgr.getRawFileDescriptor("test.txt", (error, value) => { if (error != null) { console.log("error is " + error); } else { @@ -4645,12 +4981,14 @@ getRawFileDescriptor(path: string): Promise<RawFileDescriptor> **示例:** ```ts + import { BusinessError } from '@ohos.base'; + resourceManager.getResourceManager((error, mgr) => { - mgr.getRawFileDescriptor("test.xml").then(value => { + mgr.getRawFileDescriptor("test.txt").then((value: resourceManager.RawFileDescriptor) => { let fd = value.fd; let offset = value.offset; let length = value.length; - }).catch(error => { + }).catch((error: BusinessError) => { console.log("getRawFileDescriptor promise error is " + error); }); }); @@ -4676,7 +5014,7 @@ closeRawFileDescriptor(path: string, callback: AsyncCallback<void>): void **示例:** ```ts resourceManager.getResourceManager((error, mgr) => { - mgr.closeRawFileDescriptor("test.xml", (error, value) => { + mgr.closeRawFileDescriptor("test.txt", (error, value) => { if (error != null) { console.log("error is " + error); } @@ -4709,10 +5047,6 @@ closeRawFileDescriptor(path: string): Promise<void> **示例:** ```ts resourceManager.getResourceManager((error, mgr) => { - mgr.closeRawFileDescriptor("test.xml").then(value => { - let result = value; - }).catch(error => { - console.log("closeRawFileDescriptor promise error is " + error); - }); + mgr.closeRawFileDescriptor("test.txt"); }); ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md index 98c1588316898f7417357db1f7bd8fdfb9c8c064..ffca94bfffb0ef7491ca31bc465046d51a3bdcdf 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md +++ b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @@ -305,6 +305,8 @@ queryAppGroupSync(bundleName: string): number 查询指定bundleName应用的优先级分组。 +**需要权限**:ohos.permission.BUNDLE_ACTIVE_INFO + **系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.AppGroup **系统API**:此接口为系统接口。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md index 86a03f7a1d4c509967643c07b52028ead83d55de..70a2c5ef5456631a403c756e9a2fdfae38194897 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md +++ b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @@ -433,11 +433,11 @@ isLastWorkTimeOut(workId: number): Promise\ | batteryStatus | [BatteryStatus](#batterystatus) | 否 | 电池状态。 | | storageRequest | [StorageRequest](#storagerequest) | 否 | 存储状态。 | | isRepeat | boolean | 否 | 是否循环任务。
- true表示循环任务,false表示非循环任务。 | -| repeatCycleTime | number | 否 | 循环间隔。 | +| repeatCycleTime | number | 否 | 循环间隔,单位为毫秒。 | | repeatCount | number | 否 | 循环次数。 | | isPersisted | boolean | 否 | 是否持久化保存工作。
- true表示持久化保存工作。false表示非持久化保存工作。| | isDeepIdle | boolean | 否 | 是否要求设备进入空闲状态。
- true表示需要,false表示不需要。 | -| idleWaitTime | number | 否 | 空闲等待时间。 | +| idleWaitTime | number | 否 | 空闲等待时间,单位为毫秒。 | | parameters | [key: string]: number \| string \| boolean | 否 | 携带参数信息。 | ## NetworkType diff --git a/zh-cn/application-dev/reference/apis/js-apis-router.md b/zh-cn/application-dev/reference/apis/js-apis-router.md index 4a997321335af457371122ecd71c354f6f9e3772..13e86fb23fd74b3646617b5202d74f900ee5b1f8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-router.md +++ b/zh-cn/application-dev/reference/apis/js-apis-router.md @@ -1,5 +1,7 @@ # @ohos.router (页面路由) + + 本模块提供通过不同的url访问不同的页面,包括跳转到应用内的指定页面、用应用内的某个页面替换当前页面、返回上一页面或指定的页面等。 > **说明** @@ -11,6 +13,8 @@ > - 本模块功能依赖UI的执行上下文,不可在UI上下文不明确的地方使用,参见[UIContext](./js-apis-arkui-UIContext.md#uicontext)说明。 > > - 从API version 10开始,可以通过使用[UIContext](./js-apis-arkui-UIContext.md#uicontext)中的[getRouter](./js-apis-arkui-UIContext.md#getrouter)方法获取当前UI上下文关联的[Router](./js-apis-arkui-UIContext.md#router)对象。 +> +> - 为了实现更好的转场效果,推荐使用[Navigation组件](../../ui/arkts-navigation-navigation.md)和[模态转场](../../ui/arkts-modal-transition.md)。 ## 导入模块 diff --git a/zh-cn/application-dev/reference/apis/js-apis-secureElement.md b/zh-cn/application-dev/reference/apis/js-apis-secureElement.md index 4bc85b08dc20c539034e81a9a232ee6b3414bb47..de344fdcbc6bcb8e8a0c4cb470043bfff2461401 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-secureElement.md +++ b/zh-cn/application-dev/reference/apis/js-apis-secureElement.md @@ -261,7 +261,7 @@ isSecureElementPresent(): boolean | 错误码ID | 错误信息 | | -------- | -------------------------------- | -| 3300101 | Illegal service state exception. | +| 3300101 | IllegalStateError, service state exception. | **示例:** @@ -302,8 +302,8 @@ try { | 错误码ID | 错误信息 | | -------- | -------------------------------- | -| 3300101 | Illegal service state exception. | -| 3300104 | Secure element IO exception. | +| 3300101 | IllegalStateError, service state exception. | +| 3300104 | IOError, there is a communication problem to the reader or the SE. | **示例:** @@ -340,7 +340,7 @@ try { | 错误码ID | 错误信息 | | -------- | -------------------------------- | -| 3300101 | Illegal service state exception. | +| 3300101 | IllegalStateError, service state exception. | **示例:** @@ -413,7 +413,7 @@ getATR(): number[] | 错误码ID | 错误信息 | | -------- | -------------------------------- | -| 3300101 | Illegal service state exception. | +| 3300101 | IllegalStateError, service state exception. | **示例:** @@ -456,7 +456,7 @@ close(): void | 错误码ID | 错误信息 | | -------- | -------------------------------- | -| 3300101 | Illegal service state exception. | +| 3300101 | IllegalStateError, service state exception. | **示例:** @@ -526,7 +526,7 @@ closeChannels(): void | 错误码ID | 错误信息 | | -------- | -------------------------------- | -| 3300101 | Illegal service state exception. | +| 3300101 | IllegalStateError, service state exception. | **示例:** @@ -570,10 +570,10 @@ openBasicChannel(aid: number[]): Promise\ | 错误码ID | 错误信息 | | -------- | -------------------------------- | -| 3300101 | Illegal service state exception. | -| 3300102 | No such element exception. | -| 3300103 | Illegal access rule exception. | -| 3300104 | Secure element IO exception. | +| 3300101 | IllegalStateError, service state exception. | +| 3300102 | NoSuchElementError, the AID on the SE is not available or cannot be selected. | +| 3300103 | SecurityError, the calling application cannot be granted access to this AID or the default applet on this session. | +| 3300104 | IOError, there is a communication problem to the reader or the SE. | **示例:** @@ -619,10 +619,10 @@ try { | 错误码ID | 错误信息 | | -------- | -------------------------------- | -| 3300101 | Illegal service state exception. | -| 3300102 | No such element exception. | -| 3300103 | Illegal access rule exception. | -| 3300104 | Secure element IO exception. | +| 3300101 | IllegalStateError, service state exception. | +| 3300102 | NoSuchElementError, the AID on the SE is not available or cannot be selected. | +| 3300103 | SecurityError, the calling application cannot be granted access to this AID or the default applet on this session. | +| 3300104 | IOError, there is a communication problem to the reader or the SE. | **示例:** @@ -675,10 +675,10 @@ openBasicChannel(aid: number[], p2: number): Promise\ | 错误码ID | 错误信息 | | -------- | -------------------------------- | -| 3300101 | Illegal service state exception. | -| 3300102 | No such element exception. | -| 3300103 | Illegal access rule exception. | -| 3300104 | Secure element IO exception. | +| 3300101 | IllegalStateError, service state exception. | +| 3300102 | NoSuchElementError, the AID on the SE is not available or cannot be selected. | +| 3300103 | SecurityError, the calling application cannot be granted access to this AID or the default applet on this session. | +| 3300104 | IOError, there is a communication problem to the reader or the SE. | **示例:** @@ -726,10 +726,10 @@ openBasicChannel(aid: number[], p2:number, callback: AsyncCallback\): v | 错误码ID | 错误信息 | | -------- | -------------------------------- | -| 3300101 | Illegal service state exception. | -| 3300102 | No such element exception. | -| 3300103 | Illegal access rule exception. | -| 3300104 | Secure element IO exception. | +| 3300101 | IllegalStateError, service state exception. | +| 3300102 | NoSuchElementError, the AID on the SE is not available or cannot be selected. | +| 3300103 | SecurityError, the calling application cannot be granted access to this AID or the default applet on this session. | +| 3300104 | IOError, there is a communication problem to the reader or the SE. | **示例:** @@ -782,10 +782,10 @@ openLogicalChannel(aid: number[]): Promise\ | 错误码ID | 错误信息 | | -------- | -------------------------------- | -| 3300101 | Illegal service state exception. | -| 3300102 | No such element exception. | -| 3300103 | Illegal access rule exception. | -| 3300104 | Secure element IO exception. | +| 3300101 | IllegalStateError, service state exception. | +| 3300102 | NoSuchElementError, the AID on the SE is not available or cannot be selected. | +| 3300103 | SecurityError, the calling application cannot be granted access to this AID or the default applet on this session. | +| 3300104 | IOError, there is a communication problem to the reader or the SE. | **示例:** @@ -831,10 +831,10 @@ try { | 错误码ID | 错误信息 | | -------- | -------------------------------- | -| 3300101 | Illegal service state exception. | -| 3300102 | No such element exception. | -| 3300103 | Illegal access rule exception. | -| 3300104 | Secure element IO exception. | +| 3300101 | IllegalStateError, service state exception. | +| 3300102 | NoSuchElementError, the AID on the SE is not available or cannot be selected. | +| 3300103 | SecurityError, the calling application cannot be granted access to this AID or the default applet on this session. | +| 3300104 | IOError, there is a communication problem to the reader or the SE. | **示例:** @@ -887,10 +887,10 @@ P2通常为0x00。设备应允许P2的任何值,并且应允许以下值: 0x | 错误码ID | 错误信息 | | -------- | -------------------------------- | -| 3300101 | Illegal service state exception. | -| 3300102 | No such element exception. | -| 3300103 | Illegal access rule exception. | -| 3300104 | Secure element IO exception. | +| 3300101 | IllegalStateError, service state exception. | +| 3300102 | NoSuchElementError, the AID on the SE is not available or cannot be selected. | +| 3300103 | SecurityError, the calling application cannot be granted access to this AID or the default applet on this session. | +| 3300104 | IOError, there is a communication problem to the reader or the SE. | **示例:** @@ -947,10 +947,10 @@ P2通常为0x00。设备应允许P2的任何值,并且应允许以下值: 0x | 错误码ID | 错误信息 | | -------- | -------------------------------- | -| 3300101 | Illegal service state exception. | -| 3300102 | No such element exception. | -| 3300103 | Illegal access rule exception. | -| 3300104 | Secure element IO exception. | +| 3300101 | IllegalStateError, service state exception. | +| 3300102 | NoSuchElementError, the AID on the SE is not available or cannot be selected. | +| 3300103 | SecurityError, the calling application cannot be granted access to this AID or the default applet on this session. | +| 3300104 | IOError, there is a communication problem to the reader or the SE. | **示例:** @@ -1176,9 +1176,9 @@ transmit(command: number[]): Promise | 错误码ID | 错误信息 | | -------- | -------------------------------- | -| 3300101 | Illegal service state exception. | -| 3300103 | Illegal access rule exception. | -| 3300104 | Secure element IO exception. | +| 3300101 | IllegalStateError, service state exception. | +| 3300103 | SecurityError, the calling application cannot be granted access to this AID or the default applet on this session. | +| 3300104 | IOError, there is a communication problem to the reader or the SE. | **示例:** @@ -1228,9 +1228,9 @@ transmit(command: number[], callback: AsyncCallback): void | 错误码ID | 错误信息 | | -------- | -------------------------------- | -| 3300101 | Illegal service state exception. | -| 3300103 | Illegal access rule exception. | -| 3300104 | Secure element IO exception. | +| 3300101 | IllegalStateError, service state exception. | +| 3300103 | SecurityError, the calling application cannot be granted access to this AID or the default applet on this session. | +| 3300104 | IOError, there is a communication problem to the reader or the SE. | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-socket.md b/zh-cn/application-dev/reference/apis/js-apis-socket.md index 5ccd81fdc17079f3a40a044c1765b80c842ba87f..f4ff557f7a01f6121f70774c9673c7482f40814d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-socket.md +++ b/zh-cn/application-dev/reference/apis/js-apis-socket.md @@ -2515,7 +2515,7 @@ tcpServer.on('connect', function(client) { ### off('close')10+ -off(type: 'close', callback?: Callback): void +off(type: 'close', callback?: Callback\): void 取消订阅TCPSocketConnection的关闭事件。使用callback方式作为异步方法。 @@ -5708,7 +5708,7 @@ tlsServer.on('connect', function(client) { ### off('close')10+ -off(type: 'close', callback?: Callback): void +off(type: 'close', callback?: Callback\): void 取消订阅TLSSocketConnection的关闭事件。使用callback方式作为异步方法。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-uiappearance.md b/zh-cn/application-dev/reference/apis/js-apis-uiappearance.md index 141138a52de55578e3d26b38943f1b7dcf7f2241..dc0e88fae89a3082b4199550b5e5e41739899710 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-uiappearance.md +++ b/zh-cn/application-dev/reference/apis/js-apis-uiappearance.md @@ -50,7 +50,7 @@ setDarkMode(mode: DarkMode, callback: AsyncCallback\): void 错误码详细介绍请参考[errcode-uiappearance](../errorcodes/errorcode-uiappearance.md)。 -| 错误码ID | 错误码信息 | +| 错误码ID | 错误信息 | | -- | -- | | 500001 | Internal error. | @@ -97,7 +97,7 @@ setDarkMode(mode: DarkMode): Promise\; 错误码详细介绍请参考[errcode-uiappearance](../errorcodes/errorcode-uiappearance.md)。 -| 错误码ID | 错误码信息 | +| 错误码ID | 错误信息 | | -- | -- | | 500001 | Internal error. | @@ -136,7 +136,7 @@ getDarkMode(): DarkMode; 错误码详细介绍请参考[errcode-uiappearance](../errorcodes/errorcode-uiappearance.md)。 -| 错误码ID | 错误码信息 | +| 错误码ID | 错误信息 | | -- | -- | | 500001 | Internal error. | diff --git a/zh-cn/application-dev/reference/apis/js-apis-update.md b/zh-cn/application-dev/reference/apis/js-apis-update.md index e2aa8974228692c77c455a1276bfa002f3b8b61c..fef8ec798258c7fff3c18a88bdd74eec589a18d8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-update.md +++ b/zh-cn/application-dev/reference/apis/js-apis-update.md @@ -1,10 +1,11 @@ # @ohos.update (升级) -升级范围:升级整个系统,包括内置的资源、预置应用;第三方的应用不在升级的范围。 +升级范围:升级整个系统,包括内置资源和预置应用,不包括三方应用。 -升级依赖:升级分为SD卡升级和在线升级两种。 +升级类型:SD卡升级、在线升级。 - SD卡升级依赖升级包和SD卡安装。 + - 在线升级依赖设备厂商部署的用于管理升级包的服务器。服务器由设备厂商部署,IP由调用者传入,请求的request接口是固定的,由设备厂商开发。 > **说明:** @@ -31,7 +32,7 @@ getOnlineUpdater(upgradeInfo: UpgradeInfo): Updater | 参数名 | 类型 | 必填 | 说明 | | ----------- | --------------------------- | ---- | ------ | -| upgradeInfo | [UpgradeInfo](#upgradeinfo) | 是 | 升级信息对象。 | +| upgradeInfo | [UpgradeInfo](#upgradeinfo) | 是 | 升级对象信息。 | **返回值:** @@ -45,30 +46,30 @@ getOnlineUpdater(upgradeInfo: UpgradeInfo): Updater | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts try { - const upgradeInfo = { - upgradeApp: "com.ohos.ota.updateclient", - businessType: { - vendor: update.BusinessVendor.PUBLIC, - subType: update.BusinessSubType.FIRMWARE + const upgradeInfo: update.UpgradeInfo = { + upgradeApp: "com.ohos.ota.updateclient", + businessType: { + vendor: update.BusinessVendor.PUBLIC, + subType: update.BusinessSubType.FIRMWARE + } + }; + let updater = update.getOnlineUpdater(upgradeInfo); + } catch(error) { + console.error(`Fail to get updater error: ${error}`); } - }; - let updater = update.getOnlineUpdater(upgradeInfo); -} catch(error) { - console.error(`Fail to get updater error: ${error}`); -} ``` ## update.getRestorer getRestorer(): Restorer -获取恢复出厂对象。 +获取恢复出厂设置对象。 **系统能力**:SystemCapability.Update.UpdateService @@ -85,7 +86,7 @@ getRestorer(): Restorer | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -117,7 +118,7 @@ getLocalUpdater(): LocalUpdater | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -139,7 +140,7 @@ checkNewVersion(callback: AsyncCallback\): void **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -153,14 +154,14 @@ checkNewVersion(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -updater.checkNewVersion((err, result) => { - console.log(`checkNewVersion isExistNewVersion ${result?.isExistNewVersion}`); -}); +updater.checkNewVersion((err: BusinessError, result: update.CheckResult) => { + console.log(`checkNewVersion isExistNewVersion ${result?.isExistNewVersion}`); + }); ``` ### checkNewVersion @@ -171,7 +172,7 @@ checkNewVersion(): Promise\ **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **返回值:** @@ -185,18 +186,20 @@ checkNewVersion(): Promise\ | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -updater.checkNewVersion().then(result => { - console.log(`checkNewVersion isExistNewVersion: ${result.isExistNewVersion}`); - // 版本摘要信息 - console.log(`checkNewVersion versionDigestInfo: ${result.newVersionInfo.versionDigestInfo.versionDigest}`); -}).catch(err => { - console.log(`checkNewVersion promise error ${JSON.stringify(err)}`); -}); +updater.checkNewVersion() + .then((result: update.CheckResult) => { + console.log(`checkNewVersion isExistNewVersion: ${result.isExistNewVersion}`); + // 版本摘要信息 + console.log(`checkNewVersion versionDigestInfo: ${result.newVersionInfo.versionDigestInfo.versionDigest}`); + }) + .catch((err: BusinessError)=>{ + console.log(`checkNewVersion promise error ${JSON.stringify(err)}`); + }) ``` ### getNewVersionInfo @@ -207,7 +210,7 @@ getNewVersionInfo(callback: AsyncCallback\): void **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -221,14 +224,14 @@ getNewVersionInfo(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -updater.getNewVersionInfo((err, info) => { - console.log(`info displayVersion = ${info?.versionComponents[0].displayVersion}`); - console.log(`info innerVersion = ${info?.versionComponents[0].innerVersion}`); +updater.getNewVersionInfo((err: BusinessError, info: update.NewVersionInfo) => { + console.log(`info displayVersion = ${info?.versionComponents[0].displayVersion}`); + console.log(`info innerVersion = ${info?.versionComponents[0].innerVersion}`); }); ``` @@ -240,7 +243,7 @@ getNewVersionInfo(): Promise\ **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **返回值:** @@ -254,16 +257,16 @@ getNewVersionInfo(): Promise\ | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -updater.getNewVersionInfo().then(info => { - console.log(`info displayVersion = ${info.versionComponents[0].displayVersion}`); - console.log(`info innerVersion = ${info.versionComponents[0].innerVersion}`); -}).catch(err => { - console.log(`getNewVersionInfo promise error ${JSON.stringify(err)}`); +updater.getNewVersionInfo().then((info: update.NewVersionInfo) => { + console.log(`info displayVersion = ${info.versionComponents[0].displayVersion}`); + console.log(`info innerVersion = ${info.versionComponents[0].innerVersion}`); +}).catch((err: BusinessError) => { + console.log(`getNewVersionInfo promise error ${JSON.stringify(err)}`); }); ``` @@ -275,7 +278,7 @@ getNewVersionDescription(versionDigestInfo: VersionDigestInfo, descriptionOption **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -291,25 +294,26 @@ getNewVersionDescription(versionDigestInfo: VersionDigestInfo, descriptionOption | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts // 版本摘要信息 -const versionDigestInfo = { +const versionDigestInfo: update.VersionDigestInfo = { versionDigest: "versionDigest" // 检测结果中的版本摘要信息 }; // 描述文件选项 -const descriptionOptions = { +const descriptionOptions: update.DescriptionOptions = { format: update.DescriptionFormat.STANDARD, // 标准格式 language: "zh-cn" // 中文 }; -updater.getNewVersionDescription(versionDigestInfo, descriptionOptions, (err, info) => { - console.log(`getNewVersionDescription info ${JSON.stringify(info)}`); - console.log(`getNewVersionDescription err ${JSON.stringify(err)}`); +updater.getNewVersionDescription(versionDigestInfo, descriptionOptions).then((info: Array)=> { + console.log(`getNewVersionDescription promise info ${JSON.stringify(info)}`); +}).catch((err: BusinessError) => { + console.log(`getNewVersionDescription promise error ${JSON.stringify(err)}`); }); ``` @@ -321,7 +325,7 @@ getNewVersionDescription(versionDigestInfo: VersionDigestInfo, descriptionOption **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -342,25 +346,25 @@ getNewVersionDescription(versionDigestInfo: VersionDigestInfo, descriptionOption | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts // 版本摘要信息 -const versionDigestInfo = { +const versionDigestInfo: update.VersionDigestInfo = { versionDigest: "versionDigest" // 检测结果中的版本摘要信息 }; // 描述文件选项 -const descriptionOptions = { +const descriptionOptions: update.DescriptionOptions = { format: update.DescriptionFormat.STANDARD, // 标准格式 language: "zh-cn" // 中文 }; -updater.getNewVersionDescription(versionDigestInfo, descriptionOptions).then(info => { +updater.getNewVersionDescription(versionDigestInfo, descriptionOptions).then((info: Array)=> { console.log(`getNewVersionDescription promise info ${JSON.stringify(info)}`); -}).catch(err => { +}).catch((err: BusinessError) => { console.log(`getNewVersionDescription promise error ${JSON.stringify(err)}`); }); ``` @@ -373,7 +377,7 @@ getCurrentVersionInfo(callback: AsyncCallback\): void **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -387,12 +391,12 @@ getCurrentVersionInfo(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -updater.getCurrentVersionInfo((err, info) => { +updater.getCurrentVersionInfo((err: BusinessError, info: update.CurrentVersionInfo) => { console.log(`info osVersion = ${info?.osVersion}`); console.log(`info deviceName = ${info?.deviceName}`); console.log(`info displayVersion = ${info?.versionComponents[0].displayVersion}`); @@ -407,13 +411,13 @@ getCurrentVersionInfo(): Promise\ **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **返回值:** | 类型 | 说明 | | ---------------------------------------- | ------------------- | -| Promise\<[CurrentVersionInfo](#currentversioninfo)> | Promise对象,返回当前版本对象。 | +| Promise\<[CurrentVersionInfo](#currentversioninfo)> | Promise对象,返回当前版本信息对象。 | **错误码**: @@ -421,16 +425,16 @@ getCurrentVersionInfo(): Promise\ | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -updater.getCurrentVersionInfo().then(info => { +updater.getCurrentVersionInfo().then((info: update.CurrentVersionInfo) => { console.log(`info osVersion = ${info.osVersion}`); console.log(`info deviceName = ${info.deviceName}`); console.log(`info displayVersion = ${info.versionComponents[0].displayVersion}`); -}).catch(err => { +}).catch((err: BusinessError) => { console.log(`getCurrentVersionInfo promise error ${JSON.stringify(err)}`); }); ``` @@ -443,7 +447,7 @@ getCurrentVersionDescription(descriptionOptions: DescriptionOptions, callback: A **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -458,13 +462,13 @@ getCurrentVersionDescription(descriptionOptions: DescriptionOptions, callback: A | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts // 描述文件选项 -const descriptionOptions = { +const descriptionOptions: update.DescriptionOptions = { format: update.DescriptionFormat.STANDARD, // 标准格式 language: "zh-cn" // 中文 }; @@ -483,7 +487,7 @@ getCurrentVersionDescription(descriptionOptions: DescriptionOptions): Promise\
{ +updater.getCurrentVersionDescription(descriptionOptions).then((info: Array) => { console.log(`getCurrentVersionDescription promise info ${JSON.stringify(info)}`); -}).catch(err => { +}).catch((err: BusinessError) => { console.log(`getCurrentVersionDescription promise error ${JSON.stringify(err)}`); }); ``` @@ -529,7 +532,7 @@ getTaskInfo(callback: AsyncCallback\): void **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -543,12 +546,12 @@ getTaskInfo(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -updater.getTaskInfo((err, info) => { +updater.getTaskInfo((err: BusinessError, info: update.TaskInfo) => { console.log(`getTaskInfo isexistTask= ${info?.existTask}`); }); ``` @@ -561,7 +564,7 @@ getTaskInfo(): Promise\ **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **返回值:** @@ -575,14 +578,14 @@ getTaskInfo(): Promise\ | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -updater.getTaskInfo().then(info => { +updater.getTaskInfo().then((info: update.TaskInfo) => { console.log(`getTaskInfo isexistTask= ${info.existTask}`); -}).catch(err => { +}).catch((err: BusinessError) => { console.log(`getTaskInfo promise error ${JSON.stringify(err)}`); }); ``` @@ -595,7 +598,7 @@ download(versionDigestInfo: VersionDigestInfo, downloadOptions: DownloadOptions, **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -611,22 +614,22 @@ download(versionDigestInfo: VersionDigestInfo, downloadOptions: DownloadOptions, | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts // 版本摘要信息 -const versionDigestInfo = { +const versionDigestInfo: update.VersionDigestInfo = { versionDigest: "versionDigest" // 检测结果中的版本摘要信息 }; // 下载选项 -const downloadOptions = { +const downloadOptions: update.DownloadOptions = { allowNetwork: update.NetType.CELLULAR, // 允许数据网络下载 order: update.Order.DOWNLOAD // 下载 }; -updater.download(versionDigestInfo, downloadOptions, (err) => { +updater.download(versionDigestInfo, downloadOptions, (err: BusinessError) => { console.log(`download error ${JSON.stringify(err)}`); }); ``` @@ -639,7 +642,7 @@ download(versionDigestInfo: VersionDigestInfo, downloadOptions: DownloadOptions) **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -660,24 +663,24 @@ download(versionDigestInfo: VersionDigestInfo, downloadOptions: DownloadOptions) | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts // 版本摘要信息 -const versionDigestInfo = { +const versionDigestInfo: update.VersionDigestInfo = { versionDigest: "versionDigest" // 检测结果中的版本摘要信息 }; // 下载选项 -const downloadOptions = { +const downloadOptions: update.DownloadOptions = { allowNetwork: update.NetType.CELLULAR, // 允许数据网络下载 - order: update.Order.DOWNLOAD // 下载 + order: update.Order.DOWNLOAD // 下载 }; updater.download(versionDigestInfo, downloadOptions).then(() => { console.log(`download start`); -}).catch(err => { +}).catch((err: BusinessError) => { console.log(`download error ${JSON.stringify(err)}`); }); ``` @@ -690,7 +693,7 @@ resumeDownload(versionDigestInfo: VersionDigestInfo, resumeDownloadOptions: Resu **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -706,21 +709,21 @@ resumeDownload(versionDigestInfo: VersionDigestInfo, resumeDownloadOptions: Resu | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts // 版本摘要信息 -const versionDigestInfo = { +const versionDigestInfo : update.VersionDigestInfo= { versionDigest: "versionDigest" // 检测结果中的版本摘要信息 }; // 恢复下载选项 -const resumeDownloadOptions = { +const resumeDownloadOptions : update.ResumeDownloadOptions= { allowNetwork: update.NetType.CELLULAR, // 允许数据网络下载 }; -updater.resumeDownload(versionDigestInfo, resumeDownloadOptions, (err) => { +updater.resumeDownload(versionDigestInfo, resumeDownloadOptions, (err: BusinessError) => { console.log(`resumeDownload error ${JSON.stringify(err)}`); }); ``` @@ -733,7 +736,7 @@ resumeDownload(versionDigestInfo: VersionDigestInfo, resumeDownloadOptions: Resu **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -754,23 +757,23 @@ resumeDownload(versionDigestInfo: VersionDigestInfo, resumeDownloadOptions: Resu | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts // 版本摘要信息 -const versionDigestInfo = { +const versionDigestInfo: update.VersionDigestInfo = { versionDigest: "versionDigest" // 检测结果中的版本摘要信息 }; // 恢复下载选项 -const resumeDownloadOptions = { +const resumeDownloadOptions: update.ResumeDownloadOptions = { allowNetwork: update.NetType.CELLULAR, // 允许数据网络下载 }; -updater.resumeDownload(versionDigestInfo, resumeDownloadOptions).then(value => { +updater.resumeDownload(versionDigestInfo, resumeDownloadOptions).then(() => { console.log(`resumeDownload start`); -}).catch(err => { +}).catch((err: BusinessError) => { console.log(`resumeDownload error ${JSON.stringify(err)}`); }); ``` @@ -783,7 +786,7 @@ pauseDownload(versionDigestInfo: VersionDigestInfo, pauseDownloadOptions: PauseD **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -799,21 +802,21 @@ pauseDownload(versionDigestInfo: VersionDigestInfo, pauseDownloadOptions: PauseD | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts // 版本摘要信息 -const versionDigestInfo = { +const versionDigestInfo: update.VersionDigestInfo = { versionDigest: "versionDigest" // 检测结果中的版本摘要信息 }; // 暂停下载选项 -const pauseDownloadOptions = { +const pauseDownloadOptions: update.PauseDownloadOptions = { isAllowAutoResume: true // 允许自动恢复下载 }; -updater.pauseDownload(versionDigestInfo, pauseDownloadOptions, (err) => { +updater.pauseDownload(versionDigestInfo, pauseDownloadOptions, (err: BusinessError) => { console.log(`pauseDownload error ${JSON.stringify(err)}`); }); ``` @@ -826,7 +829,7 @@ pauseDownload(versionDigestInfo: VersionDigestInfo, pauseDownloadOptions: PauseD **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -847,23 +850,23 @@ pauseDownload(versionDigestInfo: VersionDigestInfo, pauseDownloadOptions: PauseD | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts // 版本摘要信息 -const versionDigestInfo = { +const versionDigestInfo: update.VersionDigestInfo = { versionDigest: "versionDigest" // 检测结果中的版本摘要信息 }; // 暂停下载选项 -const pauseDownloadOptions = { +const pauseDownloadOptions: update.PauseDownloadOptions = { isAllowAutoResume: true // 允许自动恢复下载 }; -updater.pauseDownload(versionDigestInfo, pauseDownloadOptions).then(value => { +updater.pauseDownload(versionDigestInfo, pauseDownloadOptions).then(() => { console.log(`pauseDownload`); -}).catch(err => { +}).catch((err: BusinessError) => { console.log(`pauseDownload error ${JSON.stringify(err)}`); }); ``` @@ -876,7 +879,7 @@ upgrade(versionDigestInfo: VersionDigestInfo, upgradeOptions: UpgradeOptions, ca **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -892,21 +895,21 @@ upgrade(versionDigestInfo: VersionDigestInfo, upgradeOptions: UpgradeOptions, ca | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts // 版本摘要信息 -const versionDigestInfo = { +const versionDigestInfo: update.VersionDigestInfo = { versionDigest: "versionDigest" // 检测结果中的版本摘要信息 }; // 安装选项 -const upgradeOptions = { +const upgradeOptions: update.UpgradeOptions = { order: update.Order.INSTALL // 安装指令 }; -updater.upgrade(versionDigestInfo, upgradeOptions, (err) => { +updater.upgrade(versionDigestInfo, upgradeOptions, (err: BusinessError) => { console.log(`upgrade error ${JSON.stringify(err)}`); }); ``` @@ -919,7 +922,7 @@ upgrade(versionDigestInfo: VersionDigestInfo, upgradeOptions: UpgradeOptions): P **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -940,23 +943,23 @@ upgrade(versionDigestInfo: VersionDigestInfo, upgradeOptions: UpgradeOptions): P | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts // 版本摘要信息 -const versionDigestInfo = { +const versionDigestInfo: update.VersionDigestInfo = { versionDigest: "versionDigest" // 检测结果中的版本摘要信息 }; // 安装选项 -const upgradeOptions = { +const upgradeOptions: update.UpgradeOptions = { order: update.Order.INSTALL // 安装指令 }; updater.upgrade(versionDigestInfo, upgradeOptions).then(() => { console.log(`upgrade start`); -}).catch(err => { +}).catch((err: BusinessError) => { console.log(`upgrade error ${JSON.stringify(err)}`); }); ``` @@ -969,7 +972,7 @@ clearError(versionDigestInfo: VersionDigestInfo, clearOptions: ClearOptions, cal **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -985,21 +988,21 @@ clearError(versionDigestInfo: VersionDigestInfo, clearOptions: ClearOptions, cal | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts // 版本摘要信息 -const versionDigestInfo = { +const versionDigestInfo: update.VersionDigestInfo = { versionDigest: "versionDigest" // 检测结果中的版本摘要信息 }; // 清除选项 -const clearOptions = { +const clearOptions: update.ClearOptions = { status: update.UpgradeStatus.UPGRADE_FAIL, }; -updater.clearError(versionDigestInfo, clearOptions, (err) => { +updater.clearError(versionDigestInfo, clearOptions, (err: BusinessError) => { console.log(`clearError error ${JSON.stringify(err)}`); }); ``` @@ -1012,7 +1015,7 @@ clearError(versionDigestInfo: VersionDigestInfo, clearOptions: ClearOptions): Pr **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -1033,23 +1036,23 @@ clearError(versionDigestInfo: VersionDigestInfo, clearOptions: ClearOptions): Pr | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts // 版本摘要信息 -const versionDigestInfo = { +const versionDigestInfo: update.VersionDigestInfo = { versionDigest: "versionDigest" // 检测结果中的版本摘要信息 }; // 清除选项 -const clearOptions = { +const clearOptions: update.ClearOptions = { status: update.UpgradeStatus.UPGRADE_FAIL, }; updater.clearError(versionDigestInfo, clearOptions).then(() => { console.log(`clearError success`); -}).catch(err => { +}).catch((err: BusinessError) => { console.log(`clearError error ${JSON.stringify(err)}`); }); ``` @@ -1062,7 +1065,7 @@ getUpgradePolicy(callback: AsyncCallback\): void **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -1076,12 +1079,12 @@ getUpgradePolicy(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -updater.getUpgradePolicy((err, policy) => { +updater.getUpgradePolicy(err: BusinessError, policy: update.UpgradePolicy) => { console.log(`policy downloadStrategy = ${policy?.downloadStrategy}`); console.log(`policy autoUpgradeStrategy = ${policy?.autoUpgradeStrategy}`); }); @@ -1095,7 +1098,7 @@ getUpgradePolicy(): Promise\ **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **返回值:** @@ -1109,15 +1112,15 @@ getUpgradePolicy(): Promise\ | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -updater.getUpgradePolicy().then(policy => { +updater.getUpgradePolicy().then((policy: update.UpgradePolicy) => { console.log(`policy downloadStrategy = ${policy.downloadStrategy}`); console.log(`policy autoUpgradeStrategy = ${policy.autoUpgradeStrategy}`); -}).catch(err => { +}).catch((err: BusinessError) => { console.log(`getUpgradePolicy promise error ${JSON.stringify(err)}`); }); ``` @@ -1130,7 +1133,7 @@ setUpgradePolicy(policy: UpgradePolicy, callback: AsyncCallback\): void **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -1145,17 +1148,17 @@ setUpgradePolicy(policy: UpgradePolicy, callback: AsyncCallback\): void | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -const policy = { +const policy: update.UpgradePolicy = { downloadStrategy: false, autoUpgradeStrategy: false, - autoUpgradePeriods: [ { start: 120, end: 240 } ] // 自动升级时间段,用分钟表示 + autoUpgradePeriods: [{ start: 120, end: 240 }] // 自动升级时间段,用分钟表示 }; -updater.setUpgradePolicy(policy, (err) => { +updater.setUpgradePolicy(policy, (err: BusinessError) => { console.log(`setUpgradePolicy result: ${err}`); }); ``` @@ -1168,7 +1171,7 @@ setUpgradePolicy(policy: UpgradePolicy): Promise\ **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -1180,7 +1183,7 @@ setUpgradePolicy(policy: UpgradePolicy): Promise\ | 类型 | 说明 | | -------------- | ------------------- | -| Promise\ | Promise对象,返回设置结果对象。 | +| Promise\ | Promise对象。 无返回结果的Promise对象。| **错误码**: @@ -1188,19 +1191,19 @@ setUpgradePolicy(policy: UpgradePolicy): Promise\ | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -const policy = { +const policy: update.UpgradePolicy = { downloadStrategy: false, autoUpgradeStrategy: false, autoUpgradePeriods: [ { start: 120, end: 240 } ] // 自动升级时间段,用分钟表示 }; updater.setUpgradePolicy(policy).then(() => { console.log(`setUpgradePolicy success`); -}).catch(err => { +}).catch((err: BusinessError) => { console.log(`setUpgradePolicy promise error ${JSON.stringify(err)}`); }); ``` @@ -1213,7 +1216,7 @@ terminateUpgrade(callback: AsyncCallback\): void **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -1227,12 +1230,12 @@ terminateUpgrade(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -updater.terminateUpgrade((err) => { +updater.terminateUpgrade((err: BusinessError) => { console.log(`terminateUpgrade error ${JSON.stringify(err)}`); }); ``` @@ -1245,7 +1248,7 @@ terminateUpgrade(): Promise\ **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **返回值:** @@ -1259,14 +1262,14 @@ terminateUpgrade(): Promise\ | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts updater.terminateUpgrade().then(() => { console.log(`terminateUpgrade success`); -}).catch(err => { +}).catch((err: BusinessError) => { console.log(`terminateUpgrade error ${JSON.stringify(err)}`); }); ``` @@ -1292,17 +1295,17 @@ on(eventClassifyInfo: EventClassifyInfo, taskCallback: UpgradeTaskCallback): voi | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -const eventClassifyInfo = { +const eventClassifyInfo: update.EventClassifyInfo = { eventClassify: update.EventClassify.TASK, // 订阅升级更新事件 extraInfo: "" }; -updater.on(eventClassifyInfo, (eventInfo) => { +updater.on(eventClassifyInfo, (eventInfo: update.EventInfo) => { console.log("updater on " + JSON.stringify(eventInfo)); }); ``` @@ -1327,17 +1330,17 @@ off(eventClassifyInfo: EventClassifyInfo, taskCallback?: UpgradeTaskCallback): v | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -const eventClassifyInfo = { +const eventClassifyInfo: update.EventClassifyInfo = { eventClassify: update.EventClassify.TASK, // 订阅升级更新事件 extraInfo: "" }; -updater.off(eventClassifyInfo, (eventInfo) => { +updater.off(eventClassifyInfo, (eventInfo: update.EventInfo) => { console.log("updater off " + JSON.stringify(eventInfo)); }); ``` @@ -1352,7 +1355,7 @@ factoryReset(callback: AsyncCallback\): void **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.FACTORY_RESET,该权限为系统权限 +**需要权限**:ohos.permission.FACTORY_RESET **参数:** @@ -1366,7 +1369,7 @@ factoryReset(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** @@ -1384,7 +1387,7 @@ factoryReset(): Promise\ **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.FACTORY_RESET,该权限为系统权限 +**需要权限**:ohos.permission.FACTORY_RESET **返回值:** @@ -1398,14 +1401,14 @@ factoryReset(): Promise\ | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts restorer.factoryReset().then(() => { console.log(`factoryReset success`); -}).catch(err => { +}).catch((err: BusinessError) => { console.log(`factoryReset error ${JSON.stringify(err)}`); }); ``` @@ -1420,7 +1423,7 @@ verifyUpgradePackage(upgradeFile: UpgradeFile, certsFile: string, callback: Asyn **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -1436,12 +1439,12 @@ verifyUpgradePackage(upgradeFile: UpgradeFile, certsFile: string, callback: Asyn | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -const upgradeFile = { +const upgradeFile: update.UpgradeFile = { fileType: update.ComponentType.OTA, // OTA包 filePath: "path" // 本地升级包路径 }; @@ -1459,7 +1462,7 @@ verifyUpgradePackage(upgradeFile: UpgradeFile, certsFile: string): Promise\ { console.log(`verifyUpgradePackage success`); -}).catch(err => { +}).catch((err: BusinessError) => { console.log(`verifyUpgradePackage error ${JSON.stringify(err)}`); }); ``` @@ -1503,7 +1506,7 @@ applyNewVersion(upgradeFiles: Array<[UpgradeFile](#upgradefile)>, callback: Asyn **系统能力**:SystemCapability.Update.UpdateService -**需要权限**:ohos.permission.UPDATE_SYSTEM,该权限为系统权限 +**需要权限**:ohos.permission.UPDATE_SYSTEM **参数:** @@ -1518,12 +1521,12 @@ applyNewVersion(upgradeFiles: Array<[UpgradeFile](#upgradefile)>, callback: Asyn | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -const upgradeFiles = [{ +const upgradeFiles: Array = [{ fileType: update.ComponentType.OTA, // OTA包 filePath: "path" // 本地升级包路径 }]; @@ -1541,7 +1544,7 @@ applyNewVersion(upgradeFiles: Array<[UpgradeFile](#upgradefile)>): Promise\): Promise\ = [{ fileType: update.ComponentType.OTA, // OTA包 filePath: "path" // 本地升级包路径 }]; localUpdater.applyNewVersion(upgradeFiles).then(() => { console.log(`applyNewVersion success`); -}).catch(err => { +}).catch((err: BusinessError) => { console.log(`applyNewVersion error ${JSON.stringify(err)}`); }); ``` @@ -1591,19 +1594,19 @@ on(eventClassifyInfo: EventClassifyInfo, taskCallback: UpgradeTaskCallback): voi | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -const eventClassifyInfo = { +const eventClassifyInfo: update.EventClassifyInfo = { eventClassify: update.EventClassify.TASK, // 订阅升级更新事件 extraInfo: "" }; -function onTaskUpdate(eventInfo) { +let onTaskUpdate: update.UpgradeTaskCallback = (eventInfo: update.EventInfo) => { console.log(`on eventInfo id `, eventInfo.eventId); -} +}; localUpdater.on(eventClassifyInfo, onTaskUpdate); ``` @@ -1628,19 +1631,19 @@ off(eventClassifyInfo: EventClassifyInfo, taskCallback?: UpgradeTaskCallback): v | 错误码ID | 错误信息 | | ------- | ---------------------------------------------------- | -| 11500104 | BusinessError 11500104: IPC error. | +| 11500104 | IPC error. | **示例:** ```ts -const eventClassifyInfo = { +const eventClassifyInfo: update.EventClassifyInfo = { eventClassify: update.EventClassify.TASK, // 订阅升级更新事件 extraInfo: "" }; -function onTaskUpdate(eventInfo) { +let onTaskUpdate: update.UpgradeTaskCallback = (eventInfo: update.EventInfo) => { console.log(`on eventInfo id `, eventInfo.eventId); -} +}; localUpdater.off(eventClassifyInfo, onTaskUpdate); ``` @@ -1664,8 +1667,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate); | 名称 | 类型 | 必填 | 说明 | | ------- | ----------------------------------- | ---- | ---- | -| vendor | [BusinessVendor](#businessvendor) | 是 | 供应商。 | -| subType | [BusinessSubType](#businesssubtype) | 是 | 类型。 | +| vendor | [BusinessVendor](#businessvendor) | 是 | 供应商/厂家。 | +| subType | [BusinessSubType](#businesssubtype) | 是 | 升级类型。 | ## CheckResult @@ -1675,7 +1678,7 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate); | 名称 | 类型 | 必填 | 说明 | | ----------------- | --------------------------------- | ---- | ------ | -| isExistNewVersion | bool | 是 | 是否有新版本。 | +| isExistNewVersion | boolean | 是 | 是否有新版本。
ture表示有新版本,false表示没有新版本。| | newVersionInfo | [NewVersionInfo](#newversioninfo) | 否 | 新版本数据。 | ## NewVersionInfo @@ -1712,7 +1715,7 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate); | upgradeAction | [UpgradeAction](#upgradeaction) | 是 | 升级方式。 | | displayVersion | string | 是 | 显示版本号。 | | innerVersion | string | 是 | 版本号。 | -| size | number | 是 | 升级包大小。 | +| size | number | 是 | 升级包大小,单位为B。 | | effectiveMode | [EffectiveMode](#effectivemode) | 是 | 生效模式。 | | descriptionInfo | [DescriptionInfo](#descriptioninfo) | 是 | 版本描述文件信息。 | @@ -1790,7 +1793,7 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate); | 名称 | 类型 | 必填 | 说明 | | ----------------- | ---- | ---- | -------- | -| isAllowAutoResume | bool | 是 | 是否允许自动恢复。 | +| isAllowAutoResume | boolean | 是 | 是否允许自动恢复。
ture表示允许自动恢复,false表示不允许。 | ## UpgradeOptions @@ -1820,8 +1823,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate); | 名称 | 类型 | 必填 | 说明 | | ------------------- | --------------------------------------- | ---- | ------- | -| downloadStrategy | bool | 是 | 自动下载策略。 | -| autoUpgradeStrategy | bool | 是 | 自动升级策略。 | +| downloadStrategy | boolean | 是 | 自动下载策略。
ture表示可自动下载,false表示不可自动下载。 | +| autoUpgradeStrategy | boolean | 是 | 自动升级策略。
ture表示可自动升级,false表示不可自动升级。 | | autoUpgradePeriods | Array\<[UpgradePeriod](#upgradeperiod)> | 是 | 自动升级时间段。 | ## UpgradePeriod @@ -1843,7 +1846,7 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate); | 名称 | 类型 | 必填 | 说明 | | --------- | --------------------- | ---- | ------ | -| existTask | bool | 是 | 是否存在任务。 | +| existTask | boolean | 是 | 是否存在任务。
ture表示存在,false表示不存在。 | | taskBody | [TaskBody](#taskinfo) | 是 | 任务数据。 | ## EventInfo diff --git a/zh-cn/application-dev/reference/apis/js-apis-usbManager.md b/zh-cn/application-dev/reference/apis/js-apis-usbManager.md index 3371f909e9401656efae68098c1ebead02831e50..0e82c7c56202da3b9a0aa1b8c991f825cb9df749 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-usbManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-usbManager.md @@ -690,7 +690,7 @@ setCurrentFunctions(funcs: FunctionType): Promise\ 以下错误码的详细介绍请参见[USB错误码](../errorcodes/errorcode-usb.md)。 -| 错误码ID | 错误码信息 | +| 错误码ID | 错误信息 | | -------- | ---------------------------------------------------- | | 14400002 | Permission denied.The HDC is disabled by the system. | diff --git a/zh-cn/application-dev/reference/apis/js-apis-webSocket.md b/zh-cn/application-dev/reference/apis/js-apis-webSocket.md index 4bd5f1d6647ea88379ef5f3872f70d0fbcfe9f72..4573d345e0ac6bd2ae66a317ab1e01ace6d4faec 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-webSocket.md +++ b/zh-cn/application-dev/reference/apis/js-apis-webSocket.md @@ -538,7 +538,7 @@ ws.off('message'); ### on('close')6+ -on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): void +on(type: 'close', callback: AsyncCallback\): void 订阅WebSocket的关闭事件,使用callback方式作为异步方法。 @@ -549,7 +549,7 @@ on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------- | ---- | ------------------------------ | | type | string | 是 | 'close':WebSocket的关闭事件。 | -| callback | AsyncCallback\<{ code: number, reason: string }\> | 是 | 回调函数。
close:close错误码,reason:错误码说明 | +| callback | AsyncCallback\ | 是 | 回调函数。
close:close错误码,reason:错误码说明 | **示例:** @@ -562,7 +562,7 @@ ws.on('close', (err, value) => { ### off('close')6+ -off(type: 'close', callback?: AsyncCallback\<{ code: number, reason: string }\>): void +off(type: 'close', callback?: AsyncCallback\): void 取消订阅WebSocket的关闭事件,使用callback方式作为异步方法。 @@ -576,7 +576,7 @@ off(type: 'close', callback?: AsyncCallback\<{ code: number, reason: string }\>) | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------- | ---- | ------------------------------ | | type | string | 是 | 'close':WebSocket的关闭事件。 | -| callback | AsyncCallback\<{ code: number, reason: string }\> | 否 | 回调函数。
close:close错误码,reason:错误码说明 | +| callback | AsyncCallback\ | 否 | 回调函数。
close:close错误码,reason:错误码说明 | **示例:** @@ -655,6 +655,17 @@ ws.off('error'); | code | number | 否 | 错误码,关闭WebSocket连接时的可选参数,可根据实际情况来填。默认值为1000。 | | reason | string | 否 | 原因值,关闭WebSocket连接时的可选参数,可根据实际情况来填。默认值为空字符串("")。 | +## CloseResult10+ + +关闭WebSocket连接时,订阅close事件得到的关闭结果。 + +**系统能力**:SystemCapability.Communication.NetStack + +| 名称 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| code | number | 是 | 错误码,订阅close事件得到的关闭连接的错误码。 | +| reason | string | 是 | 原因值,订阅close事件得到的关闭连接的错误原因。 | + ## close错误码说明 发送给服务端的错误码可以自行定义,下面的列表仅供参考。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md b/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md index 63050b385cdb4e9422e80f547ec9e3c59a61ca00..e274ddc2599b46de66a41631f4bdc6791f729e34 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md @@ -1237,7 +1237,7 @@ getLinkedInfo(): Promise<WifiLinkedInfo> 获取WLAN连接信息,使用Promise异步回调。 -**需要权限:** ohos.permission.GET_WIFI_INFO +**需要权限:** ohos.permission.GET_WIFI_INFO 。 获取 macAddress 还需申请ohos.permission.GET_WIFI_LOCAL_MAC权限,无该权限时,macAddress 返回空字符串。 **系统能力:** SystemCapability.Communication.WiFi.STA @@ -1262,7 +1262,7 @@ getLinkedInfo(callback: AsyncCallback<WifiLinkedInfo>): void 获取WLAN连接信息,使用callback异步回调。 -**需要权限:** ohos.permission.GET_WIFI_INFO +**需要权限:** ohos.permission.GET_WIFI_INFO 。 获取 macAddress 还需申请ohos.permission.GET_WIFI_LOCAL_MAC权限,无该权限时,macAddress 返回空字符串。 **系统能力:** SystemCapability.Communication.WiFi.STA diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_alert.gif b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_alert.gif index 5b7357e5b8fcca94fff521c425af9024a352e9cd..a33bc5d56a5731133fb506d4be499b9aaf0b9d00 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_alert.gif and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_alert.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-menu.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-menu.md index 9a557406f3fce799027224994f74187e89dd03f7..161dc5cf8e0fd3bcb7a059a9387081541e14dce1 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-menu.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-menu.md @@ -27,6 +27,7 @@ Menu() | fontSize(deprecated) | [Length](ts-types.md#length) | 统一设置Menu中所有文本的尺寸,Length为number类型时,使用fp单位。
从API Version 10开始废弃,建议使用font代替。 | | font10+ | [Font](ts-types.md#font) | 统一设置Menu中所有文本的字体样式。 | | fontColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 统一设置Menu中所有文本的颜色。 | +| radius10+ | [Dimension](ts-types.md#dimension10) \| [BorderRadiuses](#borderradiuses9) | 设置Menu边框圆角半径。
默认值跟随主题。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-search.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-search.md index fa0e25172900125075d9bb4189998bbaf86eb341..dab546288185e08263be26859aa3b64ed8460f2f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-search.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-search.md @@ -55,7 +55,7 @@ Search(options?: { value?: string, placeholder?: ResourceStr, icon?: string, con | 参数名 | 参数类型 | 必填 | 参数描述 | | ------ | ------------------------------------------ | ---- | -------- | -| width | [Length](ts-types.md#length) | 否 | 光标尺寸。 | +| width | [Length](ts-types.md#length) | 否 | 光标尺寸,不支持百分比。 | | color | [ResourceColor](ts-types.md#resourcecolor) | 否 | 光标颜色。 | ## SearchButtonOptions10+对象说明 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md index 66c61449bc1b05ea49b9320767b1e8551194b471..3c98d9c78fdb804b094f0714d1f852b5de6ba28f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md @@ -43,14 +43,14 @@ Slider(options?: {value?: number, min?: number, max?: number, step?: number, sty | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| blockColor | [ResourceColor](ts-types.md#resourcecolor) | 设置滑块的颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。| +| blockColor | [ResourceColor](ts-types.md#resourcecolor) | 设置滑块的颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
当滑块形状设置为`SliderBlockType.DEFAULT`时,`blockColor`可设置默认圆形滑块颜色;
当滑块形状设置为`SliderBlockType.IMAGE`时,滑块无填充,设置`blockColor`不生效;
当滑块形状设置为`SliderBlockType.SHAPE`时,`blockColor`可设置自定义形状的填充颜色。 | | trackColor | [ResourceColor](ts-types.md#resourcecolor) | 设置滑轨的背景颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。| | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | 设置滑轨的已滑动部分颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | showSteps | boolean | 设置当前是否显示步长刻度值。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。| | showTips | value: boolean,
content10+?: [ResourceStr](ts-types.md#resourcestr) | value:设置滑动时是否显示气泡提示。
默认值:false
content:设置气泡提示的文本内容,默认显示当前百分比。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
当direction的值为Axis.Horizontal时,tip显示在滑块正上方。值为Axis.Vertical时,tip显示在滑块正左边。
tip的绘制区域为Slider自身节点的overlay。
Slider不设置边距或者边距比较小时,tip会被截断。| | trackThickness | [Length](ts-types.md#length) | 设置滑轨的粗细。
默认值:当参数style的值设置[SliderStyle](#sliderstyle枚举说明).OutSet 时为 4.0vp,[SliderStyle](#sliderstyle枚举说明).InSet时为20.0vp
从APIversion9开始,该接口支持在ArkTS卡片中使用。
**说明:**
设置为小于等于0的值时,按默认值显示。 | -| blockBorderColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 设置滑块描边颜色。 | -| blockBorderWidth10+ | [Length](ts-types.md#length) | 设置滑块描边粗细。 | +| blockBorderColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 设置滑块描边颜色。
**说明:**
当滑块形状设置为`SliderBlockType.DEFAULT`时,`blockBorderColor`可设置默认圆形滑块描边颜色;
当滑块形状设置为`SliderBlockType.IMAGE`时,滑块无描边,设置`blockBorderColor`不生效;
当滑块形状设置为`SliderBlockType.SHAPE`时,`blockBorderColor`可设置自定义形状中线的颜色。 | +| blockBorderWidth10+ | [Length](ts-types.md#length) | 设置滑块描边粗细。
**说明:**
当滑块形状设置为`SliderBlockType.DEFAULT`时,`blockBorderWidth`可设置默认圆形滑块描边粗细;
当滑块形状设置为`SliderBlockType.IMAGE`时,滑块无描边,设置`blockBorderWidth`不生效;
当滑块形状设置为`SliderBlockType.SHAPE`时,`blockBorderWidth`可设置自定义形状中线的粗细。 | | stepColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 设置刻度颜色。 | | trackBorderRadius10+ | [Length](ts-types.md#length) | 设置底板圆角半径。 | | blockSize10+ | [SizeOptions](ts-types.md#sizeoptions) | 设置滑块大小。 | @@ -69,7 +69,7 @@ Slider组件滑块形状参数。 ## SliderBlockType10+枚举说明 -Slier组件滑块形状枚举。 +Slider组件滑块形状枚举。 | 名称 | 描述 | | ------- | ---------------------- | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md index 29f93fa0b7de5903f7be000afd76dfc4596a0caf..5dec8ab44a7a53b340a7c164327f27bb0962f4e9 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md @@ -46,7 +46,7 @@ TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Te | caretStyle10+ | {
width: [Length](ts-types.md#length)
} | 设置光标风格。 | | caretPosition10+ | number | 设置光标位置。 | | showUnit10+ | [CustomBuilder](ts-types.md#CustomBuilder8) | 设置控件作为文本框单位。
默认无单位。 | -| showError10+ | string \| undefined | 设置错误状态下提示的错误文本或者不显示错误状态。
默认不显示错误状态。 | +| showError10+ | string \| undefined | 设置错误状态下提示的错误文本或者不显示错误状态。
默认不显示错误状态。
**说明:**
当参数类型为string并且输入内容不符合定义规范时,提示错误文本。当参数类型为undefined时,不显示错误状态。请参考[示例2](#示例2) | | showUnderline10+ | boolean | 设置是否开启下划线。
默认值:false | | passwordIcon10+ | [PasswordIcon](#passwordicon10对象说明) | 密码输入模式时,设置输入框末尾的图标。
默认为系统提供的密码图标。 | | enableKeyboardOnFocus10+ | boolean | TextInput获焦时,是否绑定输入法
默认值:true。从API version 10开始,获焦默认绑定输入法。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md index c61cc30671edef0b4733d95063e132949f0b97d9..eeb2f654179386ea7e07c2203135d88945ea1706 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md @@ -45,10 +45,12 @@ TimePicker(options?: {selected?: Date}) ## TimePickerResult对象说明 -| 名称 | 参数类型 | 描述 | -| ------ | ------ | ------- | -| hour | number | 选中时间的时。 | -| minute | number | 选中时间的分。 | +返回值为24小时制时间。 + +| 名称 | 参数类型 | 描述 | +| ------ | -------- | ----------------------------------- | +| hour | number | 选中时间的时。
取值范围:[0-23] | +| minute | number | 选中时间的分。
取值范围:[0-59] | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-custom-component-lifecycle.md b/zh-cn/application-dev/reference/arkui-ts/ts-custom-component-lifecycle.md index fe7c3260beba69efde8bca9c134d88d3e4963547..e5db57b1f4d231c8f3a37c700a03f284878d251a 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-custom-component-lifecycle.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-custom-component-lifecycle.md @@ -40,7 +40,7 @@ onPageHide?(): void ## onBackPress -onBackPress?(): void +onBackPress?(): void | boolean 当用户点击返回按钮时触发,仅\@Entry装饰的自定义组件生效。 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md index a38c7cdc716dd701b641b70f31040b456eba7134..207d2e63eaf61a56771bebd0c688b9b612349b26 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md @@ -14,7 +14,7 @@ | 名称 | 参数类型 | 参数描述 | | ---- | --------------- | -------- | -| show | [AlertDialogParamWithConfirm](#alertdialogparamwithconfirm对象说明) \| [AlertDialogParamWithButtons](#alertdialogparamwithbuttons对象说明) | 定义并显示AlertDialog组件。 | +| show | [AlertDialogParamWithConfirm](#alertdialogparamwithconfirm对象说明) \| [AlertDialogParamWithButtons](#alertdialogparamwithbuttons对象说明) \| [AlertDialogParamWithOptions](#alertdialogparamwithoptions10对象说明) | 定义并显示AlertDialog组件。 | ## AlertDialogParamWithConfirm对象说明 | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -63,6 +63,39 @@ confirm参数优先级:fontColor、backgroundColor > style > defaultFocus | gridCount | number | 否 | 弹窗容器宽度所占用栅格数。 | | maskRect10+ | [Rectangle](#rectangle10类型说明) | 否 | 弹窗遮蔽层区域,在遮蔽层区域内的事件不透传,在遮蔽层区域外的事件透传。
默认值:{ x: 0, y: 0, width: '100%', height: '100%' } | +## AlertDialogParamWithOptions10+对象说明 +| 参数名 | 参数类型 | 必填 | 参数描述 | +| --------------- | ---------------------- | ------------ | --------------------- | +| title | [ResourceStr](ts-types.md#resourcestr) | 否 | 弹窗标题。 | +| subtitle10+ | [ResourceStr](ts-types.md#resourcestr) | 否 | 弹窗子标题。 | +| message | [ResourceStr](ts-types.md#resourcestr) | 是 | 弹窗内容。 | +| autoCancel | boolean | 否 | 点击遮障层时,是否关闭弹窗。
默认值:true | +| cancel | () => void | 否 | 点击遮障层关闭dialog时的回调。 | +| alignment | [DialogAlignment](#dialogalignment枚举说明) | 否 | 弹窗在竖直方向上的对齐方式。
默认值:DialogAlignment.Default | +| offset | [Offset](ts-types.md#offset) | 否 | 弹窗相对alignment所在位置的偏移量。 | +| gridCount | number | 否 | 弹窗容器宽度所占用栅格数。 | +| maskRect10+| [Rectangle](#rectangle10类型说明) | 否 | 弹窗遮蔽层区域,在遮蔽层区域内的事件不透传,在遮蔽层区域外的事件透传。
默认值:{ x: 0, y: 0, width: '100%', height: '100%' } | +| buttons10+ | Array<[AlertDialogButtonOptions](#alertdialogbuttonoptions10对象说明)> | 否 | 弹窗容器中的多个按钮。 | +|buttonDirection10+ | [DialogButtonDirection](#dialogbuttondirection10枚举说明)| 否 | 按钮排布方向默认值为DialogButtonDirection.AUTO,建议3个以上按钮使用Auto模式(两个以上按钮会切换为纵向模式,通常能显示更多按钮),非Auto模式下,3个以上按钮可能会显示不全,超出显示范围的按钮会被截断。| + +## AlertDialogButtonOptions10+对象说明 +| 参数名 | 参数类型 | 必填 | 参数描述 | +| ------------------| ---------------------- | ------------ | --------------------- | +| enabled | boolean | 否 | 点击button是否响应,默认值true。 | +| defaultFocus | boolean | 否 | 设置button是否是默认焦点,默认值false。 | +| style | [DialogButtonStyle](#dialogbuttonstyle10枚举说明) | 否 | 设置button的风格样式,默认值DialogButtonStyle.DEFAULT。 | +| value | [ResourceStr](ts-types.md#resourcestr) | 是 | 按钮的文本内容,若值为null,则该按钮不显示。 | +| fontColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 按钮的文本颜色。 | +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 按钮背景颜色。 | +| action | () => void | 是 | 按钮选中时的回调。 | + +## DialogButtonDirection10+枚举说明 +| 名称 | 描述 | +| -------------------------- | --------- | +| AUTO | 两个及以下按钮水平排布,两个以上为竖直排布。 | +| HORIZONTAL | 按钮水平布局。 | +| VERTICAL | 按钮竖直布局。 | + confirm参数优先级:fontColor、backgroundColor > style > defaultFocus | backgroundColor | fontColor | style | defaultFocus | 效果 | @@ -186,6 +219,47 @@ struct AlertDialogExample { } ) }).backgroundColor(0x317aff) + Button('three button dialog') + .onClick(() => { + AlertDialog.show( + { + title: 'title', + subtitle: 'subtitle', + message: 'text', + autoCancel: true, + alignment: DialogAlignment.Bottom, + gridCount: 4, + offset: { dx: 0, dy: -20 }, + buttonDirection: DialogButtonDirection.HORIZONTAL, + buttons: [ + { + value: '按钮', + action: () => { + console.info('Callback when button1 is clicked') + } + }, + { + value: '按钮', + action: () => { + console.info('Callback when button2 is clicked') + } + }, + { + value: '按钮', + enabled: true, + defaultFocus: true, + style: DialogButtonStyle.HIGHLIGHT, + action: () => { + console.info('Callback when button3 is clicked') + } + }, + ], + cancel: () => { + console.info('Closed callbacks') + } + } + ) + }).backgroundColor(0x317aff) }.width('100%').margin({ top: 5 }) } } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md index 75d474a0ab1bc900758e22f154976ff1dff1316c..829d429c951ff2a2440d5bbfb53629999212e63f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md @@ -30,7 +30,7 @@ CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, aut | closeAniamtion10+ | [AnimateParam](ts-explicit-animation.md#animateparam对象说明) | 否 | 自定义设置弹窗关闭的动画效果相关参数。
**说明**:
iterations默认值为1,默认播放一次,设置为其他数值时按默认值处理。
playMode控制动画播放模式,默认值为PlayMode.Normal,设置为其他数值时按照默认值处理。 | | showInSubWindow10+ | boolean | 否 | 某弹框需要显示在主窗口之外时,是否在子窗口显示此弹窗。
默认值:false,在子窗口不显示弹窗。
**说明**:showInSubWindow为true的弹窗无法触发显示另一个showInSubWindow为true的弹窗。 | | backgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 否 | 设置弹窗背板填充。 | -| cornerRadius10+ | [BorderRadiuses](ts-types.md#borderradiuses9) \| [Dimension](ts-types.md#dimension10) | 否 | 设置背板的圆角半径。
可分别设置4个圆角的半径。
默认值:{ topLeft: '24vp', topRight: '24vp', bottomLeft: '24vp', bottomRight: '24vp' } | +| cornerRadius10+ | [BorderRadiuses](ts-types.md#borderradiuses9) \| [Dimension](ts-types.md#dimension10) | 否 | 设置背板的圆角半径。
可分别设置4个圆角的半径。
默认值:{ topLeft: '24vp', topRight: '24vp', bottomLeft: '24vp', bottomRight: '24vp' }
**说明**:自定义弹窗默认的背板圆角半径为24vp,如果需要使用cornerRadius属性,请和[borderRadius](ts-universal-attributes-border.md)属性一起使用。 | ## CustomDialogController @@ -90,7 +90,7 @@ struct CustomDialogExample { }).backgroundColor(0xffffff).fontColor(Color.Red) }.margin({ bottom: 10 }) }.borderRadius(10) - // dialog默认的borderRadius为24vp,如果需要使用border属性或cornerRadius属性,请和borderRadius属性一起使用。 + // 如果需要使用border属性或cornerRadius属性,请和borderRadius属性一起使用。 } } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-page-transition-animation.md b/zh-cn/application-dev/reference/arkui-ts/ts-page-transition-animation.md index f567b17cfd740fd1085b29a8df822d4d4890f2df..e290bfa70d9f8331786e19926d050317b6714c2d 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-page-transition-animation.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-page-transition-animation.md @@ -6,6 +6,7 @@ > > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > +> 为了实现更好的转场效果,推荐使用[Navigation组件](../../ui/arkts-navigation-navigation.md)和[模态转场](../../ui/arkts-modal-transition.md)。 | 名称 | 参数 | 必填 | 参数描述 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md b/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md index 6fe560c25eaca837892b1c8e88903b09151fc387..5a4f8f6383ccf1d17788291801b5721fb91919c8 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md @@ -193,7 +193,7 @@ let value: number = AppStorage.get('PropA'); // 47 static set<T>(propName: string, newValue: T): boolean -在AppStorage中设置propName对应属性的值。 +在AppStorage中设置propName对应属性的值。如果newValue的值和propName对应属性的值相同,即不需要做赋值操作,状态变量不会通知UI刷新propName对应属性的值。 **参数:** @@ -220,7 +220,8 @@ let res1: boolean = AppStorage.set('PropB', 47) // false static setOrCreate<T>(propName: string, newValue: T): void -propName如果已经在AppStorage中存在,则设置propName对应是属性的值为newValue。如果不存在,则创建propName属性,值为newValue。 +如果propName已经在AppStorage中存在,并且newValue和propName对应属性的值不同,则设置propName对应属性的值为newValue,否则状态变量不会通知UI刷新propName对应属性的值。 +如果propName不存在,则创建propName属性,值为newValue。 **参数:** @@ -534,7 +535,7 @@ let res1: boolean = AppStorage.Set('PropB', 47) // false static SetOrCreate<T>(propName: string, newValue: T): void -propName如果已经在AppStorage中存在,则设置propName对应是属性的值为newValue。如果不存在,则创建propName属性,值为newValue。 +如果propName已经在AppStorage中存在,则设置propName对应是属性的值为newValue。如果不存在,则创建propName属性,值为newValue。 从API version 10开始废弃,推荐使用[setOrCreate10+](#setorcreate10)。 @@ -802,7 +803,7 @@ let value: number = storage.get('PropA'); // 47 set<T>(propName: string, newValue: T): boolean -在LocalStorage中设置propName对应属性的值。 +在LocalStorage中设置propName对应属性的值。如果newValue的值和propName对应属性的值相同,即不需要做赋值操作,状态变量不会通知UI刷新propName对应属性的值。 从API version 9开始,该接口支持在ArkTS卡片中使用。 @@ -831,7 +832,8 @@ let res1: boolean = storage.set('PropB', 47); // false setOrCreate<T>(propName: string, newValue: T): boolean -propName如果已经在LocalStorage中存在,则设置propName对应是属性的值为newValue。如果不存在,则创建propName属性,初始化为newValue。 +如果propName已经在AppStorage中存在,并且newValue和propName对应属性的值不同,则设置propName对应属性的值为newValue,否则状态变量不会通知UI刷新propName对应属性的值。 +如果propName不存在,则创建propName属性,值为newValue。 从API version 9开始,该接口支持在ArkTS卡片中使用。 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md index 9cc2c9747a0c6e1333d4e95a47aec3dc828f0361..39bcf2faca21d4fa455a33ede5b7a1bad5701964 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md @@ -19,9 +19,9 @@ | 名称 | 类型 | 描述 | | ------ | ------------------------------------------------------------ | ------------------------------------------------------------ | | source | string \| [Resource](ts-types.md#resource) \| [linearGradient](ts-universal-attributes-gradient-color.md) | 边框图源或者渐变色设置。
**说明:**
边框图源仅适用于容器组件,如Row、Column、Flex,在非容器组件上使用会失效。 | -| slice | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | 设置边框图片左上角、右上角、左下角以及右下角的切割宽度。
默认值:0
**说明:**
设置负数时取默认值。
参数类型为[Length](ts-types.md#length)时,统一设置四个角的宽高。
参数为[EdgeWidths](ts-types.md#edgewidths9)时:
- Top:设置图片左上角或者右上角被切割的高。
- Bottom:设置图片左下角或者右下角被切割的高。
- Left:设置图片左上角或者左下角被切割的宽。
- Right:设置图片右上角或者右下角被切割的宽。 | -| width | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | 设置图片边框宽度。
默认值:0
**说明:**
参数类型为[Length](ts-types.md#length)时,统一设置四个角的宽高,设置负数时取默认值。
参数为[EdgeWidths](ts-types.md#edgewidths9)时:
- Top:设置图片边框上边框的宽。
- Bottom:设置图片边框下边框的宽。
- Left:设置图片边框左边框的宽。
- Right:设置图片边框右边框宽。
设置负数时值取1。 | -| outset | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | 设置边框图片向外延伸距离。
默认值:0
**说明:**
设置负数时取默认值。
参数类型为[Length](ts-types.md#length)时,统一设置四个角的宽高。
参数为[EdgeWidths](ts-types.md#edgewidths9)时:
- Top:设置边框图片上边框向外延伸的距离。
- Bottom:设置边框图片下边框向外延伸的距离。
- Left:设置边框图片左边框向外延伸的距离。
- Right:设置边框图片右边框向外延伸的距离。 | +| slice | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | 设置边框图片左上角、右上角、左下角以及右下角的切割宽度。
默认值:0
**说明:**
设置负数时取默认值。
参数类型为[Length](ts-types.md#length)时,统一设置四个角的宽高。
参数类型为[EdgeWidths](ts-types.md#edgewidths9)时:
- Top:设置图片左上角或者右上角被切割的高。
- Bottom:设置图片左下角或者右下角被切割的高。
- Left:设置图片左上角或者左下角被切割的宽。
- Right:设置图片右上角或者右下角被切割的宽。 | +| width | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | 设置图片边框宽度。
默认值:0
**说明:**
参数类型为[Length](ts-types.md#length)时,统一设置四个角的宽高,设置负数时取默认值。
参数类型为[EdgeWidths](ts-types.md#edgewidths9)时:
- Top:设置图片边框上边框的宽。
- Bottom:设置图片边框下边框的宽。
- Left:设置图片边框左边框的宽。
- Right:设置图片边框右边框宽。
设置负数时值取1。 | +| outset | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | 设置边框图片向外延伸距离。
默认值:0
**说明:**
设置负数时取默认值。
参数类型为[Length](ts-types.md#length)时,统一设置四个角的宽高。
参数类型为[EdgeWidths](ts-types.md#edgewidths9)时:
- Top:设置边框图片上边框向外延伸的距离。
- Bottom:设置边框图片下边框向外延伸的距离。
- Left:设置边框图片左边框向外延伸的距离。
- Right:设置边框图片右边框向外延伸的距离。 | | repeat | [RepeatMode](#repeatmode枚举说明) | 设置被切割的图片在边框上的重复方式。
默认值:RepeatMode.Stretch | | fill | boolean | 设置边框图片中心填充。
默认值:false | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md index 2089b18bf7cc0567a0747d1520f4207e2588e446..ff5a7d306a728597037dad4b46f41ac32d71956f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md @@ -9,9 +9,9 @@ ## 事件 -| 名称 | 支持冒泡 | 功能描述 | -| ---------------------------------------- | ---- | ---------------------------------------- | -| onAreaChange(event: (oldValue: [Area](ts-types.md#area8), newValue: [Area](ts-types.md#area8)) => void) | 否 | 组件区域变化时触发该回调。仅会响应由布局变化所导致的组件大小、位置发生变化时的回调。由绘制变化所导致的渲染属性变化不会响应回调,如translate、offset。 | +| 名称 | 支持冒泡 | 功能描述 | +| ------------------------------------------------------------ | -------- | ------------------------------------------------------------ | +| onAreaChange(event: (oldValue: [Area](ts-types.md#area8), newValue: [Area](ts-types.md#area8)) => void) | 否 | 组件区域变化时触发该回调。仅会响应由布局变化所导致的组件大小、位置发生变化时的回调。由绘制变化所导致的渲染属性变化不会响应回调,如translate、offset。
- [Area](ts-types.md#area8):返回目标元素的宽高以及目标元素相对父元素和页面左上角的坐标位置。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md index f38c48b0dedd04aa9186237b01619754e3fa1f99..2b5d2a9a6f3cb42dd6cead1c76e037b860fe892c 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md @@ -59,7 +59,7 @@ ArkUI组件默认支持拖拽。 | getSummary()10+ | [Summary](../apis/js-apis-data-udmf.md#summary) | 从DragEvent中获取拖拽相关数据的简介。 | | setResult(dragRect: [DragResult](#dragresult10枚举说明))10+ | void | 向DragEvent中设置拖拽结果。 | | getResult()10+ | [DragResult](#dragresult10枚举说明) | 从DragEvent中获取拖拽结果。 | -| getPrviewRect()10+ | [Rectangle](ts-universal-attributes-touch-target.md#rectangle对象说明) | 获取预览图所在的Rectangle。 | +| getPreviewRect()10+ | [Rectangle](ts-universal-attributes-touch-target.md#rectangle对象说明) | 获取预览图所在的Rectangle。 | | getVelocityX()10+ | number | 获取当前拖拽的x轴方向拖动速度。坐标轴原点为屏幕左上角,单位为vp,分正负方向速度,从左往右为正,反之为负。 | | getVelocityY()10+ | number | 获取当前拖拽的y轴方向拖动速度。坐标轴原点为屏幕左上角,单位为vp,分正负方向速度,从上往下为正,反之为负。 | | getVelocity()10+ | number | 获取当前拖拽的主方向拖动速度。为xy轴方向速度的平方和的算术平方根。 | diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-se.md b/zh-cn/application-dev/reference/errorcodes/errorcode-se.md index cc39336be4ff17c95daa8e410350ae2aac6b29e9..90c6f894358bced7338dfdffc6b532ea93958493 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-se.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-se.md @@ -8,7 +8,7 @@ **错误信息** -Illegal service state exception. +IllegalStateError, an attempt is made to use an SE session that has been closed. **错误描述** @@ -28,7 +28,7 @@ SE服务状态异常。 **错误信息** -No such element exception. +NoSuchElementError, the AID on the SE is not available or cannot be selected. **错误描述** @@ -48,7 +48,7 @@ No such element exception. **错误信息** -Illegal access rule exception. +SecurityError, the calling application cannot be granted access to this AID or the default applet on this session. **错误描述** @@ -67,7 +67,7 @@ Illegal access rule exception. **错误信息** -Secure element IO exception. +IOError, there is a communication problem to the reader or the SE. **错误描述** diff --git a/zh-cn/application-dev/reference/native-apis/_native_vsync.md b/zh-cn/application-dev/reference/native-apis/_native_vsync.md index 0487dbc7c286827dd833fb9798d592dc5ee84718..83a9586f575fcbde8f1cf7f50c1af6a368488fc7 100644 --- a/zh-cn/application-dev/reference/native-apis/_native_vsync.md +++ b/zh-cn/application-dev/reference/native-apis/_native_vsync.md @@ -19,7 +19,7 @@ | 名称 | 描述 | | -------- | -------- | -| [native_vsync.h](native__vsync_8h.md) | 定义获取和使用NativeVsync的相关函数
引用文件:<native_vsync/native_vsync.h> | +| [native_vsync.h](native__vsync_8h.md) | 定义获取和使用NativeVsync的相关函数
**引用文件:** <native_vsync/native_vsync.h>
**库:** libnative_vsync.so | ### 类型定义 @@ -37,7 +37,7 @@ | [OH_NativeVSync_Create](#oh_nativevsync_create) (const char \*name, unsigned int length) | 创建一个OH_NativeVSync实例,每次调用都会产生一个新的实例 | | [OH_NativeVSync_Destroy](#oh_nativevsync_destroy) ([OH_NativeVSync](#oh_nativevsync) \*nativeVsync) | 销毁OH_NativeVSync实例 | | [OH_NativeVSync_RequestFrame](#oh_nativevsync_requestframe) ([OH_NativeVSync](#oh_nativevsync) \*nativeVsync, [OH_NativeVSync_FrameCallback](#oh_nativevsync_framecallback) callback, void \*data) | 请求下一次vsync信号,当信号到来时,调用回调函数callback | - +| [OH_NativeVSync_GetPeriod](#oh_nativevsync_getperiod) ([OH_NativeVSync](#oh_nativevsync) \*nativeVsync, long long \*period) |获取vsync周期。| ## 类型定义说明 @@ -77,6 +77,34 @@ VSync回调函数类型 ## 函数说明 +### OH_NativeVSync_GetPeriod() + + +``` +int OH_NativeVSync_GetPeriod (OH_NativeVSync * nativeVsync, long long * period ) +``` + +**描述:** + +获取vsync周期。 + +\@syscap SystemCapability.Graphic.Graphic2D.NativeVsync + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| nativeVsync | 一个指向OH_NativeVSync实例的指针。| +| period | 用于获取vsync周期的变量。 | + +**返回:** + +返回值为0表示执行成功。 + +**起始版本:** + +10 + ### OH_NativeVSync_Create() diff --git a/zh-cn/application-dev/reference/native-apis/_o_h___native_buffer.md b/zh-cn/application-dev/reference/native-apis/_o_h___native_buffer.md index 18e79e28c1f3733d0074f5b1ff0f408db1da5bc7..ba9381e58e64bc32083898c438e2559c1570bab9 100644 --- a/zh-cn/application-dev/reference/native-apis/_o_h___native_buffer.md +++ b/zh-cn/application-dev/reference/native-apis/_o_h___native_buffer.md @@ -19,7 +19,7 @@ | 名称 | 描述 | | -------- | -------- | -| [native_buffer.h](native__buffer_8h.md) | 定义获取和使用NativeBuffer的相关函数。
引用文件:<native_buffer/native_buffer.h> | +| [native_buffer.h](native__buffer_8h.md) | 定义获取和使用NativeBuffer的相关函数。
**引用文件:** <native_buffer/native_buffer.h>
**库:** libnative_buffer.so| ### 结构体 @@ -35,6 +35,12 @@ | -------- | -------- | | [OH_NativeBuffer](#oh_nativebuffer) | 提供OH_NativeBuffer结构体声明。 | +### 枚举 + +| 名称 | 描述 | +| -------- | -------- | +| [OH_NativeBuffer_Usage](#oh_nativebuffer_usage) { NATIVEBUFFER_USAGE_CPU_READ = (1ULL << 0), NATIVEBUFFER_USAGE_CPU_WRITE = (1ULL << 1), NATIVEBUFFER_USAGE_MEM_DMA = (1ULL << 3) } | OH_NativeBuffer的用途。 | +| [OH_NativeBuffer_Format](#oh_nativebuffer_format) {
NATIVEBUFFER_PIXEL_FMT_RGB_565 = 3, NATIVEBUFFER_PIXEL_FMT_RGBA_5658, NATIVEBUFFER_PIXEL_FMT_RGBX_4444, NATIVEBUFFER_PIXEL_FMT_RGBA_4444,
NATIVEBUFFER_PIXEL_FMT_RGB_444, NATIVEBUFFER_PIXEL_FMT_RGBX_5551, NATIVEBUFFER_PIXEL_FMT_RGBA_5551, NATIVEBUFFER_PIXEL_FMT_RGB_555,
NATIVEBUFFER_PIXEL_FMT_RGBX_8888, NATIVEBUFFER_PIXEL_FMT_RGBA_8888, NATIVEBUFFER_PIXEL_FMT_RGB_888, NATIVEBUFFER_PIXEL_FMT_BGR_565,
NATIVEBUFFER_PIXEL_FMT_BGRX_4444, NATIVEBUFFER_PIXEL_FMT_BGRA_4444, NATIVEBUFFER_PIXEL_FMT_BGRX_5551, NATIVEBUFFER_PIXEL_FMT_BGRA_5551,
NATIVEBUFFER_PIXEL_FMT_BGRX_8888, NATIVEBUFFER_PIXEL_FMT_BGRA_8888, NATIVEBUFFER_PIXEL_FMT_BUTT = 0X7FFFFFFF
} | OH_NativeBuffer的格式。 | ### 函数 @@ -63,6 +69,70 @@ typedef struct OH_NativeBuffer OH_NativeBuffer 提供OH_NativeBuffer结构体声明。 +## 枚举类型说明 + + +### OH_NativeBuffer_Format + +``` +enum OH_NativeBuffer_Format +``` + +**描述:** + +OH_NativeBuffer的格式。 + +\@SysCap SystemCapability.Graphic.Graphic2D.NativeBuffer + +| 枚举值 | 描述 | +| -------- | -------- | +| NATIVEBUFFER_PIXEL_FMT_RGB_565 | RGB565格式 | +| NATIVEBUFFER_PIXEL_FMT_RGBA_5658 | RGBA5658格式 | +| NATIVEBUFFER_PIXEL_FMT_RGBX_4444 | RGBX4444格式 | +| NATIVEBUFFER_PIXEL_FMT_RGBA_4444 | RGBA4444格式 | +| NATIVEBUFFER_PIXEL_FMT_RGB_444 | RGB444格式 | +| NATIVEBUFFER_PIXEL_FMT_RGBX_5551 | RGBX5551格式 | +| NATIVEBUFFER_PIXEL_FMT_RGBA_5551 | RGBA5551格式 | +| NATIVEBUFFER_PIXEL_FMT_RGB_555 | RGB555格式 | +| NATIVEBUFFER_PIXEL_FMT_RGBX_8888 | RGBX8888格式 | +| NATIVEBUFFER_PIXEL_FMT_RGBA_8888 | RGBA8888格式 | +| NATIVEBUFFER_PIXEL_FMT_RGB_888 | RGB888格式 | +| NATIVEBUFFER_PIXEL_FMT_BGR_565 | BGR565格式 | +| NATIVEBUFFER_PIXEL_FMT_BGRX_4444 | BGRX4444格式 | +| NATIVEBUFFER_PIXEL_FMT_BGRA_4444 | BGRA4444格式 | +| NATIVEBUFFER_PIXEL_FMT_BGRX_5551 | BGRX5551格式 | +| NATIVEBUFFER_PIXEL_FMT_BGRA_5551 | BGRA5551格式 | +| NATIVEBUFFER_PIXEL_FMT_BGRX_8888 | BGRX8888格式 | +| NATIVEBUFFER_PIXEL_FMT_BGRA_8888 | BGRA8888格式 | +| NATIVEBUFFER_PIXEL_FMT_BUTT | 无效格式 | + +**起始版本:** + +10 + + +### OH_NativeBuffer_Usage + +``` +enum OH_NativeBuffer_Usage +``` + +**描述:** + +OH_NativeBuffer的用途。 + +\@SysCap SystemCapability.Graphic.Graphic2D.NativeBuffer + +| 枚举值 | 描述 | +| -------- | -------- | +| NATIVEBUFFER_USAGE_CPU_READ | CPU可读 | +| NATIVEBUFFER_USAGE_CPU_WRITE | CPU可写 | +| NATIVEBUFFER_USAGE_MEM_DMA | 直接内存访问缓冲区 | + +**起始版本:** + +10 + ## 函数说明 diff --git a/zh-cn/application-dev/reference/native-apis/_o_h___native_buffer___config.md b/zh-cn/application-dev/reference/native-apis/_o_h___native_buffer___config.md index 73dcff7c6944290528f4ff7ba6bf4be3197dbedf..45783932327ccd5f11842c6d31354ce30cb0997a 100644 --- a/zh-cn/application-dev/reference/native-apis/_o_h___native_buffer___config.md +++ b/zh-cn/application-dev/reference/native-apis/_o_h___native_buffer___config.md @@ -21,9 +21,72 @@ OH_NativeBuffer的属性配置,用于申请新的OH_NativeBuffer实例或查 ### 成员变量 -| 成员变量名称 | 描述 | +| 名称 | 描述 | | -------- | -------- | -| width | 宽度(像素)。 | -| height | 高度(像素)。 | -| format | 像素格式。 | -| usage | buffer的用途说明。 | +| [width](#width) | 宽度(像素)。 | +| [height](#height) | 高度(像素)。 | +| [format](#format) | 像素格式。 | +| [usage](#usage) | buffer的用途说明。 | +| [stride](#stride) | 本地窗口缓冲区步幅。 | + + +## 结构体成员变量说明 + + +### format + +``` +int32_t OH_NativeBuffer_Config::format +``` + +**描述:** + +像素格式 + + +### height + +``` +int32_t OH_NativeBuffer_Config::height +``` + +**描述:** + +高度(像素)。 + + +### stride + +``` +int32_t OH_NativeBuffer_Config::stride +``` + +**描述:** + +本地窗口缓冲区步幅。 + +**起始版本:** + +10 + + +### usage + +``` +int32_t OH_NativeBuffer_Config::usage +``` + +**描述:** + +buffer的用途说明。 + + +### width + +``` +int32_t OH_NativeBuffer_Config::width +``` + +**描述:** + +宽度(像素)。 diff --git a/zh-cn/application-dev/reference/native-apis/native__buffer_8h.md b/zh-cn/application-dev/reference/native-apis/native__buffer_8h.md index 07e37cf965ea928fa016826e10e6600621fe67e0..68f6ec4751d8e3c5bb517059fb47f927d40ec9a1 100644 --- a/zh-cn/application-dev/reference/native-apis/native__buffer_8h.md +++ b/zh-cn/application-dev/reference/native-apis/native__buffer_8h.md @@ -30,6 +30,12 @@ | -------- | -------- | | [OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) | 提供OH_NativeBuffer结构体声明 | +### 枚举 + +| 名称 | 描述 | +| -------- | -------- | +| [OH_NativeBuffer_Usage](_o_h___native_buffer.md#oh_nativebuffer_usage) { NATIVEBUFFER_USAGE_CPU_READ = (1ULL << 0), NATIVEBUFFER_USAGE_CPU_WRITE = (1ULL << 1), NATIVEBUFFER_USAGE_MEM_DMA = (1ULL << 3) } | OH_NativeBuffer的用途。 | +| [OH_NativeBuffer_Format](_o_h___native_buffer.md#oh_nativebuffer_format) {
NATIVEBUFFER_PIXEL_FMT_RGB_565 = 3, NATIVEBUFFER_PIXEL_FMT_RGBA_5658, NATIVEBUFFER_PIXEL_FMT_RGBX_4444, NATIVEBUFFER_PIXEL_FMT_RGBA_4444,
NATIVEBUFFER_PIXEL_FMT_RGB_444, NATIVEBUFFER_PIXEL_FMT_RGBX_5551, NATIVEBUFFER_PIXEL_FMT_RGBA_5551, NATIVEBUFFER_PIXEL_FMT_RGB_555,
NATIVEBUFFER_PIXEL_FMT_RGBX_8888, NATIVEBUFFER_PIXEL_FMT_RGBA_8888, NATIVEBUFFER_PIXEL_FMT_RGB_888, NATIVEBUFFER_PIXEL_FMT_BGR_565,
NATIVEBUFFER_PIXEL_FMT_BGRX_4444, NATIVEBUFFER_PIXEL_FMT_BGRA_4444, NATIVEBUFFER_PIXEL_FMT_BGRX_5551, NATIVEBUFFER_PIXEL_FMT_BGRA_5551,
NATIVEBUFFER_PIXEL_FMT_BGRX_8888, NATIVEBUFFER_PIXEL_FMT_BGRA_8888, NATIVEBUFFER_PIXEL_FMT_BUTT = 0X7FFFFFFF
} | OH_NativeBuffer的格式。 | ### 函数 diff --git a/zh-cn/application-dev/reference/native-apis/native__vsync_8h.md b/zh-cn/application-dev/reference/native-apis/native__vsync_8h.md index f127e04ce8e7028d9ce1a9d27547577d59df05c2..c1001d8bffd2d7639ca32e49b9128e6e35c6882e 100644 --- a/zh-cn/application-dev/reference/native-apis/native__vsync_8h.md +++ b/zh-cn/application-dev/reference/native-apis/native__vsync_8h.md @@ -32,3 +32,4 @@ | [OH_NativeVSync_Create](_native_vsync.md#oh_nativevsync_create) (const char \*name, unsigned int length) | 创建一个OH_NativeVSync实例,每次调用都会产生一个新的实例 | | [OH_NativeVSync_Destroy](_native_vsync.md#oh_nativevsync_destroy) (OH_NativeVSync \*nativeVsync) | 销毁OH_NativeVSync实例 | | [OH_NativeVSync_RequestFrame](_native_vsync.md#oh_nativevsync_requestframe) (OH_NativeVSync \*nativeVsync, OH_NativeVSync_FrameCallback callback, void \*data) | 请求下一次vsync信号,当信号到来时,调用回调函数callback | +| [OH_NativeVSync_GetPeriod](_native_vsync.md#oh_nativevsync_getperiod) (OH_NativeVSync \*nativeVsync, long long \*period) |获取vsync周期。| \ No newline at end of file diff --git a/zh-cn/application-dev/security/accesstoken-guidelines.md b/zh-cn/application-dev/security/accesstoken-guidelines.md index 57a4f6f752995e0cb33d12039d2b11490c87f102..0fe95d99b9c0e1dcf38e62ce2a622749cd34e7b8 100644 --- a/zh-cn/application-dev/security/accesstoken-guidelines.md +++ b/zh-cn/application-dev/security/accesstoken-guidelines.md @@ -173,25 +173,28 @@ ```ts import bundleManager from '@ohos.bundle.bundleManager'; import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; + import { BusinessError } from '@ohos.base'; async function checkAccessToken(permission: Permissions): Promise { let atManager = abilityAccessCtrl.createAtManager(); - let grantStatus: abilityAccessCtrl.GrantStatus; + let grantStatus: abilityAccessCtrl.GrantStatus = abilityAccessCtrl.GrantStatus.PERMISSION_DENIED; // 获取应用程序的accessTokenID - let tokenId: number; + let tokenId: number = 0; try { let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION); let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo; tokenId = appInfo.accessTokenId; - } catch (err) { + } catch (error) { + let err: BusinessError = error as BusinessError; console.error(`Failed to get bundle info for self. Code is ${err.code}, message is ${err.message}`); } // 校验应用是否被授予权限 try { grantStatus = await atManager.checkAccessToken(tokenId, permission); - } catch (err) { + } catch (error) { + let err: BusinessError = error as BusinessError; console.error(`Failed to check access token. Code is ${err.code}, message is ${err.message}`); } @@ -222,35 +225,34 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import window from '@ohos.window'; import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; - + import { BusinessError } from '@ohos.base'; + const permissions: Array = ['ohos.permission.READ_CALENDAR']; - export default class EntryAbility extends UIAbility { - // ... - - onWindowStageCreate(windowStage: window.WindowStage) { - // Main window is created, set main page for this ability - let context = this.context; - let atManager = abilityAccessCtrl.createAtManager(); - // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗 - - atManager.requestPermissionsFromUser(context, permissions).then((data) => { - let grantStatus: Array = data.authResults; - let length: number = grantStatus.length; - for (let i = 0; i < length; i++) { - if (grantStatus[i] === 0) { - // 用户授权,可以继续访问目标操作 - } else { - // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限 - return; - } - } - // 授权成功 - }).catch((err) => { - console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`); - }) - // ... - } + // ... + onWindowStageCreate(windowStage: window.WindowStage) { + // Main window is created, set main page for this ability + let context = this.context; + let atManager = abilityAccessCtrl.createAtManager(); + // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗 + + atManager.requestPermissionsFromUser(context, permissions).then((data) => { + let grantStatus: Array = data.authResults; + let length: number = grantStatus.length; + for (let i = 0; i < length; i++) { + if (grantStatus[i] === 0) { + // 用户授权,可以继续访问目标操作 + } else { + // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限 + return; + } + } + // 授权成功 + }).catch((err: BusinessError) => { + console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`); + }) + // ... + } } ``` @@ -259,37 +261,38 @@ ```typescript import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; import common from '@ohos.app.ability.common'; - + import { BusinessError } from '@ohos.base'; + const permissions: Array = ['ohos.permission.READ_CALENDAR']; - + @Entry @Component struct Index { - reqPermissionsFromUser(permissions: Array): void { - let context = getContext(this) as common.UIAbilityContext; - let atManager = abilityAccessCtrl.createAtManager(); - // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗 - atManager.requestPermissionsFromUser(context, permissions).then((data) => { - let grantStatus: Array = data.authResults; - let length: number = grantStatus.length; - for (let i = 0; i < length; i++) { - if (grantStatus[i] === 0) { - // 用户授权,可以继续访问目标操作 - } else { - // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限 - return; - } - } - // 授权成功 - }).catch((err) => { - console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`); - }) - } - - // 页面展示 - build() { - // ... - } + reqPermissionsFromUser(permissions: Array): void { + let context = getContext(this) as common.UIAbilityContext; + let atManager = abilityAccessCtrl.createAtManager(); + // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗 + atManager.requestPermissionsFromUser(context, permissions).then((data) => { + let grantStatus: Array = data.authResults; + let length: number = grantStatus.length; + for (let i = 0; i < length; i++) { + if (grantStatus[i] === 0) { + // 用户授权,可以继续访问目标操作 + } else { + // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限 + return; + } + } + // 授权成功 + }).catch((err: BusinessError) => { + console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`); + }) + } + + // 页面展示 + build() { + // ... + } } ``` @@ -297,10 +300,59 @@ 调用[requestPermissionsFromUser()](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9)方法后,应用程序将等待用户授权的结果。如果用户授权,则可以继续访问目标操作。如果用户拒绝授权,则需要提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限。 + ArkTS语法不支持直接使用globalThis,需要通过一个单例的map来做中转。开发者需要: + + a. 在EntryAbility.ets中导入构建的单例对象GlobalThis。 + ```ts + import { GlobalThis } from '../utils/globalThis'; // 需要根据globalThis.ets的路径自行适配 + ``` + b. 在onCreate中添加: + ```ts + GlobalThis.getInstance().setContext('context', this.context); + ``` + + > **说明:** + > + > 由于在ts中引入ets文件会有告警提示,需要将EntryAbility.ts的文件后缀修改为EntryAbility.ets,并在module.json5中同步修改。 + + **globalThis.ets示例代码如下:** + ```ts + import common from '@ohos.app.ability.common'; + + // 构造单例对象 + export class GlobalThis { + private constructor() {} + private static instance: GlobalThis; + private _uiContexts = new Map(); + + public static getInstance(): GlobalThis { + if (!GlobalThis.instance) { + GlobalThis.instance = new GlobalThis(); + } + return GlobalThis.instance; + } + + getContext(key: string): common.UIAbilityContext | undefined { + return this._uiContexts.get(key); + } + + setContext(key: string, value: common.UIAbilityContext): void { + this._uiContexts.set(key, value); + } + + // 其他需要传递的内容依此扩展 + } + ``` + ```ts + import { BusinessError } from '@ohos.base'; + import Want from '@ohos.app.ability.Want'; + import { GlobalThis } from '../utils/globalThis'; + import common from '@ohos.app.ability.common'; + function openPermissionsInSystemSettings(): void { - let context = getContext(this) as common.UIAbilityContext; - let wantInfo = { + let context: common.UIAbilityContext = GlobalThis.getInstance().getContext('context'); + let wantInfo: Want = { action: 'action.settings.app.info', parameters: { settingsParamBundleName: 'com.example.myapplication' // 打开指定应用的详情页面 @@ -308,7 +360,7 @@ } context.startAbility(wantInfo).then(() => { // ... - }).catch((err) => { + }).catch((err: BusinessError) => { // ... }) } @@ -319,6 +371,7 @@ 通过调用[requestPermissionsFromUser()](../reference/apis/js-apis-inner-app-context.md#contextrequestpermissionsfromuser7)接口向用户动态申请授权。 ```js +import { BusinessError } from '@ohos.base'; import featureAbility from '@ohos.ability.featureAbility'; reqPermissions() { @@ -329,7 +382,7 @@ reqPermissions() { console.log("data:" + JSON.stringify(data)); console.log("data permissions:" + JSON.stringify(data.permissions)); console.log("data result:" + JSON.stringify(data.authResults)); - }, (err) => { + }, (err: BusinessError) => { console.error('Failed to start ability', err.code); }); } diff --git a/zh-cn/application-dev/security/huks-guidelines.md b/zh-cn/application-dev/security/huks-guidelines.md index 2a70f27da1f5927a8fdecaf2dc574d13d954f628..2bc815d539f3ce9423a661404c19fc544cf483b8 100644 --- a/zh-cn/application-dev/security/huks-guidelines.md +++ b/zh-cn/application-dev/security/huks-guidelines.md @@ -1,6 +1,10 @@ # 通用密钥库开发指导(ArkTS) +> **说明** +> +> 本开发指导需使用API version 9及以上版本SDK,仅适用于JS语言开发。 + ## 生成新密钥 HUKS提供为业务安全随机生成密钥的能力。通过HUKS生成的密钥,密钥的全生命周期明文不会出安全环境,能保证任何人都无法接触获取到密钥的明文。即使生成密钥的业务自身,后续也只能通过HUKS提供的接口请求执行密钥操作,获取操作结果,但无法接触到密钥自身。 @@ -19,7 +23,7 @@ HUKS提供为业务安全随机生成密钥的能力。通过HUKS生成的密钥 **代码示例:** -```ts +```js /* * 以下以生成DH密钥的Callback操作使用为例 */ @@ -107,7 +111,7 @@ async function TestGenKey() { **代码示例:** -```ts +```js /* * 以导入AES256密钥为例 */ @@ -167,7 +171,7 @@ try { **代码示例:** -```ts +```js import huks from '@ohos.security.huks'; let keyAlias = 'AES256Alias_sample'; @@ -246,7 +250,7 @@ try { **代码示例:** -```ts +```js /* * 以下以SM2密钥的Callback操作验证为例 */ @@ -277,7 +281,7 @@ let inputEccPair = new Uint8Array([ // 坐标z 0xfb, 0x8b, 0x9f, 0x12, 0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a, 0x7c, 0x86, 0xba, 0xca, 0x64, 0x0b, 0x88, 0x96, 0xe2, 0xfa, 0x77, 0xbc, 0x71, 0xe3, 0x0f, 0x0f, 0x9e, 0x3c, 0xe5, 0xf9 - ]); +]); /* * 封装密钥属性参数集 @@ -341,7 +345,7 @@ let importOptions = { }; // 导出加密导入用途的公钥 -function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { +function exportKeyItem(keyAlias, huksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.exportKeyItem(keyAlias, huksOptions, function (error, data) { @@ -358,7 +362,7 @@ function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObjec }); } -async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { +async function publicExportKeyFunc(keyAlias, huksOptions) { console.info(`enter callback export`); let throwObject = {isThrow: false}; try { @@ -380,7 +384,7 @@ async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions } // 此处用导入密钥来模拟“生成加密导入用途的密钥” -function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { +function importKeyItem(keyAlias, huksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.importKeyItem(keyAlias, huksOptions, function (error, data) { @@ -397,7 +401,7 @@ function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObjec }); } -async function publicImportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { +async function publicImportKeyFunc(keyAlias, huksOptions) { console.info(`enter promise importKeyItem`); let throwObject = {isThrow: false}; try { @@ -418,7 +422,7 @@ async function publicImportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions } // 执行加密导入 -async function publicImportWrappedKey(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions) { +async function publicImportWrappedKey(keyAlias, wrappingKeyAlias, huksOptions) { console.info(`enter callback importWrappedKeyItem`); var throwObject = {isThrow: false}; try { @@ -438,7 +442,7 @@ async function publicImportWrappedKey(keyAlias:string, wrappingKeyAlias:string, } } -function importWrappedKeyItem(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions, throwObject) { +function importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions, function (error, data) { @@ -456,7 +460,7 @@ function importWrappedKeyItem(keyAlias:string, wrappingKeyAlias:string, huksOpti } // 删除加密导入用途的密钥 -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { +function deleteKeyItem(keyAlias, huksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { @@ -473,7 +477,7 @@ function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObjec }); } -async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { +async function publicDeleteKeyFunc(keyAlias, huksOptions) { console.info(`enter callback deleteKeyItem`); let throwObject = {isThrow: false}; try { @@ -585,7 +589,7 @@ async function ImportWrappedKeyNormalTest() { **代码示例:** -```ts +```js import huks from '@ohos.security.huks'; /* @@ -635,7 +639,7 @@ HUKS基于密钥会话来操作数据,使用密钥时基于以下流程: ### 加密解密 -```ts +```js /* * 以下以AES 128密钥的Callback操作使用为例 */ @@ -932,7 +936,7 @@ struct Index { 应用在协商密钥时建议传入[HuksKeyStorageType](../reference/apis/js-apis-huks.md#hukskeystoragetype)中定义的类型;从API10开始应用只能选择存储(HUKS_STORAGE_ONLY_USED_IN_HUKS),或者选择导出(HUKS_STORAGE_KEY_EXPORT_ALLOWED),若不传入,则默认同时支持存储和导出,存在安全问题,不推荐业务使用。 -```ts +```js /* * 以下以X25519 256 TEMP密钥的Callback操作使用为例 */ @@ -1047,7 +1051,7 @@ function StringToUint8Array(str) { return new Uint8Array(arr); } -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { +function generateKeyItem(keyAlias, huksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { @@ -1064,7 +1068,7 @@ function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObj }); } -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { +async function publicGenKeyFunc(keyAlias, huksOptions) { console.info(`enter callback generateKeyItem`); let throwObject = {isThrow: false}; try { @@ -1084,7 +1088,7 @@ async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { } } -function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { +function initSession(keyAlias, huksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.initSession(keyAlias, huksOptions, function (error, data) { @@ -1101,7 +1105,7 @@ function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) }); } -async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { +async function publicInitFunc(keyAlias, huksOptions) { console.info(`enter callback doInit`); let throwObject = {isThrow: false}; try { @@ -1122,7 +1126,7 @@ async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { } } -function updateSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { +function updateSession(handle, huksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.updateSession(handle, huksOptions, function (error, data) { @@ -1139,7 +1143,7 @@ function updateSession(handle:number, huksOptions:huks.HuksOptions, throwObject) }); } -async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) { +async function publicUpdateFunc(handle, huksOptions) { console.info(`enter callback doUpdate`); let throwObject = {isThrow: false}; try { @@ -1159,7 +1163,7 @@ async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) { } } -function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { +function finishSession(handle, huksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.finishSession(handle, huksOptions, function (error, data) { @@ -1176,7 +1180,7 @@ function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) }); } -async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) { +async function publicFinishFunc(handle, huksOptions) { console.info(`enter callback doFinish`); let throwObject = {isThrow: false}; try { @@ -1197,7 +1201,7 @@ async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) { } } -function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { +function exportKeyItem(keyAlias, huksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.exportKeyItem(keyAlias, huksOptions, function (error, data) { @@ -1214,7 +1218,7 @@ function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObjec }); } -async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { +async function publicExportKeyFunc(keyAlias, huksOptions) { console.info(`enter callback export`); let throwObject = {isThrow: false}; try { @@ -1235,7 +1239,7 @@ async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions } } -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { +function deleteKeyItem(keyAlias, huksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { @@ -1252,7 +1256,7 @@ function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObjec }); } -async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { +async function publicDeleteKeyFunc(keyAlias, huksOptions) { console.info(`enter callback deleteKeyItem`); let throwObject = {isThrow: false}; try { @@ -1303,7 +1307,7 @@ async function testAgree() { 应用在派生密钥时建议传入[HuksKeyStorageType](../reference/apis/js-apis-huks.md#hukskeystoragetype)中定义的类型;从API10开始应用只能选择存储(HUKS_STORAGE_ONLY_USED_IN_HUKS),或者选择导出(HUKS_STORAGE_KEY_EXPORT_ALLOWED),若不传入,则默认同时支持存储和导出,存在安全问题,不推荐业务使用。 -```ts +```js /* * 以下以HKDF256密钥的Promise操作使用为例 */ @@ -1421,7 +1425,7 @@ function StringToUint8Array(str) { return new Uint8Array(arr); } -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { +function generateKeyItem(keyAlias, huksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { @@ -1438,7 +1442,7 @@ function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObj }); } -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { +async function publicGenKeyFunc(keyAlias, huksOptions) { console.info(`enter callback generateKeyItem`); let throwObject = {isThrow: false}; try { @@ -1458,7 +1462,7 @@ async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { } } -function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { +function initSession(keyAlias, huksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.initSession(keyAlias, huksOptions, function (error, data) { @@ -1475,7 +1479,7 @@ function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) }); } -async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { +async function publicInitFunc(keyAlias, huksOptions) { console.info(`enter callback doInit`); let throwObject = {isThrow: false}; try { @@ -1496,7 +1500,7 @@ async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { } } -function updateSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { +function updateSession(handle, huksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.updateSession(handle, huksOptions, function (error, data) { @@ -1513,7 +1517,7 @@ function updateSession(handle:number, huksOptions:huks.HuksOptions, throwObject) }); } -async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) { +async function publicUpdateFunc(handle, huksOptions) { console.info(`enter callback doUpdate`); let throwObject = {isThrow: false}; try { @@ -1533,7 +1537,7 @@ async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) { } } -function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { +function finishSession(handle, huksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.finishSession(handle, huksOptions, function (error, data) { @@ -1550,7 +1554,7 @@ function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) }); } -async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) { +async function publicFinishFunc(handle, huksOptions) { console.info(`enter callback doFinish`); let throwObject = {isThrow: false}; try { @@ -1571,7 +1575,7 @@ async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) { } } -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { +function deleteKeyItem(keyAlias, huksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { @@ -1588,7 +1592,7 @@ function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObjec }); } -async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { +async function publicDeleteKeyFunc(keyAlias, huksOptions) { console.info(`enter callback deleteKeyItem`); let throwObject = {isThrow: false}; try { @@ -1689,379 +1693,379 @@ HUKS提供了全面完善的密钥访问控制能力,确保存储在HUKS中的 1. 生成密钥并指定指纹访问控制和相关属性 - ```ts - import huks from '@ohos.security.huks'; +```js +import huks from '@ohos.security.huks'; - /* - * 确定密钥别名和封装密钥属性参数集 - */ - let keyAlias = 'dh_key_fingerprint_access'; - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, - } - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - // 指定密钥身份认证的类型:指纹 - properties[5] = { - tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, - value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_FINGERPRINT - } - // 指定密钥安全授权的类型(失效类型):新录入生物特征(指纹)后无效 - properties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, - value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL - } - // 指定挑战值的类型:默认类型 - properties[7] = { - tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, - value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL - } - let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) - } +/* + * 确定密钥别名和封装密钥属性参数集 + */ +let keyAlias = 'dh_key_fingerprint_access'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, +} +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, +} +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, +} +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, +} +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +// 指定密钥身份认证的类型:指纹 +properties[5] = { + tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, + value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_FINGERPRINT +} +// 指定密钥安全授权的类型(失效类型):新录入生物特征(指纹)后无效 +properties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, + value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL +} +// 指定挑战值的类型:默认类型 +properties[7] = { + tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, + value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL +} +let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) +} - /* - * 生成密钥 - */ - function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { - return new Promise((resolve, reject) => { - try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); - } +/* + * 生成密钥 + */ +function generateKeyItem(keyAlias, huksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} - async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); - let throwObject = {isThrow: false}; - try { - await generateKeyItem(keyAlias, huksOptions, throwObject) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } - } +async function publicGenKeyFunc(keyAlias, huksOptions) { + console.info(`enter callback generateKeyItem`); + let throwObject = {isThrow: false}; + try { + await generateKeyItem(keyAlias, huksOptions, throwObject) + .then((data) => { + console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} - async function TestGenKeyForFingerprintAccessControl() { - await publicGenKeyFunc(keyAlias, huksOptions); - } - ``` +async function TestGenKeyForFingerprintAccessControl() { + await publicGenKeyFunc(keyAlias, huksOptions); +} +``` 2. 初始化密钥会话获取挑战值并发起指纹认证获取认证令牌 - ```ts - import huks from '@ohos.security.huks'; - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - /* - * 确定密钥别名和封装密钥属性参数集 - */ - let srcKeyAlias = 'sm4_key_fingerprint_access'; - let handle; - let challenge; - let fingerAuthToken; - let authType = userIAM_userAuth.UserAuthType.FINGERPRINT; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - - /* 集成生成密钥参数集 & 加密参数集 */ - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, - } - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) - } - - function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.initSession(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); - } - - async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback doInit`); - let throwObject = {isThrow: false}; - try { - await initSession(keyAlias, huksOptions, throwObject) - .then ((data) => { - console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); - handle = data.handle; - challenge = data.challenge; - }) - .catch((error) => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); - } - } +```js +import huks from '@ohos.security.huks'; +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - function userIAMAuthFinger(huksChallenge:Uint8Array) { - // 获取认证对象 - let auth; - try { - auth = userIAM_userAuth.getAuthInstance(huksChallenge, authType, authTrustLevel); - console.log("get auth instance success"); - } catch (error) { - console.log("get auth instance failed" + error); - } - - // 订阅认证结果 - try { - auth.on("result", { - callback: (result: userIAM_userAuth.AuthResultInfo) => { - /* 认证成功获取认证令牌 */ - fingerAuthToken = result.token; - } - }); - console.log("subscribe authentication event success"); - } catch (error) { - console.log("subscribe authentication event failed " + error); - } - - // 开始认证 - try { - auth.start(); - console.info("authV9 start auth success"); - } catch (error) { - console.info("authV9 start auth failed, error = " + error); - } - } +/* + * 确定密钥别名和封装密钥属性参数集 + */ +let srcKeyAlias = 'sm4_key_fingerprint_access'; +let handle; +let challenge; +let fingerAuthToken; +let authType = userIAM_userAuth.UserAuthType.FINGERPRINT; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - async function testInitAndAuthFinger() { - /* 初始化密钥会话获取挑战值 */ - await publicInitFunc(srcKeyAlias, huksOptions); - /* 调用userIAM进行身份认证 */ - userIAMAuthFinger(challenge); - } - ``` +/* 集成生成密钥参数集 & 加密参数集 */ +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, +} +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, +} +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, +} +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, +} +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) +} -3. 传入认证令牌进行数据操作 +function initSession(keyAlias, huksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.initSession(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} - ```ts - /* - * 以下以SM4 128密钥的Callback操作使用为例 - */ - import huks from '@ohos.security.huks'; +async function publicInitFunc(keyAlias, huksOptions) { + console.info(`enter callback doInit`); + let throwObject = {isThrow: false}; + try { + await initSession(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); + handle = data.handle; + challenge = data.challenge; + }) + .catch((error) => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} - /* - * 确定密钥别名和封装密钥属性参数集 - */ - let srcKeyAlias = 'sm4_key_fingerprint_access'; - let IV = '1234567890123456'; - let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; - let handle; - let fingerAuthToken; - let updateResult = new Array(); - let finishOutData; - - /* 集成生成密钥参数集 & 加密参数集 */ - let propertiesEncrypt = new Array(); - propertiesEncrypt[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, - } - propertiesEncrypt[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, - } - propertiesEncrypt[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, - } - propertiesEncrypt[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - propertiesEncrypt[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, - } - propertiesEncrypt[5] = { - tag: huks.HuksTag.HUKS_TAG_IV, - value: StringToUint8Array(IV), - } - let encryptOptions = { - properties: propertiesEncrypt, - inData: new Uint8Array(new Array()) - } +function userIAMAuthFinger(huksChallenge) { + // 获取认证对象 + let auth; + try { + auth = userIAM_userAuth.getAuthInstance(huksChallenge, authType, authTrustLevel); + console.log("get auth instance success"); + } catch (error) { + console.log("get auth instance failed" + error); + } - function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); - } + // 订阅认证结果 + try { + auth.on("result", { + callback: (result) => { + /* 认证成功获取认证令牌 */ + fingerAuthToken = result.token; + } + }); + console.log("subscribe authentication event success"); +} catch (error) { + console.log("subscribe authentication event failed " + error); +} - function updateSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.updateSession(handle, huksOptions, token, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); - } +// 开始认证 +try { + auth.start(); + console.info("authV9 start auth success"); +} catch (error) { + console.info("authV9 start auth failed, error = " + error); +} +} - async function publicUpdateFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) { - console.info(`enter callback doUpdate`); - let throwObject = {isThrow: false}; - try { - await updateSession(handle, huksOptions, token, throwObject) - .then ((data) => { - console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); - } - } +async function testInitAndAuthFinger() { + /* 初始化密钥会话获取挑战值 */ + await publicInitFunc(srcKeyAlias, huksOptions); + /* 调用userIAM进行身份认证 */ + userIAMAuthFinger(challenge); +} +``` - function finishSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.finishSession(handle, huksOptions, token, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); - } +3. 传入认证令牌进行数据操作 - async function publicFinishFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) { - console.info(`enter callback doFinish`); - let throwObject = {isThrow: false}; - try { - await finishSession(handle, huksOptions, token, throwObject) - .then ((data) => { - finishOutData = data.outData; - console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); - } - } +```js +/* +* 以下以SM4 128密钥的Callback操作使用为例 +*/ +import huks from '@ohos.security.huks'; - async function testSm4Cipher() { - encryptOptions.inData = StringToUint8Array(cipherInData); - /* 传入认证令牌 */ - await publicUpdateFunc(handle, fingerAuthToken, encryptOptions); - encryptUpdateResult = updateResult; - - encryptOptions.inData = new Uint8Array(new Array()); - /* 传入认证令牌 */ - await publicFinishFunc(handle, fingerAuthToken, encryptOptions); - if (finishOutData === cipherInData) { - console.info('test finish encrypt err '); - } else { - console.info('test finish encrypt success'); - } - } - ``` +/* +* 确定密钥别名和封装密钥属性参数集 +*/ +let srcKeyAlias = 'sm4_key_fingerprint_access'; +let IV = '1234567890123456'; +let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; +let handle; +let fingerAuthToken; +let updateResult = new Array(); +let finishOutData; -### 细粒度用户身份认证访问控制 +/* 集成生成密钥参数集 & 加密参数集 */ +let propertiesEncrypt = new Array(); +propertiesEncrypt[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, +} +propertiesEncrypt[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, +} +propertiesEncrypt[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, +} +propertiesEncrypt[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +propertiesEncrypt[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, +} +propertiesEncrypt[5] = { + tag: huks.HuksTag.HUKS_TAG_IV, + value: StringToUint8Array(IV), +} +let encryptOptions = { + properties: propertiesEncrypt, + inData: new Uint8Array(new Array()) +} -该功能是基于已有[密钥访问控制](#密钥访问控制)能力的扩展,提供了基于生物特征和锁屏密码二次身份认证的细粒度访问控制能力,允许设置密钥在加密、解密、签名、验签、密钥协商、密钥派生的单个或多个场景时是否需要进行身份验证。比如,业务需要使用HUKS密钥加密保存账号密码信息等数据,要求在加密的时候不进行指纹等身份认证,解密的时候需要进行指纹等身份认证,这是就需要依赖HUKS提供细粒度的二次身份认证访问控制机制。 +function StringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} -**开发流程** +function updateSession(handle, huksOptions, token, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.updateSession(handle, huksOptions, token, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} -1. 基于用户身份认证访问控制的流程,在密钥生成阶段,通过额外指定用于细粒度用户身份认证访问控制的HuksTag:[HUKS_TAG_KEY_AUTH_PURPOSE](../reference/apis/js-apis-huks.md#hukstag)值,来指定在某种算法用途的情况下需要使用用户身份认证访问控制能力。 -2. 基于用户身份认证访问控制的流程,在密钥使用阶段,业务无需再次指定HUKS_TAG_KEY_AUTH_PURPOSE值,同用户身份认证访问控制的开发流程。 +async function publicUpdateFunc(handle, token, huksOptions) { + console.info(`enter callback doUpdate`); + let throwObject = {isThrow: false}; + try { + await updateSession(handle, huksOptions, token, throwObject) + .then ((data) => { + console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +function finishSession(handle, huksOptions, token, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.finishSession(handle, huksOptions, token, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} + +async function publicFinishFunc(handle, token, huksOptions) { + console.info(`enter callback doFinish`); + let throwObject = {isThrow: false}; + try { + await finishSession(handle, huksOptions, token, throwObject) + .then ((data) => { + finishOutData = data.outData; + console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function testSm4Cipher() { + encryptOptions.inData = StringToUint8Array(cipherInData); + /* 传入认证令牌 */ + await publicUpdateFunc(handle, fingerAuthToken, encryptOptions); + let encryptUpdateResult = updateResult; + + encryptOptions.inData = new Uint8Array(new Array()); + /* 传入认证令牌 */ + await publicFinishFunc(handle, fingerAuthToken, encryptOptions); + if (finishOutData === cipherInData) { + console.info('test finish encrypt err '); + } else { + console.info('test finish encrypt success'); + } +} +``` + +### 细粒度用户身份认证访问控制 + +该功能是基于已有[密钥访问控制](#密钥访问控制)能力的扩展,提供了基于生物特征和锁屏密码二次身份认证的细粒度访问控制能力,允许设置密钥在加密、解密、签名、验签、密钥协商、密钥派生的单个或多个场景时是否需要进行身份验证。比如,业务需要使用HUKS密钥加密保存账号密码信息等数据,要求在加密的时候不进行指纹等身份认证,解密的时候需要进行指纹等身份认证,这是就需要依赖HUKS提供细粒度的二次身份认证访问控制机制。 + +**开发流程** + +1. 基于用户身份认证访问控制的流程,在密钥生成阶段,通过额外指定用于细粒度用户身份认证访问控制的HuksTag:[HUKS_TAG_KEY_AUTH_PURPOSE](../reference/apis/js-apis-huks.md#hukstag)值,来指定在某种算法用途的情况下需要使用用户身份认证访问控制能力。 +2. 基于用户身份认证访问控制的流程,在密钥使用阶段,业务无需再次指定HUKS_TAG_KEY_AUTH_PURPOSE值,同用户身份认证访问控制的开发流程。 **接口说明** @@ -2083,421 +2087,422 @@ HUKS提供了全面完善的密钥访问控制能力,确保存储在HUKS中的 1. 生成密钥并指定指纹访问控制和相关属性,以及HUKS_TAG_KEY_AUTH_PURPOSE值 - ```ts - import huks from '@ohos.security.huks'; +```js +import huks from '@ohos.security.huks'; - /* - * 确定密钥别名和封装密钥属性参数集 - */ - let keyAlias = 'dh_key_fingerprint_access'; - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, - } - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - // 指定密钥身份认证的类型:指纹 - properties[5] = { - tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, - value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_FINGERPRINT - } - // 指定密钥安全授权的类型(失效类型):新录入生物特征(指纹)后无效 - properties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, - value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL - } - // 指定挑战值的类型:默认类型 - properties[7] = { - tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, - value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL - } - // 指定某种算法用途时需要用户身份认证访问控制:比如解密需要 - properties[8] = { - tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT - } - let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) - } +/* + * 确定密钥别名和封装密钥属性参数集 + */ +let keyAlias = 'dh_key_fingerprint_access'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, +} +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, +} +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, +} +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, +} +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +// 指定密钥身份认证的类型:指纹 +properties[5] = { + tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, + value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_FINGERPRINT +} +// 指定密钥安全授权的类型(失效类型):新录入生物特征(指纹)后无效 +properties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, + value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL +} +// 指定挑战值的类型:默认类型 +properties[7] = { + tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, + value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL +} +// 指定某种算法用途时需要用户身份认证访问控制:比如解密需要 +properties[8] = { + tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT +} +let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) +} - /* - * 生成密钥 - */ - async function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { - return new Promise((resolve, reject) => { - try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); - } +/* + * 生成密钥 + */ +async function generateKeyItem(keyAlias, huksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} - async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); - let throwObject = {isThrow: false}; - try { - await generateKeyItem(keyAlias, huksOptions, throwObject) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } - } +async function publicGenKeyFunc(keyAlias, huksOptions) { + console.info(`enter callback generateKeyItem`); + let throwObject = {isThrow: false}; + try { + await generateKeyItem(keyAlias, huksOptions, throwObject) + .then((data) => { + console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} - async function TestGenKeyForFingerprintAccessControl() { - await publicGenKeyFunc(keyAlias, huksOptions); - } - ``` +async function TestGenKeyForFingerprintAccessControl() { + await publicGenKeyFunc(keyAlias, huksOptions); +} +``` 2. 使用密钥-加密场景-加密时不需要进行用户身份认证访问控制 - ```ts +```js import huks from '@ohos.security.huks'; - /* - * 确定密钥别名和封装密钥属性参数集 - */ - let srcKeyAlias = 'sm4_key_fingerprint_access'; - let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; // 明文数据 - let IV = '1234567890123456'; - let handle; - let cipherText; // 加密后的密文数据 - - function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); - } +/* + * 确定密钥别名和封装密钥属性参数集 + */ +let srcKeyAlias = 'sm4_key_fingerprint_access'; +let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; // 明文数据 +let IV = '1234567890123456'; +let handle; +let cipherText; // 加密后的密文数据 - /* 集成生成密钥参数集 & 加密参数集 */ - let propertiesEncrypt = new Array(); - propertiesEncrypt[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, - } - propertiesEncrypt[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, - } - propertiesEncrypt[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, - } - propertiesEncrypt[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - propertiesEncrypt[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, - } - propertiesEncrypt[5] = { - tag: huks.HuksTag.HUKS_TAG_IV, - value: StringToUint8Array(IV), - } - let encryptOptions = { - properties: propertiesEncrypt, - inData: new Uint8Array(new Array()) - } +function StringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} - function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.initSession(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); - } +/* 集成生成密钥参数集 & 加密参数集 */ +let propertiesEncrypt = new Array(); +propertiesEncrypt[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, +} +propertiesEncrypt[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, +} +propertiesEncrypt[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, +} +propertiesEncrypt[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +propertiesEncrypt[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, +} +propertiesEncrypt[5] = { + tag: huks.HuksTag.HUKS_TAG_IV, + value: StringToUint8Array(IV), +} +let encryptOptions = { + properties: propertiesEncrypt, + inData: new Uint8Array(new Array()) +} - async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback doInit`); - let throwObject = {isThrow: false}; - try { - await initSession(keyAlias, huksOptions, throwObject) - .then ((data) => { - console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); - handle = data.handle; - }) - .catch((error) => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); - } - } +function initSession(keyAlias, huksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.initSession(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} - function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.finishSession(handle, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); - } +async function publicInitFunc(keyAlias, huksOptions) { + console.info(`enter callback doInit`); + let throwObject = {isThrow: false}; + try { + await initSession(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); + handle = data.handle; + }) + .catch((error) => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} - async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) { - console.info(`enter callback doFinish`); - let throwObject = {isThrow: false}; - try { - await finishSession(handle, huksOptions, throwObject) - .then ((data) => { - cipherText = data.outData; - console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); - } - } +function finishSession(handle, huksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.finishSession(handle, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} + +async function publicFinishFunc(handle, huksOptions) { + console.info(`enter callback doFinish`); + let throwObject = {isThrow: false}; + try { + await finishSession(handle, huksOptions, throwObject) + .then ((data) => { + cipherText = data.outData; + console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} - async function testSm4Cipher() { - /* 初始化密钥会话获取挑战值 */ - await publicInitFunc(srcKeyAlias, encryptOptions); +async function testSm4Cipher() { + /* 初始化密钥会话获取挑战值 */ + await publicInitFunc(srcKeyAlias, encryptOptions); - /* 加密 */ - encryptOptions.inData = StringToUint8Array(cipherInData); - await publicFinishFunc(handle, encryptOptions); - } - ``` + /* 加密 */ + encryptOptions.inData = StringToUint8Array(cipherInData); + await publicFinishFunc(handle, encryptOptions); +} +``` 3. 使用密钥-解密场景-解密时需要进行用户身份认证访问控制 - ```ts +```js import huks from '@ohos.security.huks'; - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - /* - * 确定密钥别名和封装密钥属性参数集 - */ - let srcKeyAlias = 'sm4_key_fingerprint_access'; - let cipherText = 'r56ywtTJUQC6JFJ2VV2kZw=='; // 加密时得到的密文数据, 业务需根据实际加密结果修改 - let IV = '1234567890123456'; - let handle; - let finishOutData; // 解密后的明文数据 - let fingerAuthToken; - let authType = userIAM_userAuth.UserAuthType.FINGERPRINT; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - - function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); - } +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - /* 集成生成密钥参数集 & 加密参数集 */ - let propertiesDecrypt = new Array(); - propertiesDecrypt[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, - } - propertiesDecrypt[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, - } - propertiesDecrypt[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, - } - propertiesDecrypt[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - propertiesDecrypt[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, - } - propertiesDecrypt[5] = { - tag: huks.HuksTag.HUKS_TAG_IV, - value: StringToUint8Array(IV), - } - let decryptOptions = { - properties: propertiesDecrypt, - inData: new Uint8Array(new Array()) - } +/* + * 确定密钥别名和封装密钥属性参数集 + */ +let srcKeyAlias = 'sm4_key_fingerprint_access'; +let cipherText = 'r56ywtTJUQC6JFJ2VV2kZw=='; // 加密时得到的密文数据, 业务需根据实际加密结果修改 +let IV = '1234567890123456'; +let handle; +let finishOutData; // 解密后的明文数据 +let fingerAuthToken; +let challenge; +let authType = userIAM_userAuth.UserAuthType.FINGERPRINT; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.initSession(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); - } +function StringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} - async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback doInit`); - let throwObject = {isThrow: false}; - try { - await initSession(keyAlias, huksOptions, throwObject) - .then ((data) => { - console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); - handle = data.handle; - challenge = data.challenge; - }) - .catch((error) => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); - } - } +/* 集成生成密钥参数集 & 加密参数集 */ +let propertiesDecrypt = new Array(); +propertiesDecrypt[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, +} +propertiesDecrypt[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, +} +propertiesDecrypt[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, +} +propertiesDecrypt[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +propertiesDecrypt[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, +} +propertiesDecrypt[5] = { + tag: huks.HuksTag.HUKS_TAG_IV, + value: StringToUint8Array(IV), +} +let decryptOptions = { + properties: propertiesDecrypt, + inData: new Uint8Array(new Array()) +} - function userIAMAuthFinger(huksChallenge:Uint8Array) { - // 获取认证对象 - let auth; - try { - auth = userIAM_userAuth.getAuthInstance(huksChallenge, authType, authTrustLevel); - console.log("get auth instance success"); - } catch (error) { - console.log("get auth instance failed" + error); - } - - // 订阅认证结果 - try { - auth.on("result", { - callback: (result: userIAM_userAuth.AuthResultInfo) => { - /* 认证成功获取认证令牌 */ - fingerAuthToken = result.token; - } - }); - console.log("subscribe authentication event success"); - } catch (error) { - console.log("subscribe authentication event failed " + error); - } - - // 开始认证 - try { - auth.start(); - console.info("authV9 start auth success"); - } catch (error) { - console.info("authV9 start auth failed, error = " + error); - } - } +function initSession(keyAlias, huksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.initSession(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} - function finishSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.finishSession(handle, huksOptions, token, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); - } +async function publicInitFunc(keyAlias, huksOptions) { + console.info(`enter callback doInit`); + let throwObject = {isThrow: false}; + try { + await initSession(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); + handle = data.handle; + challenge = data.challenge; + }) + .catch((error) => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} - async function publicFinishFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) { - console.info(`enter callback doFinish`); - let throwObject = {isThrow: false}; - try { - await finishSession(handle, huksOptions, token, throwObject) - .then ((data) => { - finishOutData = data.outData; - console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); - } - } +function userIAMAuthFinger(huksChallenge) { + // 获取认证对象 + let auth; + try { + auth = userIAM_userAuth.getAuthInstance(huksChallenge, authType, authTrustLevel); + console.log("get auth instance success"); + } catch (error) { + console.log("get auth instance failed" + error); + } + + // 订阅认证结果 + try { + auth.on("result", { + callback: (result) => { + /* 认证成功获取认证令牌 */ + fingerAuthToken = result.token; + } + }); + console.log("subscribe authentication event success"); +} catch (error) { + console.log("subscribe authentication event failed " + error); +} - async function testSm4Cipher() { - /* 初始化密钥会话获取挑战值 */ - await publicInitFunc(srcKeyAlias, decryptOptions); +// 开始认证 +try { + auth.start(); + console.info("authV9 start auth success"); +} catch (error) { + console.info("authV9 start auth failed, error = " + error); +} +} - /* 调用userIAM进行身份认证 */ - userIAMAuthFinger(challenge); +function finishSession(handle, huksOptions, token, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.finishSession(handle, huksOptions, token, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} - /* 认证成功后进行解密, 需要传入Auth获取到的authToken值 */ - decryptOptions.inData = StringToUint8Array(cipherText); - await publicFinishFunc(handle, fingerAuthToken, decryptOptions); - } - ``` +async function publicFinishFunc(handle, token, huksOptions) { + console.info(`enter callback doFinish`); + let throwObject = {isThrow: false}; + try { + await finishSession(handle, huksOptions, token, throwObject) + .then ((data) => { + finishOutData = data.outData; + console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function testSm4Cipher() { + /* 初始化密钥会话获取挑战值 */ + await publicInitFunc(srcKeyAlias, decryptOptions); + + /* 调用userIAM进行身份认证 */ + userIAMAuthFinger(challenge); + + /* 认证成功后进行解密, 需要传入Auth获取到的authToken值 */ + decryptOptions.inData = StringToUint8Array(cipherText); + await publicFinishFunc(handle, fingerAuthToken, decryptOptions); +} +``` ## 密钥证明 @@ -2518,7 +2523,7 @@ HUKS为密钥提供合法性证明能力,主要应用于非对称密钥的公 **开发步骤** -```ts +```js /* * 以下以attestKey Callback接口操作验证为例 */ @@ -2601,7 +2606,7 @@ function StringToUint8Array(str) { return new Uint8Array(arr); } -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { +function generateKeyItem(keyAlias, huksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { @@ -2618,7 +2623,7 @@ function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObj }); } -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { +async function publicGenKeyFunc(keyAlias, huksOptions) { console.info(`enter callback generateKeyItem`); let throwObject = {isThrow: false}; try { @@ -2638,7 +2643,7 @@ async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { } } -function attestKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise{ +function attestKeyItem(keyAlias, huksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.attestKeyItem(keyAlias, huksOptions, function (error, data) { @@ -2655,7 +2660,7 @@ function attestKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObjec }); } -async function publicAttestKey(keyAlias:string, huksOptions:huks.HuksOptions) { +async function publicAttestKey(keyAlias, huksOptions) { console.info(`enter callback attestKeyItem`); let throwObject = {isThrow: false}; try { diff --git a/zh-cn/application-dev/task-management/work-scheduler.md b/zh-cn/application-dev/task-management/work-scheduler.md index ddbe25b05d0a26a0287a3572b2f55c191ce5241b..484f68b5b93cf0b33a2e8e9cf0f86a2c3181694f 100644 --- a/zh-cn/application-dev/task-management/work-scheduler.md +++ b/zh-cn/application-dev/task-management/work-scheduler.md @@ -151,7 +151,7 @@ WorkInfo参数用于设置应用条件,参数设置时需遵循以下规则: "extensionAbilities": [ { "name": "MyWorkSchedulerExtensionAbility", - "srcEntry": "./ets/WorkSchedulerExtension/WorkSchedulerExtension.ts", + "srcEntry": "./ets/WorkSchedulerExtension/WorkSchedulerExtension.ets", "label": "$string:WorkSchedulerExtensionAbility_label", "description": "$string:WorkSchedulerExtensionAbility_desc", "type": "workScheduler" diff --git a/zh-cn/application-dev/ui/arkts-animation.md b/zh-cn/application-dev/ui/arkts-animation.md index 80de9162b5467d2d7db93d55d99572e653a07a31..8c7bdfb5998118f5001ca65e01a85ea8a6a0431c 100644 --- a/zh-cn/application-dev/ui/arkts-animation.md +++ b/zh-cn/application-dev/ui/arkts-animation.md @@ -4,8 +4,19 @@ UI(用户界面)中包含开发者与设备进行交互时所看到的各种组件(如时间、壁纸等)。属性作为接口,用于控制组件的行为。例如,开发者可通过位置属性调整组件在屏幕上的位置。 -属性值的变化,通常会引起UI的变化。动画可在UI发生改变时,添加流畅的过渡效果。以应用启动为例,当用户点击应用图标时,应用窗口应取代桌面,作为屏幕的主要显示内容。如果不添加动画,相关属性将在一瞬间完成变化,应用窗口直接替换桌面,出现不连贯的视觉感受。动画可以解决UI变化时在视觉上不连续的问题。 +属性值的变化,通常会引起UI的变化。动画可在UI发生改变时,添加流畅的过渡效果。如果不加入动画,属性将在一瞬间完成变化。造成突兀感的同时,容易导致用户失去视觉焦点。 +![zh-cn_image_20230822](figures/zh-cn_image_20230822.gif) + +动画的目的包括: + +- 使界面的过渡自然流畅。 +- 增强用户从界面获得的反馈感和互动感。 +- 在内容加载等场景中,增加用户的耐心,缓解等待带来的不适感。 +- 引导用户了解和操作设备。 + + +在需要为UI变化添加过渡的场景,都可以使用动画,如开机、应用启动退出、下拉进入控制中心等。这些动画可向用户提供关于其操作的反馈,并有助于让用户始终关注界面。 ArkUI中提供多种动画接口(属性动画、转场动画等),用于驱动属性值按照设定的动画参数,从起始值逐渐变化到终点值。尽管变化过程中参数值并非绝对的连续,而是具有一定的离散性。但由于人眼会产生视觉暂留,所以最终看到的就是一个“连续“的动画。UI的一次改变称为一个动画帧,对应一次屏幕刷新。决定动画流畅度的一个重要指标就是帧率FPS(Frame Per Second),即每秒的动画帧数,帧率越高则动画就会越流畅。ArkUI中,动画参数包含了如动画时长、动画曲线等参数。动画曲线作为主要因素,决定了属性值变化的规律。以线性动画曲线为例,在动画时长内,属性值将从起点值匀速变化到终点值。属性过快或过慢的变化,都可能带来不好的视觉感受,影响用户体验。因此动画参数特别是动画曲线,需要结合场景和曲线特点进行设计和调整。 @@ -20,8 +31,8 @@ ArkUI中提供多种动画接口(属性动画、转场动画等),用于驱 - 属性动画:最基础的动画类型,按照动画参数逐帧驱动属性的变化,产生一帧帧的动画效果。 - 转场动画:为组件在出现和消失时添加过渡动画。为了保证动画一致性,部分接口动画曲线已内置,不支持开发者自定义。 - - 不推荐使用Ability去组合界面:Ability是一个任务,会在多任务界面独立显示一个卡片,Ability之间的跳转是任务之间的跳转。以应用内查看大图的典型场景为例,不建议应用内调用图库Ability去打开图片查看大图,会导致任务的跳转,图库Ability也会加入多任务界面中。正确的方式是应用内构建大图组件,通过模态转场去调起大图组件,所有的界面都在一个Ability内闭环。 - - 使用Navigation组件实现导航,不要使用page导航方式。page+router方式会导致页面之间的割裂,不利于实现联动的转场效果,并且不支持一次开发多端部署。 + - 不推荐在应用内使用UIAbility组合所有的界面:UIAbility是一个任务,会在多任务界面独立显示一个卡片,UIAbility之间的跳转是任务之间的跳转。以应用内查看大图的典型场景为例,不建议应用内调用图库的UIAbility去打开图片查看大图,会导致任务的跳转,图库的UIAbility也会加入多任务界面中。正确的方式是应用内构建大图组件,通过模态转场去调起大图组件,一个任务内的所有的界面都在一个UIAbility内闭环。 + - 导航转场中,应使用Navigation组件实现转场动画。过去的page+router方式在实现导航转场过程中,因为page和page之间相互独立,其联动动画效果受限。不仅容易导致页面之间的割裂,并且不支持一次开发多端部署。 - 组件动画:组件提供默认动效(如List的滑动动效)便于开发者使用,同时部分组件还支持定制化动效。 diff --git a/zh-cn/application-dev/ui/arkts-component-animation.md b/zh-cn/application-dev/ui/arkts-component-animation.md index dcce81d8180d68035cbfc220571be840df0e73c6..831132f9b4f194a7f1ebadce6e4f1d0a2c4ce069 100644 --- a/zh-cn/application-dev/ui/arkts-component-animation.md +++ b/zh-cn/application-dev/ui/arkts-component-animation.md @@ -224,7 +224,6 @@ export const taskDataArr: Array = export struct TaskSwitchMainPage { displayWidth: number = WindowManager.getInstance().getDisplayWidth(); scroller: Scroller = new Scroller(); - bgImage: Resource = $r('app.media.share'); cardSpace: number = 0; // 卡片间距 cardWidth: number = this.displayWidth / 2 - this.cardSpace / 2; // 卡片宽度 cardHeight: number = 400; // 卡片高度 diff --git a/zh-cn/application-dev/ui/arkts-enter-exit-transition.md b/zh-cn/application-dev/ui/arkts-enter-exit-transition.md index 1077e0de31361cafa07788b85ffc4ab14447cdb8..0d7f6e774940a5b8b8d886bcd0a7e1f08ab87a80 100644 --- a/zh-cn/application-dev/ui/arkts-enter-exit-transition.md +++ b/zh-cn/application-dev/ui/arkts-enter-exit-transition.md @@ -67,7 +67,7 @@ ``` - 完整的示例代码和效果如下。 + 完整的示例代码和效果如下: ```ts import curves from '@ohos.curves'; diff --git a/zh-cn/application-dev/ui/arkts-graphics-display.md b/zh-cn/application-dev/ui/arkts-graphics-display.md index 5490c8c570244a14b8a88edc0f42b962c1d9d612..0596121209e9d63213c9e02210b0f2a16dd96291 100644 --- a/zh-cn/application-dev/ui/arkts-graphics-display.md +++ b/zh-cn/application-dev/ui/arkts-graphics-display.md @@ -75,17 +75,15 @@ Image支持加载存档图、多媒体像素图两种类型。 支持file://路径前缀的字符串,用于访问通过媒体库提供的图片路径。 1. 调用接口获取图库的照片url。 - ​ ```ts import picker from '@ohos.file.picker'; - + @Entry @Component struct Index { @State imgDatas: string[] = []; // 获取照片url集 getAllImg() { - let photoPicker = new picker.PhotoViewPicker(); let result = new Array(); try { let PhotoSelectOptions = new picker.PhotoSelectOptions(); @@ -101,7 +99,7 @@ Image支持加载存档图、多媒体像素图两种类型。 } catch (err) { console.error(`PhotoViewPicker failed with. Code: ${err.code}, message: ${err.message}`); } } - + // aboutToAppear中调用上述函数,获取图库的所有图片url,存在imgDatas中 async aboutToAppear() { this.getAllImg(); @@ -121,8 +119,8 @@ Image支持加载存档图、多媒体像素图两种类型。 } } ``` + 2. 从媒体库获取的url格式通常如下。 - ​ ```ts Image('file://media/Photos/5') .width(200) @@ -150,14 +148,12 @@ PixelMap是图片解码后的像素图,具体用法请参考[图片开发指 请求网络图片请求,解码编码PixelMap。 1. 引用网络权限与媒体库权限。 - ​ ```ts import http from '@ohos.net.http'; import ResponseCode from '@ohos.net.http'; import image from '@ohos.multimedia.image'; ``` 2. 填写网络图片地址。 - ​ ```ts http.createHttp().request("https://www.example.com/xxx.png", (error, data) => { @@ -168,25 +164,24 @@ PixelMap是图片解码后的像素图,具体用法请参考[图片开发指 } ) ``` - 3. 将网络地址成功返回的数据,编码转码成pixelMap的图片格式。 - ​ + 3. 将网络地址成功返回的数据,编码转码成pixelMap的图片格式。 ```ts let code = data.responseCode; - if(ResponseCode.ResponseCode.OK === code) { + if (ResponseCode.ResponseCode.OK === code) { let imageSource = image.createImageSource(data.result); let options = { - alphaType: 0, // 透明度 - editable: false, // 是否可编辑 - pixelFormat: 3, // 像素格式 - scaleMode: 1, // 缩略值 - size: {height: 100, width: 100} - } // 创建图片大小 - imageSource.createPixelMap(options).then((pixelMap) => { + alphaType: 0, // 透明度 + editable: false, // 是否可编辑 + pixelFormat: 3, // 像素格式 + scaleMode: 1, // 缩略值 + size: { height: 100, width: 100 } + } // 创建图片大小 + imageSource.createPixelMap(options).then((pixelMap) => { this.image = pixelMap - }) + }) + } ``` 4. 显示图片。 - ​ ```ts Button("获取网络图片") .onClick(() => { diff --git a/zh-cn/application-dev/ui/arkts-layout-development-create-list.md b/zh-cn/application-dev/ui/arkts-layout-development-create-list.md index 7f66bea51141aa539b71807f93dd0f8a28cee2ce..bbf53685abd2f1143dc0dc88224df6f9d44d997c 100644 --- a/zh-cn/application-dev/ui/arkts-layout-development-create-list.md +++ b/zh-cn/application-dev/ui/arkts-layout-development-create-list.md @@ -46,7 +46,7 @@ List除了提供垂直和水平布局能力、超出屏幕时可以滚动的自 列表的主轴方向是指子组件列的排列方向,也是列表的滚动方向。垂直于主轴的轴称为交叉轴,其方向与主轴方向相互垂直。 -如下图所示,垂直列表的主轴是垂直方向,交叉轴是水平方向;水平列表的主轴是水平方向,交叉轴是水平方向。 +如下图所示,垂直列表的主轴是垂直方向,交叉轴是水平方向;水平列表的主轴是水平方向,交叉轴是垂直方向。 **图4** 列表的主轴与交叉轴   diff --git a/zh-cn/application-dev/ui/arkts-layout-development-linear.md b/zh-cn/application-dev/ui/arkts-layout-development-linear.md index 38585141a0bb6a64e595c277658cf55342cf9821..f1a3c194d2254eeb8fd9bbf79ec6e33b05a324c9 100644 --- a/zh-cn/application-dev/ui/arkts-layout-development-linear.md +++ b/zh-cn/application-dev/ui/arkts-layout-development-linear.md @@ -76,7 +76,7 @@ Row({ space: 35 }) { 在布局容器内,可以通过alignItems属性设置子元素在交叉轴(排列方向的垂直方向)上的对齐方式。且在各类尺寸屏幕中,表现一致。其中,交叉轴为垂直方向时,取值为[VerticalAlign类型](../reference/arkui-ts/ts-appendix-enums.md#verticalalign),水平方向取值为[HorizontalAlign](../reference/arkui-ts/ts-appendix-enums.md#horizontalalign)。 -alignSelf属性用于控制单个子元素在容器主轴上的对齐方式,其优先级高于alignItems属性,如果设置了alignSelf属性,则在单个子元素上会覆盖alignItems属性。 +alignSelf属性用于控制单个子元素在容器交叉轴上的对齐方式,其优先级高于alignItems属性,如果设置了alignSelf属性,则在单个子元素上会覆盖alignItems属性。 ### Column容器内子元素在水平方向上的排列 diff --git a/zh-cn/application-dev/ui/arkts-layout-development-relative-layout.md b/zh-cn/application-dev/ui/arkts-layout-development-relative-layout.md index 3e3b9afbf2e9df811d8cd399528cfd3f7a8b9327..956b221c9bb04194c81bb61254a4480472cce763 100644 --- a/zh-cn/application-dev/ui/arkts-layout-development-relative-layout.md +++ b/zh-cn/application-dev/ui/arkts-layout-development-relative-layout.md @@ -26,7 +26,7 @@ ### 锚点设置 -锚点设置是指设置子元素相对于父元素或兄弟元素的位置依赖关系。在水平方向上,可以设置left、middle、right的锚点。在竖直方向上,可以设置top、center、bottom的锚点。为了明确定义锚点,必须为RelativeContainer及其子元素设置ID,用于指定锚点信息。ID默认为“container”,其余子元素的ID通过id属性设置。未设置ID的子元素在RelativeContainer中不会显示。 +锚点设置是指设置子元素相对于父元素或兄弟元素的位置依赖关系。在水平方向上,可以设置left、middle、right的锚点。在竖直方向上,可以设置top、center、bottom的锚点。为了明确定义锚点,必须为RelativeContainer及其子元素设置ID,用于指定锚点信息。ID默认为“__container__”,其余子元素的ID通过id属性设置。未设置ID的子元素在RelativeContainer中不会显示。 >**说明:** > diff --git a/zh-cn/application-dev/ui/arkts-navigation-transition.md b/zh-cn/application-dev/ui/arkts-navigation-transition.md index 9dc638b55139e336dc4732705aadfdd3496a968a..9001828b0b4ba8d14fa1e988c71e5628991dac1d 100644 --- a/zh-cn/application-dev/ui/arkts-navigation-transition.md +++ b/zh-cn/application-dev/ui/arkts-navigation-transition.md @@ -12,13 +12,81 @@ ```ts +@Component +export struct MyFirstIndex { + @Consume('pathInfos') pathInfos: NavPathStack + name: string = '' + @State value: string = '' + + build() { + NavDestination() { + Column() { + Blank() + Text('通过点击NavRouter区域进入导航目标页面' + this.value) + .fontStyle(FontStyle.Italic) + .lineHeight(35) + .fontSize(25) + .fontColor(Color.Black) + .textAlign(TextAlign.Center) + .letterSpacing(5) + .textShadow({ radius: 2, offsetX: 4, offsetY: 4, color: 0x909399 }) + .padding({ left: 30, right: 30 }) + + Blank() + + Button('返回上级页面') + .backgroundColor(Color.Black) + .onClick(() => { + this.pathInfos.pop() + }) + Blank() + } + .size({ width: '100%', height: '100%' }) + }.title(this.name + '二级页面') + } +} + +@Component +export struct MySecondIndex { + @Consume('pathInfos') pathInfos: NavPathStack; + name: String = ''; + @State value: String = '' + + build() { + NavDestination() { + Column() { + Blank() + Text('通过更新路由栈数据对象进入导航目标界面' + this.value) + .fontStyle(FontStyle.Italic) + .lineHeight(35) + .fontSize(25) + .fontColor(Color.Black) + .textAlign(TextAlign.Center) + .letterSpacing(5) + .textShadow({ radius: 2, offsetX: 4, offsetY: 4, color: 0x909399 }) + .padding({ left: 30, right: 30 }) + + Blank() + + Button('返回上级页面') + .backgroundColor(Color.Black) + .onClick(() => { + this.pathInfos.pop() + }) + Blank() + } + .size({ width: '100%', height: '100%' }) + }.title(this.name + '二级页面') + } +} + @Entry @Component struct NavigationDemo { - private listArray: Array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + @Provide('pathInfos') pathInfos: NavPathStack = new NavPathStack() + private listArray: Array = [0, 1, 2] - // 设置标题栏菜单组件,如果不需要标题栏组件,可以不设置 - @Builder NavigationMenus() { + @Builder NavPathStack() { Column() { Text('menu') .fontColor('#182431') @@ -30,102 +98,103 @@ struct NavigationDemo { .alignItems(HorizontalAlign.Start) } + // Navigation的navDestination属性方法设置的构造函数,在路由栈变化时触发该构建数创建新的路由页面 + @Builder myRouter(name: string, param: string) { + if (name == '方式一进入') { + MyFirstIndex({ name: name, value: param }) + } + if (name == '方式二进入') { + MySecondIndex({ name: name, value: param }) + } + } + build() { - Stack() { - Column() { - // 定义Navigation组件,设置显示模式,设置标题 - Navigation() { - // 这里定义了一个输入法框组件 - TextInput({ placeholder: 'search...' }) - .width('90%') - .height(40) - .backgroundColor('#ededed') - .margin({ bottom: 10 }) - - // 通过List定义导航的一级界面 - List({ space: 12, initialIndex: 0 }) { - ForEach(this.listArray, (item) => { - ListItem() { - // 通过NavRouter定义导航转场,通过NavDestination定义导航目标界面,界面之间通过组件间的状态变量或者普通变量传递参数 - // NavRouter必须包含两个子组件,第一个组件是导航一级界面,第二个子组件必须为NavDestination为导航目标界面 - NavRouter() { - // 第一个组件:导航的一级界面显示的组件 + Column() { + Navigation(this.pathInfos) { + TextInput({ placeholder: 'search...' }) + .width('90%') + .height(40) + .margin({ bottom: 10 }) + + // 通过List定义导航的一级界面 + List({ space: 12, initialIndex: 0 }) { + ForEach(this.listArray, (item) => { + ListItem() { + // 通过NavDestination定义导航目标界面,界面之间同故宫组件间的状态变量或者普通变量传递参数 + // NavRouter点击之后会传递name和param参数给Navigation的navDestination书香方法设置的builder函数(myRouter) + NavRouter({ name: '方式一进入', param: '' + item }) { + Row() { Row() { - Row() - .width(40) - .height(40) - .backgroundColor('#a8a8a8') - .margin({ right: 12 }) - .borderRadius(20) - - Column() { - Text('导航一级页面') - .fontSize(16) - .lineHeight(21) - .fontWeight(FontWeight.Medium) - Text('点击跳转目标子页面') - .fontSize(13) - .lineHeight(21) - .fontColor('#a8a8a8') - } - .alignItems(HorizontalAlign.Start) - - Blank() - - Row() - .width(15) - .height(15) - .margin({ right: 12 }) - .border({ - width: { top: 2, right: 2 }, - color: 0xcccccc - }) - .rotate({ angle: 45 }) + Text('' + item) + .fontColor(Color.White) + .fontSize(15) + .fontWeight(FontWeight.Bold) } - .borderRadius(15) - .shadow({ radius: 100, color: '#ededed' }) - .width('90%') - .alignItems(VerticalAlign.Center) - .padding({ left: 16, top: 12, bottom: 12 }) - .height(80) - - // 第二个组件:导航的目的界面 - NavDestination() { - // 目的界面的内容,这里一般为自定义的Component - Column() { - Text("导航目标页面" + item + "内容") - .fontSize(20) - .fontColor(Color.Black) - .textAlign(TextAlign.Center) - .width('100%') - .height('100%') - } - .width('100%') - .height('100%') - .backgroundColor(0xf5f5f5) + .width(40) + .height(40) + .backgroundColor('#a8a8a8') + .margin({ right: 12 }) + .borderRadius(20) + .justifyContent(FlexAlign.Center) + + Column() { + Text('导航一级页面') + .fontSize(16) + .lineHeight(21) + .fontWeight(FontWeight.Medium) + Text('点击跳转目标子页面' + item) + .fontSize(13) + .lineHeight(21) + .fontColor('#a8a8a8') } - .title('导航目标页面') // 这里定义二级界面的标题 + .alignItems(HorizontalAlign.Start) + + Blank() + + Row() + .width(15) + .height(15) + .margin({ right: 12 }) + .border({ + width: { top: 2, right: 2 }, + color: 0xcccccc + }) + .rotate({ angle: 45 }) } + .borderRadius(15) + .shadow({ radius: 100, color: '#ededed' }) + .width('90%') + .alignItems(VerticalAlign.Center) + .padding({ left: 16, top: 12, bottom: 12 }) + .height(80) + .backgroundColor(Color.White) } - .width('100%') - }, item => item) - } - .listDirection(Axis.Vertical) - .edgeEffect(EdgeEffect.Spring) - .sticky(StickyStyle.Header) - .chainAnimation(false) - .borderRadius(15) - .width('100%') - .height('100%') + } + .width('100%') + }, item => item) } + .listDirection(Axis.Vertical) + .edgeEffect(EdgeEffect.Spring) + .sticky(StickyStyle.Header) + .chainAnimation(false) .width('100%') - .mode(NavigationMode.Auto) // 设置显示模式为Auto - .title('导航转场') // 设置标题文字 - .titleMode(NavigationTitleMode.Full) // 设置标题栏模式 - .menus(this.NavigationMenus) // 设置标题栏菜单 + + Column() + .height('20%') + + Button('点击进入下一页') + .onClick(() => { + // 通过操作绑定的路由栈数据对象触发Navigation更新,基于pathInfos数据变化场景触发navDestination属性方法构建新页面 + this.pathInfos.pushPathByName('方式二进入', 4) + }) } + .navDestination(this.myRouter) .width('100%') + .mode(NavigationMode.Auto) + .title('导航转场') // 设置标题文字 } + .size({ width: '100%', height: '100%' }) + .backgroundColor(0xf4f4f5) } } ``` diff --git a/zh-cn/application-dev/ui/arkts-routing.md b/zh-cn/application-dev/ui/arkts-routing.md index 5d8c695164a196439205fd53ca42fc9caf99db47..70b5d3f6c3b3468e97be44235a2fe5002e4cc219 100644 --- a/zh-cn/application-dev/ui/arkts-routing.md +++ b/zh-cn/application-dev/ui/arkts-routing.md @@ -342,6 +342,7 @@ import router from '@ohos.router'; ```ts // library/src/main/ets/pages/Index.ets +// library为新建共享包自定义的名字 @Entry({ routeName : 'myPage' }) @Component struct MyComponent { @@ -353,7 +354,7 @@ struct MyComponent { ```ts // entry/src/main/ets/pages/Index.ets import router from '@ohos.router'; -import 'library/src/main/ets/Index.ets' // 引入共享包library中的命名路由页面 +import 'library/src/main/ets/pages/Index.ets' // 引入共享包library中的命名路由页面 @Entry @Component diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001562700449.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001562700449.png index 9c2b84e0e070e67613504dcb52ea02acb6ed72b9..da349d8e58a9acbf6375ab921261ffcacdde9c5d 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001562700449.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001562700449.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001562820813.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001562820813.png index 20ddfe6941c5313b1054f1d479da8b24014c3928..f115a300f68cf764d3e29115f803741a5a3f973a 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001562820813.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001562820813.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001562940505.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001562940505.png index 3fc091e4e68bf1ef8c57ad082549e88b31d94caf..1cde8cb357d9c80cfeaa08e5e796f02ad1ff763e 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001562940505.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001562940505.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001588458252.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001588458252.gif index cf42cf73d80c25d5907aa105a5763ad9dc2cee2d..e1f95fe85496ec749ec080b6d4ff1898ff66f236 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001588458252.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001588458252.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_20230822.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_20230822.gif new file mode 100644 index 0000000000000000000000000000000000000000..f2be85c6d1f7deddaf8bc6081d7b715b7c222ba2 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/zh-cn_image_20230822.gif differ diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.11.2/changelogs-arkui.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.11.2/changelogs-arkui.md index b0e987b22466f2d09653dd8d4229b510ca8281e7..6ab192ac0f474e237a7419292937ab66c78a909d 100644 --- a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.11.2/changelogs-arkui.md +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.11.2/changelogs-arkui.md @@ -10,3 +10,11 @@ **关键的接口变更** PanelHeight枚举的WRAP_CONTENT值从0变为'wrapContent',接口行为变更对开发者无影响。 + +## cl.arkui.2 aspectRatio设置非法值和undefined时,默认值从1.0变为null。 + +**变更影响** + +变更前,开发者设置负数和undefined,aspectRatio = 1.0 + +变更后,开发者设置负数和undefined,aspectRatio为null。例如,Row只设置宽度且没有子组件,aspectRatio不设置值或者设置成负数时,此时Row高度为0。