提交 5c9ffd0b 编写于 作者: 关明月 提交者: Gitee

Merge branch 'master' of gitee.com:openharmony/docs into master

...@@ -85,14 +85,19 @@ zh-cn/device-dev/subsystems/subsys-security-sigverify.md @duangavin123_admin ...@@ -85,14 +85,19 @@ zh-cn/device-dev/subsystems/subsys-security-sigverify.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-security-rightmanagement.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-security-rightmanagement.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-security-communicationverify.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-security-communicationverify.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-security-devicesecuritylevel.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-security-devicesecuritylevel.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-boot-overview.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-init.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-appspawn.md @Austin23 zh-cn/device-dev/subsystems/subsys-boot-appspawn.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-appspawn-standard.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-bootstrap.md @Austin23 zh-cn/device-dev/subsystems/subsys-boot-bootstrap.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-syspara.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-faqs.md @Austin23 zh-cn/device-dev/subsystems/subsys-boot-faqs.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-init-cfg.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-init-jobs.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-init-plugin.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-init-sandbox.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-init-service.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-init-sysparam.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-init.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-overview.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-ref.md @Austin23 zh-cn/device-dev/subsystems/subsys-boot-ref.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot.md @Austin23
zh-cn/device-dev/subsystems/subsys-testguide-test.md @Austin23 zh-cn/device-dev/subsystems/subsys-testguide-test.md @Austin23
zh-cn/device-dev/subsystems/subsys-dfx-overview.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-dfx-overview.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-dfx-hilog-rich.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-dfx-hilog-rich.md @duangavin123_admin
......
此差异已折叠。
...@@ -4,8 +4,8 @@ An ability is the abstraction of a functionality that an application can provide ...@@ -4,8 +4,8 @@ An ability is the abstraction of a functionality that an application can provide
The ability framework model has two forms. The ability framework model has two forms.
- FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there are Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities. - FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there is Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities.
- Stage model, which is introduced since API version 9. In the stage model, there are Ability and ExtensionAbility. The ExtensionAbility is further extended to ServiceExtensionAbility, FormExtensionAbility, DataShareExtensionAbility, and more. - Stage model, which is introduced since API version 9. In the stage model, there is `Ability` and `ExtensionAbility`. `ExtensionAbility` is further extended to `ServiceExtensionAbility`, `FormExtensionAbility`, `DataShareExtensionAbility`, and more.
The stage model is designed to make it easier to develop complex applications in the distributed environment. The table below lists the design differences between the two models. The stage model is designed to make it easier to develop complex applications in the distributed environment. The table below lists the design differences between the two models.
......
...@@ -54,8 +54,14 @@ To make you better understand how functions work together and jumpstart your app ...@@ -54,8 +54,14 @@ To make you better understand how functions work together and jumpstart your app
API references encompass all components and APIs available in OpenHarmony, helping you use and integrate APIs more effectively. API references encompass all components and APIs available in OpenHarmony, helping you use and integrate APIs more effectively.
They are organized as follows: They are organized as follows:
- [JS and TS APIs](reference/apis/js-apis-DataUriUtils.md)
- Native APIs - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
- [Standard Library](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md) - [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- [JS and TS APIs](reference/apis/js-apis-DataUriUtils.md)
- Native APIs
- [Standard Library](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md)
...@@ -8,37 +8,11 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat ...@@ -8,37 +8,11 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat
**Table 1** Native IPC APIs **Table 1** Native IPC APIs
<a name="table178849240013"></a> | Class/Interface | Function | Description |
<table><thead align="left"><tr id="row6884924608"><th class="cellrowborder" valign="top" width="14.12141214121412%" id="mcps1.2.4.1.1"><p id="p98846241706"><a name="p98846241706"></a><a name="p98846241706"></a>Class/Interface</p> | --------------- | -------- | ----------- |
</th> | IRemoteBroker | sptr<IRemoteObject> AsObject() | Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of **IRemoteBroker**. If you call this method on the stub, the **RemoteObject** is returned; if you call this method on the proxy, the proxy object is returned. |
<th class="cellrowborder" valign="top" width="52.54525452545254%" id="mcps1.2.4.1.2"><p id="p1488482414020"><a name="p1488482414020"></a><a name="p1488482414020"></a>Function</p> | IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) | Called to process a request from the proxy and return the result. Derived classes need to override this method. |
</th> | IRemoteProxy | | Service proxy classes are derived from the **IRemoteProxy** class. |
<th class="cellrowborder" valign="top" width="33.33333333333333%" id="mcps1.2.4.1.3"><p id="p388516244016"><a name="p388516244016"></a><a name="p388516244016"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row15885824402"><td class="cellrowborder" valign="top" width="14.12141214121412%" headers="mcps1.2.4.1.1 "><p id="p08859241008"><a name="p08859241008"></a><a name="p08859241008"></a>IRemoteBroker</p>
</td>
<td class="cellrowborder" valign="top" width="52.54525452545254%" headers="mcps1.2.4.1.2 "><p id="p388572412010"><a name="p388572412010"></a><a name="p388572412010"></a>sptr&lt;IRemoteObject&gt; AsObject()</p>
</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.3 "><p id="p13885724405"><a name="p13885724405"></a><a name="p13885724405"></a>Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of <strong id="b18927631105113"><a name="b18927631105113"></a><a name="b18927631105113"></a>IRemoteBroker</strong>. If you call this method on the stub, the <strong id="b7932163110519"><a name="b7932163110519"></a><a name="b7932163110519"></a>RemoteObject</strong> is returned; if you call this method on the proxy, the proxy object is returned.</p>
</td>
</tr>
<tr id="row138859241808"><td class="cellrowborder" valign="top" width="14.12141214121412%" headers="mcps1.2.4.1.1 "><p id="p1888515245012"><a name="p1888515245012"></a><a name="p1888515245012"></a>IRemoteStub</p>
</td>
<td class="cellrowborder" valign="top" width="52.54525452545254%" headers="mcps1.2.4.1.2 "><p id="p1388516240011"><a name="p1388516240011"></a><a name="p1388516240011"></a>virtual int OnRemoteRequest(uint32_t code, MessageParcel &amp;data, MessageParcel &amp;reply, MessageOption &amp;option)</p>
</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.3 "><p id="p1188582414016"><a name="p1188582414016"></a><a name="p1188582414016"></a>Called to process a request from the proxy and return the result. Derived classes need to override this method.</p>
</td>
</tr>
<tr id="row108856241904"><td class="cellrowborder" valign="top" width="14.12141214121412%" headers="mcps1.2.4.1.1 "><p id="p6885924609"><a name="p6885924609"></a><a name="p6885924609"></a>IRemoteProxy</p>
</td>
<td class="cellrowborder" valign="top" width="52.54525452545254%" headers="mcps1.2.4.1.2 ">&nbsp;&nbsp;</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.3 "><p id="p688592413018"><a name="p688592413018"></a><a name="p688592413018"></a>Service proxy classes are derived from the <strong id="b169739356519"><a name="b169739356519"></a><a name="b169739356519"></a>IRemoteProxy</strong> class.</p>
</td>
</tr>
</tbody>
</table>
## How to Develop<a name="section4207112818418"></a> ## How to Develop<a name="section4207112818418"></a>
......
# Subscribing to State Changes of a Remote Object<a name="EN-US_TOPIC_0000001104030756"></a> # Subscribing to State Changes of a Remote Object
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. You can also unsubscribe from the state changes if they are no longer needed. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **IRemoteObject.DeathRecipient** interface and the **onRemoteDied** method 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. 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** callback and the **onRemoteDied** method 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.
**Development Using Native APIs** Note that 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.
The following APIs are used to add a recipient for death notifications of a remote stub object, remove such a recipient, and perform subsequent operations upon receiving a death notification of the remote stub object:
```
bool AddDeathRecipient(const sptr<DeathRecipient> &recipient);
bool RemoveDeathRecipient(const sptr<DeathRecipient> &recipient);
void OnRemoteDied(const wptr<IRemoteObject> &object);
```
The sample code is as follows:
## **Development Using Native APIs**
| API| Description|
| -------- | -------- |
| AddDeathRecipient(const sptr\<DeathRecipient> &recipient); | Adds a recipient for death notifications of a remote stub object.|
| RemoveDeathRecipient(const sptr\<DeathRecipient> &recipient); | Removes the recipient for death notifications of a remote stub object.|
| OnRemoteDied(const wptr\<IRemoteObject> &object); | Called when the remote stub object dies.|
## Sample Code
``` ```
class TestDeathRecipient : public IRemoteObject::DeathRecipient { class TestDeathRecipient : public IRemoteObject::DeathRecipient {
public: public:
virtual void OnRemoteDied(const wptr<IRemoteObject>& remoteObject); virtual void OnRemoteDied(const wptr<IRemoteObject>& remoteObject);
} }
sptr<IRemoteObject::DeathRecipient> deathRecipient (new TestDeathRecipient()); // Construct a death notification recipient. sptr<IRemoteObject::DeathRecipient> deathRecipient (new TestDeathRecipient());// Construct a death notification recipient.
bool result = proxy->AddDeathRecipient(deathRecipient); // Add the recipient to the proxy. bool result = proxy->AddDeathRecipient(deathRecipient); // Add a recipient for death notifications.
result = proxy->RemoveDeathRecipient(deathRecipient); // Remove the recipient. result = proxy->RemoveDeathRecipient(deathRecipient); // Remove the recipient for death notifications.
``` ```
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
## Use Cases ## Use Cases
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. 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.
If an error occurs in any of the preceding processes, the client will receive a callback of the **error** event. If an error occurs in any of the preceding processes, the client will receive a callback of the **error** event.
...@@ -18,14 +18,14 @@ The WebSocket connection function is mainly implemented by the WebSocket module. ...@@ -18,14 +18,14 @@ The WebSocket connection function is mainly implemented by the WebSocket module.
| connect() | Establishes a WebSocket connection to a given URL. | | connect() | Establishes a WebSocket connection to a given URL. |
| send() | Sends data through the WebSocket connection. | | send() | Sends data through the WebSocket connection. |
| close() | Closes a WebSocket connection. | | close() | Closes a WebSocket connection. |
| on(type:&nbsp;'open') | Enables listening for **open** events of a WebSocket connection. | | on(type: 'open') | Enables listening for **open** events of a WebSocket connection. |
| off(type:&nbsp;'open') | Disables listening for **open** events of a WebSocket connection. | | off(type: 'open') | Disables listening for **open** events of a WebSocket connection. |
| on(type:&nbsp;'message') | Enables listening for **message** events of a WebSocket connection. | | on(type: 'message') | Enables listening for **message** events of a WebSocket connection. |
| off(type:&nbsp;'message') | Disables listening for **message** events of a WebSocket connection. | | off(type: 'message') | Disables listening for **message** events of a WebSocket connection. |
| on(type:&nbsp;'close') | Enables listening for **close** events of a WebSocket connection. | | on(type: 'close') | Enables listening for **close** events of a WebSocket connection. |
| off(type:&nbsp;'close') | Disables listening for **close** events of a WebSocket connection. | | off(type: 'close') | Disables listening for **close** events of a WebSocket connection. |
| on(type:&nbsp;'error') | Enables listening for **error** events of a WebSocket connection. | | on(type: 'error') | Enables listening for **error** events of a WebSocket connection. |
| off(type:&nbsp;'error') | Disables listening for **error** events of a WebSocket connection. | | off(type: 'error') | Disables listening for **error** events of a WebSocket connection. |
## How to Develop ## How to Develop
...@@ -50,9 +50,9 @@ The WebSocket connection function is mainly implemented by the WebSocket module. ...@@ -50,9 +50,9 @@ The WebSocket connection function is mainly implemented by the WebSocket module.
// When receiving the on('open') event, the client can use the send() API to communicate with the server. // When receiving the on('open') event, the client can use the send() API to communicate with the server.
ws.send("Hello, server!", (err, value) => { ws.send("Hello, server!", (err, value) => {
if (!err) { if (!err) {
console.log("send success"); console.log("Message sent successfully");
} else { } else {
console.log("send fail, err:" + JSON.stringify(err)); console.log("Failed to send the message. Err:" + JSON.stringify(err));
} }
}); });
}); });
...@@ -62,9 +62,9 @@ The WebSocket connection function is mainly implemented by the WebSocket module. ...@@ -62,9 +62,9 @@ The WebSocket connection function is mainly implemented by the WebSocket module.
if (value === 'bye') { if (value === 'bye') {
ws.close((err, value) => { ws.close((err, value) => {
if (!err) { if (!err) {
console.log("close success"); console.log("Connection closed successfully");
} else { } else {
console.log("close fail, err is " + JSON.stringify(err)); console.log("Failed to close the connection. Err: " + JSON.stringify(err));
} }
}); });
} }
...@@ -77,9 +77,9 @@ The WebSocket connection function is mainly implemented by the WebSocket module. ...@@ -77,9 +77,9 @@ The WebSocket connection function is mainly implemented by the WebSocket module.
}); });
ws.connect(defaultIpAddress, (err, value) => { ws.connect(defaultIpAddress, (err, value) => {
if (!err) { if (!err) {
console.log("connect success"); console.log("Connected successfully");
} else { } else {
console.log("connect fail, err:" + JSON.stringify(err)); console.log("Connection failed. Err:" + JSON.stringify(err));
} }
}); });
``` ```
...@@ -100,7 +100,7 @@ The RDB provides **RdbPredicates** for you to set database operation conditions. ...@@ -100,7 +100,7 @@ The RDB provides **RdbPredicates** for you to set database operation conditions.
| RdbPredicates | glob(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match the specified string.<br>- **field**: column name in the database table.<br>- **value**: value specified.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| | RdbPredicates | glob(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match the specified string.<br>- **field**: column name in the database table.<br>- **value**: value specified.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.|
| RdbPredicates | between(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value within the specified range.<br>- **field**: column name in the database table.<br>- **low**: minimum value that matches the **RdbPredicates**.<br>- **high**: maximum value that matches the **RdbPredicates**.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| | RdbPredicates | between(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value within the specified range.<br>- **field**: column name in the database table.<br>- **low**: minimum value that matches the **RdbPredicates**.<br>- **high**: maximum value that matches the **RdbPredicates**.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.|
| RdbPredicates | notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range.<br>- **field**: column name in the database table.<br>- **low**: minimum value that matches the **RdbPredicates**.<br>- **high**: maximum value that matches the **RdbPredicates**.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| | RdbPredicates | notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range.<br>- **field**: column name in the database table.<br>- **low**: minimum value that matches the **RdbPredicates**.<br>- **high**: maximum value that matches the **RdbPredicates**.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.|
| RdbPredicates | greaterThan(field: string, value: ValueType): RdbPredicatesgr | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value.<br>- **field**: column name in the database table.<br>- **value**: value specified.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| | RdbPredicates | greaterThan(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value.<br>- **field**: column name in the database table.<br>- **value**: value specified.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.|
| RdbPredicates | lessThan(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value.<br>- **field**: column name in the database table.<br>- **value**: value specified.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| | RdbPredicates | lessThan(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value.<br>- **field**: column name in the database table.<br>- **value**: value specified.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.|
| RdbPredicates | greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value specified.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| | RdbPredicates | greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value specified.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.|
| RdbPredicates | lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value specified.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| | RdbPredicates | lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value specified.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.|
......
...@@ -2,13 +2,13 @@ ...@@ -2,13 +2,13 @@
## When to Use ## When to Use
The event logging function helps applications log various information generated during running. The event logging function helps applications to log various information generated during running.
## Available APIs ## Available APIs
JS application event logging APIs are provided by the **hiAppEvent** module. JS application event logging APIs are provided by the **hiAppEvent** module.
**APIs for Event Logging** **Table 1** APIs for event logging
| API | Return Value | Description | | API | Return Value | Description |
| ------------------------------------------------------------ | -------------- | ------------------------------------------------------------ | | ------------------------------------------------------------ | -------------- | ------------------------------------------------------------ |
...@@ -17,7 +17,7 @@ JS application event logging APIs are provided by the **hiAppEvent** module. ...@@ -17,7 +17,7 @@ JS application event logging APIs are provided by the **hiAppEvent** module.
When an asynchronous callback is used, the return value can be processed directly in the callback. When a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Event Verification Result Codes](#event-verification-result-codes). When an asynchronous callback is used, the return value can be processed directly in the callback. When a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Event Verification Result Codes](#event-verification-result-codes).
**APIs for Event Logging Configuration** **Table 2** APIs for event logging configuration
| API | Return Value | Description | | API | Return Value | Description |
| ------------------------------ | ------------ | ------------------------------------------------------------ | | ------------------------------ | ------------ | ------------------------------------------------------------ |
......
...@@ -2,8 +2,10 @@ ...@@ -2,8 +2,10 @@
HiAppEvent provides event logging APIs for applications to log the fault, statistical, security, and user behavior events reported during running. Based on event information, you will be able to analyze the running status of your application. HiAppEvent provides event logging APIs for applications to log the fault, statistical, security, and user behavior events reported during running. Based on event information, you will be able to analyze the running status of your application.
The HiAppEvent module of OpenHarmony can be used to develop application event services and provide functions related to application events, including flushing application events to a disk and querying historical application event data.
## Basic Concepts ## Basic Concepts
The HiAppEvent module of OpenHarmony can be used to develop application event services and provide functions related to application events, including flushing application events to a disk and querying historical application event data. - **Logging**
**Logging**: Logs changes caused by user operations to provide service data for development, product, and O&M analysis. Logs changes caused by user operations to provide service data for development, product, and O&M analysis.
...@@ -8,7 +8,7 @@ HiTraceMeter provides APIs for system performance tracing. You can call the APIs ...@@ -8,7 +8,7 @@ HiTraceMeter provides APIs for system performance tracing. You can call the 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** **Table 1** APIs for performance tracing
| API| Return Value| Description| | API| Return Value| Description|
| ---------------------------------------------------------------------------- | --------- | ------------ | | ---------------------------------------------------------------------------- | --------- | ------------ |
......
...@@ -15,4 +15,4 @@ hiTraceMeter is a tool for you to trace service processes and monitor system per ...@@ -15,4 +15,4 @@ hiTraceMeter is a tool for you to trace service processes and monitor system per
## Constraints ## Constraints
- Due to the asynchronous I/O feature of JS, the hiTraceMeter module provides only asynchronous APIs. Due to the asynchronous I/O feature of JS, the hiTraceMeter module provides only asynchronous APIs.
...@@ -23,57 +23,64 @@ You can use APIs provided in the following table to obtain the system language a ...@@ -23,57 +23,64 @@ You can use APIs provided in the following table to obtain the system language a
### How to Develop ### How to Develop
1. Obtain the system language.<br> 1. Obtain the system language.
Call the **getSystemLanguage** method to obtain the system language (**i18n** is the name of the imported module). Call the **getSystemLanguage** method to obtain the system language (**i18n** is the name of the imported module).
``` ```js
var language = i18n.getSystemLanguage(); var language = i18n.getSystemLanguage();
``` ```
2. Obtain the system region.<br> 2. Obtain the system region.
Call the **getSystemRegion** method to obtain the system region. Call the **getSystemRegion** method to obtain the system region.
``` ```js
var region = i18n.getSystemRegion(); var region = i18n.getSystemRegion();
``` ```
3. Obtain the system locale.<br> 3. Obtain the system locale.
Call the **getSystemLocale** method to obtain the system locale. Call the **getSystemLocale** method to obtain the system locale.
``` ```js
var locale = i18n.getSystemLocale(); var locale = i18n.getSystemLocale();
``` ```
4. Check whether the locale's language is RTL.<br> 4. Check whether the locale's language is RTL.
Call the **isRTL** method to check whether the locale's language is RTL. Call the **isRTL** method to check whether the locale's language is RTL.
``` ```js
var rtl = i18n.isRTL("zh-CN"); var rtl = i18n.isRTL("zh-CN");
``` ```
5. Check whether the system uses a 24-hour clock.<br> 5. Check whether the system uses a 24-hour clock.
Call the **is24HourClock** method to check whether the system uses a 24-hour clock. Call the **is24HourClock** method to check whether the system uses a 24-hour clock.
``` ```js
var hourClock = i18n.is24HourClock(); var hourClock = i18n.is24HourClock();
``` ```
6. Obtain the localized display of a language.<br> 6. Obtain the localized display of a language.
Call the **getDisplayLanguage** method to obtain the localized display of a language. **language** indicates the language to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. Call the **getDisplayLanguage** method to obtain the localized display of a language. **language** indicates the language to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized.
``` ```js
var language = "en"; var language = "en";
var locale = "zh-CN"; var locale = "zh-CN";
var sentenceCase = false; var sentenceCase = false;
var localizedLanguage = i18n.getDisplayLanguage(language, locale, sentenceCase); var localizedLanguage = i18n.getDisplayLanguage(language, locale, sentenceCase);
``` ```
7. Obtain the localized display of a country.<br> 7. Obtain the localized display of a country.
Call the **getDisplayCountry** method to obtain the localized display of a country name. **country** indicates the country code (a two-letter code in compliance with ISO-3166, for example, CN), **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. Call the **getDisplayCountry** method to obtain the localized display of a country name. **country** indicates the country code (a two-letter code in compliance with ISO-3166, for example, CN), **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized.
``` ```js
var country = "US"; var country = "US";
var locale = "zh-CN"; var locale = "zh-CN";
var sentenceCase = false; var sentenceCase = false;
...@@ -106,70 +113,78 @@ You can use APIs provided in the following table to obtain the system language a ...@@ -106,70 +113,78 @@ You can use APIs provided in the following table to obtain the system language a
### How to Develop ### How to Develop
1. Instantiate a **Calendar** object.<br> 1. Instantiate a **Calendar** object.
Call the **getCalendar** method to obtain the time zone object of a specific locale and type (**i18n** is the name of the imported module). **type** indicates the valid calendar type, for example, **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic_civil**, **islamic_tbla**, **islamic_umalqura**, **japanese**, and **persian**. If **type** is left unspecified, the default calendar type of the locale is used. Call the **getCalendar** method to obtain the time zone object of a specific locale and type (**i18n** is the name of the imported module). **type** indicates the valid calendar type, for example, **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic_civil**, **islamic_tbla**, **islamic_umalqura**, **japanese**, and **persian**. If **type** is left unspecified, the default calendar type of the locale is used.
``` ```js
var calendar = i18n.getCalendar("zh-CN", "gregory); var calendar = i18n.getCalendar("zh-CN", "gregory);
``` ```
2. Set the time for the **Calendar** object.<br> 2. Set the time for the **Calendar** object.
Call the **setTime** method to set the time of the **Calendar** object. This method receives two types of parameters. One is a **Date** object, and the other is a value indicating the number of milliseconds elapsed since January 1, 1970, 00:00:00 GMT. Call the **setTime** method to set the time of the **Calendar** object. This method receives two types of parameters. One is a **Date** object, and the other is a value indicating the number of milliseconds elapsed since January 1, 1970, 00:00:00 GMT.
``` ```js
var date1 = new Date(); var date1 = new Date();
calendar.setTime(date1); calendar.setTime(date1);
var date2 = 1000; var date2 = 1000;
calendar.setTime(date2); calendar.setTime(date2);
``` ```
3. Set the year, month, day, hour, minute, and second for the **Calendar** object.<br> 3. Set the year, month, day, hour, minute, and second for the **Calendar** object.
Call the **set** method to set the year, month, day, hour, minute, and second for the **Calendar** object. Call the **set** method to set the year, month, day, hour, minute, and second for the **Calendar** object.
``` ```js
calendar.set(2021, 12, 21, 6, 0, 0) calendar.set(2021, 12, 21, 6, 0, 0)
``` ```
4. Set and obtain the time zone for the **Calendar** object.<br> 4. Set and obtain the time zone for the **Calendar** object.
Call the **setTimeZone** and **getTimeZone** methods to set and obtain the time zone for the **Calendar** object. The **setTimeZone** method requires an input string to indicate the time zone to be set. Call the **setTimeZone** and **getTimeZone** methods to set and obtain the time zone for the **Calendar** object. The **setTimeZone** method requires an input string to indicate the time zone to be set.
``` ```js
calendar.setTimeZone("Asia/Shanghai"); calendar.setTimeZone("Asia/Shanghai");
var timezone = calendar.getTimeZone(); var timezone = calendar.getTimeZone();
``` ```
5. Set and obtain the first day of a week for the **Calendar** object.<br> 5. Set and obtain the first day of a week for the **Calendar** object.
Call the **setFirstDayOfWeek** and **getFirstDayOfWeek** methods to set and obtain the first day of a week for the **Calendar** object. **setFirstDayOfWeek** must be set to a value indicating the first day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday. Call the **setFirstDayOfWeek** and **getFirstDayOfWeek** methods to set and obtain the first day of a week for the **Calendar** object. **setFirstDayOfWeek** must be set to a value indicating the first day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.
``` ```js
calendar.setFirstDayOfWeek(1); calendar.setFirstDayOfWeek(1);
var firstDayOfWeek = calendar.getFirstDayOfWeek(); var firstDayOfWeek = calendar.getFirstDayOfWeek();
``` ```
6. Set and obtain the minimum count of days in the first week for the **Calendar** object.<br> 6. Set and obtain the minimum count of days in the first week for the **Calendar** object.
Call the **setMinimalDaysInFirstWeek** and **getMinimalDaysInFirstWeek** methods to set and obtain the minimum count of days in the first week for the **Calendar** object. Call the **setMinimalDaysInFirstWeek** and **getMinimalDaysInFirstWeek** methods to set and obtain the minimum count of days in the first week for the **Calendar** object.
``` ```js
calendar.setMinimalDaysInFirstWeek(3); calendar.setMinimalDaysInFirstWeek(3);
var minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); var minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek();
``` ```
7. Obtain the localized display of the **Calendar** object.<br> 7. Obtain the localized display of the **Calendar** object.
Call the **getDisplayName** method to obtain the localized display of the **Calendar** object. Call the **getDisplayName** method to obtain the localized display of the **Calendar** object.
``` ```js
var localizedName = calendar.getDisplayName("zh-CN"); var localizedName = calendar.getDisplayName("zh-CN");
``` ```
8. Check whether a date is a weekend.<br> 8. Check whether a date is a weekend.
Call the **isWeekend** method to determine whether the input date is a weekend. Call the **isWeekend** method to determine whether the input date is a weekend.
``` ```js
var date = new Date(); var date = new Date();
var weekend = calendar.isWeekend(date); var weekend = calendar.isWeekend(date);
``` ```
...@@ -191,25 +206,26 @@ You can use APIs provided in the following table to obtain the system language a ...@@ -191,25 +206,26 @@ You can use APIs provided in the following table to obtain the system language a
### How to Develop ### How to Develop
1. Instantiate a **PhoneNumberFormat** object.<br> 1. Instantiate a **PhoneNumberFormat** object.
Call the **PhoneNumberFormat** constructor to instantiate a **PhoneNumberFormat** object. The country code and formatting options of the phone number need to be passed into this constructor. The formatting options are optional, including a style option. Values of this option include: **E164**, **INTERNATIONAL**, **NATIONAL**, and **RFC3966**. Call the **PhoneNumberFormat** constructor to instantiate a **PhoneNumberFormat** object. The country code and formatting options of the phone number need to be passed into this constructor. The formatting options are optional, including a style option. Values of this option include: **E164**, **INTERNATIONAL**, **NATIONAL**, and **RFC3966**.
``` ```js
var phoneNumberFormat = new i18n.PhoneNumberFormat("CN", {type: "E164"}); var phoneNumberFormat = new i18n.PhoneNumberFormat("CN", {type: "E164"});
``` ```
2. Check whether the phone number format is correct. 2. Check whether the phone number format is correct.
Call the **isValidNumber** method to check whether the format of the input phone number is correct. Call the **isValidNumber** method to check whether the format of the input phone number is correct.
``` ```js
var validNumber = phoneNumberFormat.isValidNumber("15812341234"); var validNumber = phoneNumberFormat.isValidNumber("15812341234");
``` ```
3. Format a phone number. 3. Format a phone number.
Call the **format** method of **PhoneNumberFormat** to format the input phone number. Call the **format** method of **PhoneNumberFormat** to format the input phone number.
``` ```js
var formattedNumber = phoneNumberFormat.format("15812341234"); var formattedNumber = phoneNumberFormat.format("15812341234");
``` ```
...@@ -232,7 +248,7 @@ The **unitConvert** API is provided to help you implement measurement conversion ...@@ -232,7 +248,7 @@ The **unitConvert** API is provided to help you implement measurement conversion
Call the [unitConvert](../reference/apis/js-apis-intl.md) method to convert a measurement unit and format the display result. Call the [unitConvert](../reference/apis/js-apis-intl.md) method to convert a measurement unit and format the display result.
``` ```js
var fromUnit = {unit: "cup", measureSystem: "US"}; var fromUnit = {unit: "cup", measureSystem: "US"};
var toUnit = {unit: "liter", measureSystem: "SI"}; var toUnit = {unit: "liter", measureSystem: "SI"};
var number = 1000; var number = 1000;
...@@ -259,32 +275,36 @@ The **unitConvert** API is provided to help you implement measurement conversion ...@@ -259,32 +275,36 @@ The **unitConvert** API is provided to help you implement measurement conversion
### How to Develop ### How to Develop
1. Instantiate an **IndexUtil** object.<br> 1. Instantiate an **IndexUtil** object.
Call the **getInstance** method to instantiate an **IndexUtil** object for a specific locale. When the **locale** parameter is empty, instantiate an **IndexUtil** object of the default locale. Call the **getInstance** method to instantiate an **IndexUtil** object for a specific locale. When the **locale** parameter is empty, instantiate an **IndexUtil** object of the default locale.
``` ```js
var indexUtil = getInstance("zh-CN"); var indexUtil = getInstance("zh-CN");
``` ```
2. Obtain the index list.<br> 2. Obtain the index list.
Call the **getIndexList** method to obtain the alphabet index list of the current locale. Call the **getIndexList** method to obtain the alphabet index list of the current locale.
``` ```js
var indexList = indexUtil.getIndexList(); var indexList = indexUtil.getIndexList();
``` ```
3. Add an index.<br> 3. Add an index.
Call the **addLocale** method to add the alphabet index of a new locale to the current index list. Call the **addLocale** method to add the alphabet index of a new locale to the current index list.
``` ```js
indexUtil.addLocale("ar") indexUtil.addLocale("ar")
``` ```
4. Obtain the index of a string.<br> 4. Obtain the index of a string.
Call the **getIndex** method to obtain the alphabet index of a string. Call the **getIndex** method to obtain the alphabet index of a string.
``` ```js
var text = "access index"; var text = "access index";
indexUtil.getIndex(text); indexUtil.getIndex(text);
``` ```
...@@ -313,38 +333,42 @@ When a text is displayed in more than one line, [BreakIterator](../reference/api ...@@ -313,38 +333,42 @@ When a text is displayed in more than one line, [BreakIterator](../reference/api
### How to Develop ### How to Develop
1. Instantiate a **BreakIterator** object.<br> 1. Instantiate a **BreakIterator** object.
Call the **getLineInstance** method to instantiate a **BreakIterator** object. Call the **getLineInstance** method to instantiate a **BreakIterator** object.
``` ```js
var locale = "en-US" var locale = "en-US"
var breakIterator = i18n.getLineInstance(locale); var breakIterator = i18n.getLineInstance(locale);
``` ```
2. Set and access the text that requires line breaking.<br> 2. Set and access the text that requires line breaking.
Call the **setLineBreakText** and **getLineBreakText** methods to set and access the text that requires line breaking. Call the **setLineBreakText** and **getLineBreakText** methods to set and access the text that requires line breaking.
``` ```js
var text = "Apple is my favorite fruit"; var text = "Apple is my favorite fruit";
breakIterator.setLineBreakText(text); breakIterator.setLineBreakText(text);
var breakText = breakIterator.getLineBreakText(); var breakText = breakIterator.getLineBreakText();
``` ```
3. Obtain the current position of the **BreakIterator** object.<br> 3. Obtain the current position of the **BreakIterator** object.
Call the **current** method to obtain the current position of the **BreakIterator** object in the text being processed. Call the **current** method to obtain the current position of the **BreakIterator** object in the text being processed.
``` ```js
var pos = breakIterator.current(); var pos = breakIterator.current();
``` ```
4. Set the position of a **BreakIterator** object.<br> 4. Set the position of a **BreakIterator** object.
The following APIs are provided to adjust the **first**, **last**, **next**, **previous**, or **following** position of the **BreakIterator** object in the text to be processed. The following APIs are provided to adjust the **first**, **last**, **next**, **previous**, or **following** position of the **BreakIterator** object in the text to be processed.
``` ```js
var firstPos = breakIterator.first(); // Set a BreakIterator object to the first break point, that is, the start position of the text. var firstPos = breakIterator.first(); // Set a BreakIterator object to the first break point, that is, the start position of the text.
var lastPos = breakIterator.last(); // Set a BreakIterator object to the last break point, that is, the position after the text end. var lastPos = breakIterator.last(); // Set a BreakIterator object to the last break point, that is, the position after the text end.
// Move a BreakIterator object forward or backward by a certain number of break points. // Move a BreakIterator object forward or backward by a certain number of break points.
...@@ -356,10 +380,11 @@ When a text is displayed in more than one line, [BreakIterator](../reference/api ...@@ -356,10 +380,11 @@ When a text is displayed in more than one line, [BreakIterator](../reference/api
var followingPos = breakIterator.following(10); var followingPos = breakIterator.following(10);
``` ```
5. Determine whether a position is a break point.<br> 5. Determine whether a position is a break point.
Call the **isBoundary** method to determine whether a position is a break point. If yes, **true** is returned and the **BreakIterator** object is moved to this position. If no, **false** is returned and the **BreakIterator** object is moved to a break point after this position. Call the **isBoundary** method to determine whether a position is a break point. If yes, **true** is returned and the **BreakIterator** object is moved to this position. If no, **false** is returned and the **BreakIterator** object is moved to a break point after this position.
``` ```js
var isboundary = breakIterator.isBoundary(5); var isboundary = breakIterator.isBoundary(5);
``` ```
...@@ -3,7 +3,8 @@ ...@@ -3,7 +3,8 @@
This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N interfaces defined in ECMA 402. This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N interfaces defined in ECMA 402.
The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities. The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities.
> **NOTE**<br> > **NOTE**
>
> In the code snippets in this document, **intl** refers to the name of the imported module. > In the code snippets in this document, **intl** refers to the name of the imported module.
## Setting Locale Information ## Setting Locale Information
...@@ -24,7 +25,8 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc ...@@ -24,7 +25,8 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc
### How to Develop ### How to Develop
1. Instantiate a **Locale** object.<br> 1. Instantiate a **Locale** object.
Create a **Locale** object by using the **Locale** constructor. This method receives a string representing the locale and an optional [Attributes](../reference/apis/js-apis-intl.md) list. Create a **Locale** object by using the **Locale** constructor. This method receives a string representing the locale and an optional [Attributes](../reference/apis/js-apis-intl.md) list.
A **Locale** object consists of four parts: language, script, region, and extension, which are separated by using a hyphen (-). A **Locale** object consists of four parts: language, script, region, and extension, which are separated by using a hyphen (-).
...@@ -42,30 +44,33 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc ...@@ -42,30 +44,33 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc
| kf | Whether upper case or lower case is considered when sorting or comparing strings.| | kf | Whether upper case or lower case is considered when sorting or comparing strings.|
``` ```js
var locale = "zh-CN"; var locale = "zh-CN";
var options = {caseFirst: false, calendar: "chinese", collation: pinyin}; var options = {caseFirst: false, calendar: "chinese", collation: pinyin};
var localeObj = new intl.Locale(locale, options); var localeObj = new intl.Locale(locale, options);
``` ```
2. Obtain the string representing a **Locale** object.<br> 2. Obtain the string representing a **Locale** object.
Call the **toString** method to obtain the string representing a **Locale** object, which includes the language, region, and other options. Call the **toString** method to obtain the string representing a **Locale** object, which includes the language, region, and other options.
``` ```js
var localeStr = localeObj.toString(); var localeStr = localeObj.toString();
``` ```
3. Maximize locale information.<br> 3. Maximize locale information.
Call the **maximize** method to maximize locale information; that is, supplement the missing script and region information. Call the **maximize** method to maximize locale information; that is, supplement the missing script and region information.
``` ```js
var maximizedLocale = localeObj.maximize(); var maximizedLocale = localeObj.maximize();
``` ```
4. Minimize locale information.<br> 4. Minimize locale information.
Call the **minimize** method to minimize locale information; that is, delete the unnecessary script and region information. Call the **minimize** method to minimize locale information; that is, delete the unnecessary script and region information.
``` ```js
var minimizedLocale = localeObj.minimize(); var minimizedLocale = localeObj.minimize();
``` ```
...@@ -88,42 +93,46 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date ...@@ -88,42 +93,46 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
### How to Develop ### How to Develop
1. Instantiate a **DateTimeFormat** object.<br> 1. Instantiate a **DateTimeFormat** object.
Use the default constructor of **DateTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **DateTimeFormat** object. Use the default constructor of **DateTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **DateTimeFormat** object.
``` ```js
var dateTimeFormat = new intl.DateTimeFormat(); var dateTimeFormat = new intl.DateTimeFormat();
``` ```
Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md). Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md).
``` ```js
var options = {dateStyle: "full", timeStyle: "full"}; var options = {dateStyle: "full", timeStyle: "full"};
var dateTimeFormat = new intl.DateTimeFormat("zh-CN", options); var dateTimeFormat = new intl.DateTimeFormat("zh-CN", options);
``` ```
2. Format the date and time.<br> 2. Format the date and time.
Call the **format** method to format the date and time in the **DateTimeFormat** object. This method returns a string representing the formatting result. Call the **format** method to format the date and time in the **DateTimeFormat** object. This method returns a string representing the formatting result.
``` ```js
Date date = new Date(); Date date = new Date();
var formatResult = dateTimeFormat.format(date); var formatResult = dateTimeFormat.format(date);
``` ```
3. Format a period.<br> 3. Format a period.
Call the **formatRange** method to format the period in the **DateTimeFormat** object. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result. Call the **formatRange** method to format the period in the **DateTimeFormat** object. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result.
``` ```js
Date startDate = new Date(); Date startDate = new Date();
Date endDate = new Date(); Date endDate = new Date();
var formatResult = dateTimeFormat.formatRange(startDate, endDate); var formatResult = dateTimeFormat.formatRange(startDate, endDate);
``` ```
4. Obtain attributes of the **DateTimeFormat** object.<br> 4. Obtain attributes of the **DateTimeFormat** object.
Call the **resolvedOptions** method to obtain attributes of the **DateTimeFormat** object. This method will return an array that contains all attributes and values of the object. Call the **resolvedOptions** method to obtain attributes of the **DateTimeFormat** object. This method will return an array that contains all attributes and values of the object.
``` ```js
var options = dateTimeFormat.resolvedOptions(); var options = dateTimeFormat.resolvedOptions();
``` ```
...@@ -145,33 +154,36 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for ...@@ -145,33 +154,36 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for
### How to Develop ### How to Develop
1. Instantiate a **NumberFormat** object.<br> 1. Instantiate a **NumberFormat** object.
Use the default constructor of **NumberFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **NumberFormat** object. Use the default constructor of **NumberFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **NumberFormat** object.
``` ```js
var numberFormat = new intl.NumberFormat(); var numberFormat = new intl.NumberFormat();
``` ```
Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md). Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md).
``` ```js
var options = {compactDisplay: "short", notation: "compact"}; var options = {compactDisplay: "short", notation: "compact"};
var numberFormat = new intl.NumberFormat("zh-CN", options); var numberFormat = new intl.NumberFormat("zh-CN", options);
``` ```
2. Format a number.<br> 2. Format a number.
Call the **format** method to format a number. A string is returned as the formatting result. Call the **format** method to format a number. A string is returned as the formatting result.
``` ```js
var number = 1234.5678 var number = 1234.5678
var formatResult = numberFormat.format(number); var formatResult = numberFormat.format(number);
``` ```
3. Obtain attributes of the **NumberFormat** object.<br> 3. Obtain attributes of the **NumberFormat** object.
Call the **resolvedOptions** method to obtain attributes of the **NumberFormat** object. This method will return an array that contains all attributes and values of the object. Call the **resolvedOptions** method to obtain attributes of the **NumberFormat** object. This method will return an array that contains all attributes and values of the object.
``` ```js
var options = numberFormat.resolvedOptions(); var options = numberFormat.resolvedOptions();
``` ```
...@@ -193,33 +205,36 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on ...@@ -193,33 +205,36 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on
### How to Develop ### How to Develop
1. Instantiate a **Collator** object.<br> 1. Instantiate a **Collator** object.
Use the default constructor of **Collator** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **Collator** object. Use the default constructor of **Collator** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **Collator** object.
``` ```js
var collator = new intl.Collator(); var collator = new intl.Collator();
``` ```
Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md). Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md).
```js
var collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"});
``` ```
var collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"};
```
2. Compare two strings.<br> 2. Compare two strings.
Call the **compare** method to compare two input strings. This method returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths. Call the **compare** method to compare two input strings. This method returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths.
``` ```js
var str1 = "first string"; var str1 = "first string";
var str2 = "second string"; var str2 = "second string";
var compareResult = collator.compare(str1, str2); var compareResult = collator.compare(str1, str2);
``` ```
3. Obtain attributes of the **Collator** object.<br> 3. Obtain attributes of the **Collator** object.
Call the **resolvedOptions** method to obtain attributes of the **Collator** object. This method will return an array that contains all attributes and values of the object. Call the **resolvedOptions** method to obtain attributes of the **Collator** object. This method will return an array that contains all attributes and values of the object.
``` ```js
var options = collator.resolvedOptions(); var options = collator.resolvedOptions();
``` ```
...@@ -240,24 +255,26 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu ...@@ -240,24 +255,26 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu
### How to Develop ### How to Develop
1. Instantiate a **PluralRules** object.<br> 1. Instantiate a **PluralRules** object.
Use the default constructor of **PluralRules** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **PluralRules** object. Use the default constructor of **PluralRules** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **PluralRules** object.
``` ```js
var pluralRules = new intl.PluralRules(); var pluralRules = new intl.PluralRules();
``` ```
Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md). Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md).
``` ```js
var plurals = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}; var plurals = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"});
``` ```
2. Determine the singular-plural type.<br> 2. Determine the singular-plural type.
Call the **select** method to determine the singular-plural type of an input number. This method will return a string representing the singular-plural type, which can be any of the following: **zero**, **one**, **two**, **few**, **many**, and **other**. Call the **select** method to determine the singular-plural type of an input number. This method will return a string representing the singular-plural type, which can be any of the following: **zero**, **one**, **two**, **few**, **many**, and **other**.
``` ```js
var number = 1234.5678 var number = 1234.5678
var categoryResult = plurals.select(number); var categoryResult = plurals.select(number);
``` ```
...@@ -281,41 +298,45 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r ...@@ -281,41 +298,45 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r
### How to Develop ### How to Develop
1. Instantiate a **RelativeTimeFormat** object.<br> 1. Instantiate a **RelativeTimeFormat** object.
Use the default constructor of **RelativeTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **RelativeTimeFormat** object. Use the default constructor of **RelativeTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **RelativeTimeFormat** object.
``` ```js
var relativeTimeFormat = new intl.RelativeTimeFormat(); var relativeTimeFormat = new intl.RelativeTimeFormat();
``` ```
Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [ RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md). Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [ RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md).
``` ```js
var relativeTimeFormat = new intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); var relativeTimeFormat = new intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
``` ```
2. Format the relative time.<br> 2. Format the relative time.
Call the **format** method to format the relative time. This method receives a numeric value representing the time length and a string-form unit, like **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, and **second**. This method returns a string representing the formatting result. Call the **format** method to format the relative time. This method receives a numeric value representing the time length and a string-form unit, like **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, and **second**. This method returns a string representing the formatting result.
``` ```js
var number = 2; var number = 2;
var unit = "year" var unit = "year"
var formatResult = relativeTimeFormat.format(number, unit); var formatResult = relativeTimeFormat.format(number, unit);
``` ```
3. Obtain each part of the relative time format.<br> 3. Obtain each part of the relative time format.
Upon obtaining each part of the relative time format, customize the relative time formatting result. Upon obtaining each part of the relative time format, customize the relative time formatting result.
``` ```js
var number = 2; var number = 2;
var unit = "year" var unit = "year"
var formatResult = relativeTimeFormat.formatToParts(number, unit); var formatResult = relativeTimeFormat.formatToParts(number, unit);
``` ```
4. Obtain attributes of the **RelativeTimeFormat** object.<br> 4. Obtain attributes of the **RelativeTimeFormat** object.
Call the **resolvedOptions** method to obtain attributes of the **RelativeTimeFormat** object. This method will return an array that contains all attributes and values of the object. For a full list of attributes, see [ RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md). Call the **resolvedOptions** method to obtain attributes of the **RelativeTimeFormat** object. This method will return an array that contains all attributes and values of the object. For a full list of attributes, see [ RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md).
``` ```js
var options = numberFormat.resolvedOptions(); var options = numberFormat.resolvedOptions();
``` ```
...@@ -48,7 +48,7 @@ For details about the APIs, see [AudioRenderer in Audio Management](../reference ...@@ -48,7 +48,7 @@ For details about the APIs, see [AudioRenderer in Audio Management](../reference
```js ```js
var mode_ = audio.InterruptMode.SHARE_MODE; var mode_ = audio.InterruptMode.SHARE_MODE;
await this.audioRenderer.setInterruptMode(mode_).then(()=>{ await this.audioRenderer.setInterruptMode(mode_).then(() => {
console.log('[JSAR] [SetInterruptMode] Setting: '+ (mode_ == 0? " share mode":"independent mode") + "success"); console.log('[JSAR] [SetInterruptMode] Setting: '+ (mode_ == 0? " share mode":"independent mode") + "success");
}); });
``` ```
# Guide to Switching to Full SDK
Both the public SDK and full SDK are toolkits for application development.
The public SDK is intended for application developers and provided as standard in DevEco Studio. It does not contain system APIs – APIs required by system applications.
The full SDK is intended for original equipment manufacturers (OEMs) and provided separately. It contains system APIs.
The SDK of API version 8 provided in DevEco Studio is a public SDK. If your project depends on any system API, such as the **animator** component, **xcomponent** component, or APIs in **@ohos.application.abilityManager.d.ts**, **@ohos.application.formInfo.d.ts**, or **@ohos.bluetooth.d.ts**, switch to the full SDK by performing the following steps.
## Downloading the Full SDK (of 3.1.1 Release in this example)
Manually download the full SDK. For details, see the source code acquisition section in [OpenHarmony 3.1.1 Release](https://gitee.com/openharmony/docs/blob/master/en/release-notes/OpenHarmony-v3.1.1-release.md).
![image-20220613161049897](figures/en-us_image_0000001655128646.png)
## Checking the Local SDK Location<br>In this example, an eTS project is used. For a JS project, replace **ets** with **js**.
In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the location of the local SDK.
![](figures/en-us_image_0000001655128939.png)
![image-20220613160524053](figures/en-us_image_0000001655128998.png)
## Replacing the SDK
1. Make sure the downloaded SDK is a full SDK.
a. Verify that the name of the downloaded file contains **sdk-full**.
![image-20220613220702504](figures/en-us_image_0000001655129232.png)
b. Verify that the SDK contains system APIs (such as APIs defined in **@ohos.application.abilityManager.d.ts**, **@ohos.application.formInfo.d.ts**, and **@ohos.bluetooth.d.ts**).
Note: The criteria for identifying system APIs are subject to the released API documentation.
2. Replace the SDK. The following uses full SDK 3.1.6.6 for Windows as an example.
a. Decompress the downloaded full SDK file: `ets-windows-3.1.6.5-Release.zip`
![image-20220613165018184](figures/en-us_image_0000001655129264.png)
b. Replace the SDK files.
Back up the local SDK files. (Copy and rename the version number directory in the **ets** directory, or copy the entire **ets** directory to another local path.)
Go to the obtained location of the local installed SDK and back up the files therein.
![image-20220613161352157](figures/en-us_image_0000001655129041.png)
Note: The name of the backup version number directory must be different from the value of **version** field in the **oh-uni-package.json** file. In the example below, the name of the backup version number directory is **3.1.6.6_backup**.
![image-20220613165018184](figures/en-us_image_0000001655129398.png)
The configuration in the **oh-uni-package.json** file is as follows:
```
{
"apiVersion": "8",
"displayName": "Ets",
"meta": {
"metaVersion": "3.0.0"
},
"path": "ets",
"releaseType": "Release",
"version": "3.1.6.6"
}
```
**Delete all files in the original SDK (3.1.6.6) directory.** Failure to do so may result in some files being unable to be overwritten.
Copy the full SDK to the location of the local SDK.
Copy all files in the **ets** directory in the full SDK to the **ets\3.1.6.6** directory in the location of the local SDK.
Change the value of **version** in the **oh-uni-package.json** file to the current SDK version number.
In the **3.1.6.6\build-tools\ets-loader** directory, open the **cmd/powerShell** window and run the **npm install** command to download the **node_modules** dependency package.
![image-20220613171111405](figures/en-us_image_0000001655129333.png)
c. Check for system APIs.
![image-20220613213038104](figures/en-us_image_0000001655129372.png)
...@@ -32,6 +32,7 @@ ...@@ -32,6 +32,7 @@
- [@ohos.ability.errorCode](js-apis-ability-errorCode.md) - [@ohos.ability.errorCode](js-apis-ability-errorCode.md)
- [@ohos.ability.wantConstant](js-apis-ability-wantConstant.md) - [@ohos.ability.wantConstant](js-apis-ability-wantConstant.md)
- [@ohos.application.abilityDelegatorRegistry](js-apis-abilityDelegatorRegistry.md) - [@ohos.application.abilityDelegatorRegistry](js-apis-abilityDelegatorRegistry.md)
- [@ohos.application.abilityManager](js-apis-application-abilityManager.md)
- [@ohos.application.appManager](js-apis-appmanager.md) - [@ohos.application.appManager](js-apis-appmanager.md)
- [@ohos.application.Configuration](js-apis-configuration.md) - [@ohos.application.Configuration](js-apis-configuration.md)
- [@ohos.application.ConfigurationConstant](js-apis-configurationconstant.md) - [@ohos.application.ConfigurationConstant](js-apis-configurationconstant.md)
...@@ -43,6 +44,8 @@ ...@@ -43,6 +44,8 @@
- [@ohos.application.formProvider](js-apis-formprovider.md) - [@ohos.application.formProvider](js-apis-formprovider.md)
- [@ohos.application.missionManager](js-apis-missionManager.md) - [@ohos.application.missionManager](js-apis-missionManager.md)
- [@ohos.application.Want](js-apis-application-Want.md) - [@ohos.application.Want](js-apis-application-Want.md)
- [@ohos.continuation.continuationManager](js-apis-continuation-continuationExtraParams.md)
- [@ohos.continuation.continuationManager](js-apis-continuation-continuationManager.md)
- [@ohos.wantAgent](js-apis-wantAgent.md) - [@ohos.wantAgent](js-apis-wantAgent.md)
- application/[abilityDelegator](js-apis-application-abilityDelegator.md) - application/[abilityDelegator](js-apis-application-abilityDelegator.md)
- application/[abilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md) - application/[abilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md)
...@@ -52,7 +55,7 @@ ...@@ -52,7 +55,7 @@
- application/[MissionSnapshot](js-apis-application-MissionSnapshot.md) - application/[MissionSnapshot](js-apis-application-MissionSnapshot.md)
- application/[ProcessRunningInfo](js-apis-processrunninginfo.md) - application/[ProcessRunningInfo](js-apis-processrunninginfo.md)
- application/[shellCmdResult](js-apis-application-shellCmdResult.md) - application/[shellCmdResult](js-apis-application-shellCmdResult.md)
- continuation/[ContinuationResult](js-apis-continuation-continuationResult.md)
- Common Event and Notification - Common Event and Notification
- [@ohos.commonEvent](js-apis-commonEvent.md) - [@ohos.commonEvent](js-apis-commonEvent.md)
......
...@@ -25,9 +25,9 @@ abilitymanager.getAbilityRunningInfos((err,data) => { ...@@ -25,9 +25,9 @@ abilitymanager.getAbilityRunningInfos((err,data) => {
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| ability | ElementName | Yes| No| Information that matches an ability. | | ability | ElementName | Yes| No| Information that matches an ability. |
| pid | number | Yes| No| Process ID.| | pid | number | Yes| No| Process ID.|
| uid | number | Yes| No| User ID. | | uid | number | Yes| No| User ID. |
| processName | string | Yes| No| Process name. | | processName | string | Yes| No| Process name. |
| startTime | number | Yes| No| Ability start time. | | startTime | number | Yes| No| Ability start time. |
| abilityState | [abilityManager.AbilityState](js-apis-abilityManager.md#abilityState) | Yes| No| Ability state. | | abilityState | [abilityManager.AbilityState](js-apis-application-abilityManager.md#abilitystate) | Yes| No| Ability state. |
...@@ -1956,6 +1956,7 @@ Defines OAuth token information. ...@@ -1956,6 +1956,7 @@ Defines OAuth token information.
| -------- | ------ | ---- | -------- | | -------- | ------ | ---- | -------- |
| authType | string | Yes | Authentication type.| | authType | string | Yes | Authentication type.|
| token | string | Yes | Value of the token. | | token | string | Yes | Value of the token. |
| account<sup>9+</sup> | AppAccountInfo | No | Account information of the token. |
## AuthenticatorInfo<sup>8+</sup> ## AuthenticatorInfo<sup>8+</sup>
......
...@@ -19,5 +19,5 @@ import StartOptions from '@ohos.application.StartOptions'; ...@@ -19,5 +19,5 @@ import StartOptions from '@ohos.application.StartOptions';
| Name| Readable| Writable| Type| Mandatory| Description| | Name| Readable| Writable| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- | -------- |
| windowMode | Yes| No| number | No| Window mode.| | [windowMode](js-apis-application-abilityConstant.md#AbilityConstant.WindowMode) | Yes| No| number | No| Window mode.|
| displayId | Yes| No| number | No| Display ID.| | displayId | Yes| No| number | No| Display ID.|
# Window Extension Ability
**WindowExtensionAbility** inherits from **ExtensionAbility**. The content in a **WindowExtensionAbility** object can be displayed as an ability component in other application windows.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The APIs provided by this module are system APIs.
>
> The APIs of this module can be used only in the stage model.
## Modules to Import
```ts
import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility';
```
## Attributes
**System capability**: SystemCapability.WindowManager.WindowManager.Core
| Name | Type| Readable| Writable| Description |
| --------- | -------- | ---- | ---- | ------------------------- |
| context | [ExtensionContext](js-apis-extension-context.md) | Yes | No | Context of an Extension ability. |
## WindowExtensionAbility.onConnect
onConnect(want: Want): rpc.RemoteObject
Called when this Window Extension ability is connected to an ability for the first time.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name. |
**Return value**
| Type | Description |
| ----------------------------------------------- | -------------------- |
| [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Proxy of this Window Extension ability.|
**Example**
```ts
import rpc from '@ohos.rpc';
class StubTest extends rpc.RemoteObject {
constructor(des) {
super(des);
}
onRemoteRequest(code, data, reply, option) {
return true;
}
queryLocalInterface(descriptor) {
return null;
}
getInterfaceDescriptor() {
return "";
}
sendRequest(code, data, reply, options) {
return null;
}
getCallingPid() {
return 1;
}
getCallingUid() {
return 1;
}
attachLocalInterface(localInterface, descriptor){}
}
export default class MyWindowExtensionAbility extends WindowExtensionAbility {
onConnect(want): rpc.RemoteObject {
console.info('WindowExtAbility onConnect ' + want.abilityName);
return new StubTest("test");
}
}
```
## WindowExtensionAbility.onDisconnect
onDisconnect(want: Want): void
Called when this Window Extension ability is disconnected from all connected abilities.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name. |
**Example**
```ts
export default class MyWindowExtensionAbility extends WindowExtensionAbility {
onDisconnect(want) {
console.info('WindowExtAbility onDisconnect ' + want.abilityName);
}
}
```
## WindowExtensionAbility.onWindowReady
onWindowReady(window: Window): void
Called when a window is ready.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| window | [Window](js-apis-window.md) | Yes| Current **Window** instance.|
**Example**
```ts
export default class MyWindowExtensionAbility extends WindowExtensionAbility {
onWindowReady(window) {
window.loadContent('WindowExtAbility/pages/index1').then(() => {
window.getProperties().then((pro) => {
console.log("WindowExtension " + JSON.stringify(pro));
})
window.show();
})
}
}
```
...@@ -62,3 +62,17 @@ Enumerates ability continuation results. ...@@ -62,3 +62,17 @@ Enumerates ability continuation results.
| AGREE | 0 | Continuation agreed.| | AGREE | 0 | Continuation agreed.|
| REJECT | 1 | Continuation denied.| | REJECT | 1 | Continuation denied.|
| MISMATCH | 2 | Mismatch.| | MISMATCH | 2 | Mismatch.|
## AbilityConstant.WindowMode
Enumerates the window modes when an ability is started.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Value| Description |
| --- | --- | --- |
| WINDOW_MODE_UNDEFINED | 0 | Undefined window mode. |
| WINDOW_MODE_FULLSCREEN | 1 | The ability is displayed in full screen. |
| WINDOW_MODE_SPLIT_PRIMARY | 100 | The ability is displayed in the primary window in split-screen mode. |
| WINDOW_MODE_SPLIT_SECONDARY | 101 | The ability is displayed in the secondary window in split-screen mode. |
| WINDOW_MODE_FLOATING | 102 | The ability is displayed in a floating window.|
...@@ -7,7 +7,7 @@ The **AbilityManager** module provides APIs for obtaining, adding, and modifying ...@@ -7,7 +7,7 @@ The **AbilityManager** module provides APIs for obtaining, adding, and modifying
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module are system APIs and cannot be called by third-party applications. > The APIs of this module are system APIs and cannot be called by third-party applications.
# Modules to Import ## Modules to Import
```js ```js
import AbilityManager from '@ohos.application.abilityManager' import AbilityManager from '@ohos.application.abilityManager'
...@@ -19,6 +19,8 @@ Enumerates the ability states. ...@@ -19,6 +19,8 @@ Enumerates the ability states.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
| Name| Value| Description| | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| INITIAL | 0 | The ability is in the initial state.| | INITIAL | 0 | The ability is in the initial state.|
......
...@@ -7,7 +7,7 @@ The **ApplicationContext** module provides application-level context. You can us ...@@ -7,7 +7,7 @@ The **ApplicationContext** module provides application-level context. You can us
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model. > The APIs of this module can be used only in the stage model.
## How to Use ## Usage
Before calling any APIs in **ApplicationContext**, obtain an **ApplicationContext** instance through the **context** instance. Before calling any APIs in **ApplicationContext**, obtain an **ApplicationContext** instance through the **context** instance.
...@@ -28,7 +28,7 @@ Registers a listener to monitor the ability lifecycle of the application. ...@@ -28,7 +28,7 @@ Registers a listener to monitor the ability lifecycle of the application.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------------------ | -------- | ---- | ------------------------------ | | ------------------------ | -------- | ---- | ------------------------------ |
| [AbilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md) | callback | Yes | Callback used to return the ID of the registered listener.| | callback | [AbilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md) | Yes | Callback used to return the ID of the registered listener.|
**Return value** **Return value**
...@@ -98,7 +98,7 @@ Deregisters the listener that monitors the ability lifecycle of the application. ...@@ -98,7 +98,7 @@ Deregisters the listener that monitors the ability lifecycle of the application.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------- | -------- | ---- | -------------------------- | | ------------- | -------- | ---- | -------------------------- |
| callbackId | number | Yes | ID of the listener to deregister.| | callbackId | number | Yes | ID of the listener to deregister.|
| AsyncCallback | callback | Yes | Callback used to return the result. | | callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -123,7 +123,7 @@ Registers a listener for system environment changes. This API uses an asynchrono ...@@ -123,7 +123,7 @@ Registers a listener for system environment changes. This API uses an asynchrono
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------------------ | -------- | ---- | ------------------------------ | | ------------------------ | -------- | ---- | ------------------------------ |
| [EnvironmentCallback](js-apis-application-EnvironmentCallback.md) | callback | Yes | Callback used to return the ID of the registered listener.| | callback | [EnvironmentCallback](js-apis-application-EnvironmentCallback.md) | Yes | Callback used to return the ID of the registered listener.|
**Return value** **Return value**
...@@ -175,7 +175,7 @@ Deregisters the listener for system environment changes. This API uses an asynch ...@@ -175,7 +175,7 @@ Deregisters the listener for system environment changes. This API uses an asynch
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------- | -------- | ---- | -------------------------- | | ------------- | -------- | ---- | -------------------------- |
| callbackId | number | Yes | ID of the listener to deregister. | | callbackId | number | Yes | ID of the listener to deregister. |
| AsyncCallback | callback | Yes | Callback used to return the result. | | callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example** **Example**
......
# BundleInfo # BundleInfo
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
The **BundleInfo** module provides bundle information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**.
Provides the application bundle information.
## BundleInfo ## BundleInfo
**System capability**: SystemCapability.BundleManager.BundleFramework **System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------ | | --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
| name | string | Yes | No | Bundle name. | | name | string | Yes | No | Bundle name. |
| type | string | Yes | No | Bundle type. | | type | string | Yes | No | Bundle type. |
| appId | string | Yes | No | ID of the application to which the bundle belongs. | | appId | string | Yes | No | ID of the application to which the bundle belongs. |
| uid | number | Yes | No | UID of the application to which the bundle belongs. | | uid | number | Yes | No | UID of the application to which the bundle belongs. |
| installTime | number | Yes | No | Time when the HAP file was installed. | | installTime | number | Yes | No | Time when the HAP file was installed. |
| updateTime | number | Yes | No | Time when the HAP file was updated. | | updateTime | number | Yes | No | Time when the HAP file was updated. |
| appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. | | appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. |
| abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information. | | abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information.<br>The value is obtained by passing **GET_BUNDLE_WITH_ABILITIES**.|
| reqPermissions | Array\<string> | Yes | No | Permissions to request from the system for running the application. | | reqPermissions | Array\<string> | Yes | No | Permissions to request from the system for running the application.<br>The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.|
| reqPermissionDetails | Array\<[ReqPermissionDetail](#ReqPermissionDetail)> | Yes | No | Detailed information of the permissions to request from the system.| | reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetail)> | Yes | No | Detailed information of the permissions to request from the system.<br>The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.|
| vendor | string | Yes | No | Vendor of the bundle. | | vendor | string | Yes | No | Vendor of the bundle. |
| versionCode | number | Yes | No | Version number of the bundle. | | versionCode | number | Yes | No | Version number of the bundle. |
| versionName | string | Yes | No | Version description of the bundle. | | versionName | string | Yes | No | Version description of the bundle. |
| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. | | compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. |
| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. | | targetVersion | number | Yes | No | Latest SDK version required for running the bundle. |
| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. | | isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. |
| hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. | | hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. |
| entryModuleName | string | Yes | No | Name of the entry module. | | entryModuleName | string | Yes | No | Name of the entry module. |
| cpuAbi | string | Yes | No | cpuAbi information of the bundle. | | cpuAbi | string | Yes | No | CPU and ABI information of the bundle. |
| isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. | | isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. |
| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | | minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. |
| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. | | entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. |
| reqPermissionStates<sup>8+</sup> | Array\<number> | Yes | No | Permission grant state. | | reqPermissionStates<sup>8+</sup> | Array\<number> | Yes | No | Permission grant state. |
| extensionAbilityInfo<sup>9+</sup> | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Extension ability information. | | extensionAbilityInfo<sup>9+</sup> | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Extension ability information.<br>The value is obtained by passing **GET_BUNDLE_WITH_EXTENSION_ABILITY**.|
......
...@@ -6,9 +6,7 @@ ...@@ -6,9 +6,7 @@
> >
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
The **ExtensionAbilityInfo** module provides Extension ability information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**.
Provides the Extension ability information.
## ExtensionAbilityInfo ## ExtensionAbilityInfo
...@@ -28,5 +26,5 @@ Provides the Extension ability information. ...@@ -28,5 +26,5 @@ Provides the Extension ability information.
| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information of the Extension ability. | | applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information of the Extension ability. |
| metadata | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the Extension ability. | | metadata | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the Extension ability. |
| enabled | boolean | Yes | No | Whether the Extension ability is enabled. | | enabled | boolean | Yes | No | Whether the Extension ability is enabled. |
| readPermission | string | Yes | No | Permission required for reading the Extension ability data. | | readPermission | string | Yes | No | Permission required for reading data from the Extension ability. |
| writePermission | string | Yes | No | Permission required for writing data to the Extension ability. | | writePermission | string | Yes | No | Permission required for writing data to the Extension ability. |
...@@ -6,16 +6,12 @@ ...@@ -6,16 +6,12 @@
> >
> 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.
The **HapModuleInfo** module provides module information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**.
Provides the HAP module information.
## HapModuleInfo ## HapModuleInfo
**System capability**: SystemCapability.BundleManager.BundleFramework **System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| --------------------------------- | ------------------------------------------------------------ | ---- | ---- | -------------------- | | --------------------------------- | ------------------------------------------------------------ | ---- | ---- | -------------------- |
| name | string | Yes | No | Module name. | | name | string | Yes | No | Module name. |
...@@ -36,4 +32,4 @@ Provides the HAP module information. ...@@ -36,4 +32,4 @@ Provides the HAP module information.
| mainElementName<sup>9+</sup> | string | Yes | No | Information about the main ability. | | mainElementName<sup>9+</sup> | string | Yes | No | Information about the main ability. |
| extensionAbilityInfo<sup>9+</sup> | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Information about the Extension ability.| | extensionAbilityInfo<sup>9+</sup> | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Information about the Extension ability.|
| metadata<sup>9+</sup> | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the ability. | | metadata<sup>9+</sup> | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the ability. |
| hashValue<sup>9+</sup> | string | Yes | No | Hash value of the module. | | hashValue<sup>9+</sup> | string | Yes | No | Hash value of the module.<br>The value is obtained by passing **GET_BUNDLE_WITH_HASH_VALUE**.|
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
## Modules to Import ## Modules to Import
``` ```js
import bytrace from '@ohos.bytrace'; import bytrace from '@ohos.bytrace';
``` ```
...@@ -35,7 +35,7 @@ Marks the start of a timeslice trace task. ...@@ -35,7 +35,7 @@ Marks the start of a timeslice trace task.
**Example** **Example**
``` ```js
bytrace.startTrace("myTestFunc", 1); bytrace.startTrace("myTestFunc", 1);
bytrace.startTrace("myTestFunc", 1, 5); // The expected duration of the trace is 5 ms. bytrace.startTrace("myTestFunc", 1, 5); // The expected duration of the trace is 5 ms.
``` ```
...@@ -62,7 +62,7 @@ Marks the end of a timeslice trace task. ...@@ -62,7 +62,7 @@ Marks the end of a timeslice trace task.
**Example** **Example**
``` ```js
bytrace.finishTrace("myTestFunc", 1); bytrace.finishTrace("myTestFunc", 1);
``` ```
...@@ -105,7 +105,7 @@ Defines the variable that indicates the number of timeslice trace tasks. ...@@ -105,7 +105,7 @@ Defines the variable that indicates the number of timeslice trace tasks.
**Example** **Example**
``` ```js
let traceCount = 3; let traceCount = 3;
bytrace.traceByValue("myTestCount", traceCount); bytrace.traceByValue("myTestCount", traceCount);
traceCount = 4; traceCount = 4;
......
# ContinuationExtraParams
The **ContinuationExtraParams** module provides the extra parameters required by the device selection module in the continuation management entry.
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## ContinuationExtraParams
Describes the extra parameters required by the device selection module in the continuation management entry.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| deviceType | Array\<string> | Yes| Yes| Device type.|
| targetBundle | string | Yes| Yes| Target bundle name.|
| description | string | Yes| Yes| Device filtering description.|
| filter | any | Yes| Yes| Device filtering parameter.|
| continuationMode | [ContinuationMode](js-apis-continuation-continuationManager.md#continuationmode) | Yes| Yes| Continuation mode.|
| authInfo | { [key: string]: any } | Yes| Yes| Authentication information.|
# continuationManager
The **continuationManager** module provides the continuation management entry. You can use the APIs of this module to connect to and cancel the continuation management service, subscribe to and unsubscribe from device connection events, start the device selection module, and update the device connection state.
Currently, this module provides incomplete functions, and its APIs are mainly used to start the device selection module. **The continuation capability is not available for application development.**
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```js
import continuationManager from '@ohos.continuation.continuationManager'
```
## continuationManager.register
register(callback: AsyncCallback\<number>): void;
Registers the continuation management service and obtains a token. This API does not involve any filter parameters and uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<number> | Yes| Callback used to return the token generated after the continuation management service is connected.|
**Example**
```js
let token = -1;
continuationManager.register((err, data) => {
if (err.code != 0) {
console.error('register failed, cause: ' + JSON.stringify(err));
return;
}
console.info('register finished, ' + JSON.stringify(data));
token = data;
});
```
## continuationManager.register
register(options: ContinuationExtraParams, callback: AsyncCallback\<number>): void;
Registers the continuation management service and obtains a token. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | Yes| Extra parameters used to filter the list of available devices.|
| callback | AsyncCallback\<number> | Yes| Callback used to return the token generated after the continuation management service is connected.|
**Example**
```js
let token = -1;
let continuationExtraParams = {
deviceType: ["00E"]
};
continuationManager.register(continuationExtraParams, (err, data) => {
if (err.code != 0) {
console.error('register failed, cause: ' + JSON.stringify(err));
return;
}
console.info('register finished, ' + JSON.stringify(data));
token = data;
});
```
## continuationManager.register
register(options?: ContinuationExtraParams): Promise\<number>;
Registers the continuation management service and obtains a token. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | No| Extra parameters used to filter the list of available devices. This parameter can be null.|
**Return value**
| Type | Description |
| ------------------------- | ------------------ |
| Promise\<number> | Promise used to return the token generated after the continuation management service is connected.|
**Example**
```js
let token = -1;
let continuationExtraParams = {
deviceType: ["00E"]
};
continuationManager.register(continuationExtraParams)
.then((data) => {
console.info('register finished, ' + JSON.stringify(data));
token = data;
})
.catch((err) => {
console.error('register failed, cause: ' + JSON.stringify(err));
});
```
## continuationManager.on("deviceConnect")<sup>(deprecated)</sup>
> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondeviceconnect) instead.
on(type: "deviceConnect", callback: Callback\<ContinuationResult>): void;
Subscribes to device connection events. This API uses an asynchronous callback to return the result.
## continuationManager.on("deviceDisconnect")<sup>(deprecated)</sup>
> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondevicedisconnect) instead.
on(type: "deviceDisconnect", callback: Callback\<string>): void;
Subscribes to device disconnection events. This API uses an asynchronous callback to return the result.
## continuationManager.off("deviceConnect")<sup>(deprecated)</sup>
> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdeviceconnect) instead.
off(type: "deviceConnect", callback?: Callback\<ContinuationResult>): void;
Unsubscribes from device connection events. This API uses an asynchronous callback to return the result.
## continuationManager.off("deviceDisconnect")<sup>(deprecated)</sup>
> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdevicedisconnect) instead.
off(type: "deviceDisconnect", callback?: Callback\<string>): void;
Unsubscribes from device disconnection events. This API uses an asynchronous callback to return the result.
## continuationManager.on("deviceConnect")<sup>9+</sup>
on(type: "deviceConnect", token: number, callback: Callback\<Array\<ContinuationResult>>): void;
Subscribes to device connection events. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **deviceConnect**.|
| token | number | Yes| Token obtained after the registration of the continuation management service.|
| callback | Callback\<Array\<[ContinuationResult](js-apis-continuation-continuationResult.md)>> | Yes| Callback invoked when a device is selected from the device list provided by the device selection module. This callback returns the device ID, type, and name.|
**Example**
```js
let token = 1;
continuationManager.on("deviceConnect", token, (data) => {
console.info('onDeviceConnect len: ' + data.length);
for (let i = 0; i < data.length; i++) {
console.info('onDeviceConnect deviceId: ' + JSON.stringify(data[i].id));
console.info('onDeviceConnect deviceType: ' + JSON.stringify(data[i].type));
console.info('onDeviceConnect deviceName: ' + JSON.stringify(data[i].name));
}
});
```
## continuationManager.on("deviceDisconnect")<sup>9+</sup>
on(type: "deviceDisconnect", token: number, callback: Callback\<Array\<string>>): void;
Subscribes to device disconnection events. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **deviceDisconnect**.|
| token | number | Yes| Token obtained after the registration of the continuation management service.|
| callback | Callback\<Array\<string>> | Yes| Callback invoked when a device is disconnected in the device selection module. This callback returns the device ID.|
**Example**
```js
let token = 1;
continuationManager.on("deviceDisconnect", token, (data) => {
console.info('onDeviceDisconnect len: ' + data.length);
for (let i = 0; i < data.length; i++) {
console.info('onDeviceDisconnect deviceId: ' + JSON.stringify(data[i]));
}
console.info('onDeviceDisconnect finished.');
});
```
## continuationManager.off("deviceConnect")<sup>9+</sup>
off(type: "deviceConnect", token: number): void;
Unsubscribes from device connection events.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **deviceConnect**.|
| token | number | Yes| Token obtained after the registration of the continuation management service.|
**Example**
```js
let token = 1;
continuationManager.off("deviceConnect", token);
```
## continuationManager.off("deviceDisconnect")<sup>9+</sup>
off(type: "deviceDisconnect", token: number): void;
Unsubscribes from device disconnection events.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **deviceDisconnect**.|
| token | number | Yes| Token obtained after the registration of the continuation management service.|
**Example**
```js
let token = 1;
continuationManager.off("deviceDisconnect", token);
```
## continuationManager.startDeviceManager
startDeviceManager(token: number, callback: AsyncCallback\<void>): void;
Starts the device selection module to show the list of available devices on the network. This API does not involve any filter parameters and uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| token | number | Yes| Token obtained after the registration of the continuation management service.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Example**
```js
let token = 1;
continuationManager.startDeviceManager(token, (err, data) => {
if (err.code != 0) {
console.error('startDeviceManager failed, cause: ' + JSON.stringify(err));
return;
}
console.info('startDeviceManager finished, ' + JSON.stringify(data));
});
```
## continuationManager.startDeviceManager
startDeviceManager(token: number, options: ContinuationExtraParams, callback: AsyncCallback\<void>): void;
Starts the device selection module to show the list of available devices on the network. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| token | number | Yes| Token obtained after the registration of the continuation management service.|
| options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | Yes| Extra parameters used to filter the list of available devices.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Example**
```js
let token = 1;
let continuationExtraParams = {
deviceType: ["00E"]
};
continuationManager.startDeviceManager(token, continuationExtraParams, (err, data) => {
if (err.code != 0) {
console.error('startDeviceManager failed, cause: ' + JSON.stringify(err));
return;
}
console.info('startDeviceManager finished, ' + JSON.stringify(data));
});
```
## continuationManager.startDeviceManager
startDeviceManager(token: number, options?: ContinuationExtraParams): Promise\<void>;
Starts the device selection module to show the list of available devices on the network. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| token | number | Yes| Token obtained after the registration of the continuation management service.|
| options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | No| Extra parameters used to filter the list of available devices. This parameter can be null.|
**Return value**
| Type | Description |
| ------------------------- | ------------------ |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
let token = 1;
let continuationExtraParams = {
deviceType: ["00E"]
};
continuationManager.startDeviceManager(token, continuationExtraParams)
.then((data) => {
console.info('startDeviceManager finished, ' + JSON.stringify(data));
})
.catch((err) => {
console.error('startDeviceManager failed, cause: ' + JSON.stringify(err));
});
```
## continuationManager.updateConnectStatus
updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState, callback: AsyncCallback\<void>): void;
Instructs the device selection module to update the device connection state. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| token | number | Yes| Token obtained after the registration of the continuation management service.|
| deviceId | string | Yes| Device ID.|
| status | [DeviceConnectState](#deviceconnectstate) | Yes| Device connection state.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Example**
```js
let token = 1;
let deviceId: string = "test deviceId";
continuationManager.updateConnectStatus(token, deviceId, continuationManager.DeviceConnectState.CONNECTED, (err, data) => {
if (err.code != 0) {
console.error('updateConnectStatus failed, cause: ' + JSON.stringify(err));
return;
}
console.info('updateConnectStatus finished, ' + JSON.stringify(data));
});
```
## continuationManager.updateConnectStatus
updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState): Promise\<void>;
Instructs the device selection module to update the device connection state. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| token | number | Yes| Token obtained after the registration of the continuation management service.|
| deviceId | string | Yes| Device ID.|
| status | [DeviceConnectState](#deviceconnectstate) | Yes| Device connection state.|
**Return value**
| Type | Description |
| ------------------------- | ------------------ |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
let token = 1;
let deviceId: string = "test deviceId";
continuationManager.updateConnectStatus(token, deviceId, continuationManager.DeviceConnectState.CONNECTED)
.then((data) => {
console.info('updateConnectStatus finished, ' + JSON.stringify(data));
})
.catch((err) => {
console.error('updateConnectStatus failed, cause: ' + JSON.stringify(err));
});
```
## continuationManager.unregister
unregister(token: number, callback: AsyncCallback\<void>): void;
Deregisters the continuation management service. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| token | number | Yes| Token obtained after the registration of the continuation management service.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Example**
```js
let token = 1;
continuationManager.unregister(token, (err, data) => {
if (err.code != 0) {
console.error('unregister failed, cause: ' + JSON.stringify(err));
return;
}
console.info('unregister finished, ' + JSON.stringify(data));
});
```
## continuationManager.unregister
unregister(token: number): Promise\<void>;
Deregisters the continuation management service. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| token | number | Yes| Token obtained after the registration of the continuation management service.|
**Return value**
| Type | Description |
| ------------------------- | ------------------ |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
let token = 1;
continuationManager.unregister(token)
.then((data) => {
console.info('unregister finished, ' + JSON.stringify(data));
})
.catch((err) => {
console.error('unregister failed, cause: ' + JSON.stringify(err));
});
```
## DeviceConnectState
Enumerates the device connection states.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Value| Description|
| -------- | -------- | -------- | -------- |
| IDLE | number | 0 | The device is in the initial state.|
| CONNECTING | number | 1 | The device is being connected.|
| CONNECTED | number | 2 | The device is connected.|
| DISCONNECTING | number | 3 | The device is being disconnected.|
## ContinuationMode
Enumerates the continuation modes provided by the device selection module.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Value| Description|
| -------- | -------- | -------- | -------- |
| COLLABORATION_SINGLE | number | 0 | Single-choice mode.|
| COLLABORATION_MULTIPLE | number | 1 | Multi-choice mode.|
# ContinuationResult
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## ContinuationResult
Describes the device information returned by the continuation management entry.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| id | string | Yes| Yes| Device ID.|
| type | string | Yes| Yes| Device type.|
| name | string | Yes| Yes| Device name.|
# XML-to-JavaScript Conversion # XML-to-JavaScript Conversion
> **NOTE**<br/> The **convertxml** module provides APIs for converting XML text into JavaScript objects.
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -47,10 +50,10 @@ let xml = ...@@ -47,10 +50,10 @@ let xml =
'</note>'; '</note>';
let conv = new convertxml.ConvertXML(); let conv = new convertxml.ConvertXML();
let options = {trim : false, declarationKey:"_declaration", let options = {trim : false, declarationKey:"_declaration",
instructionKey : "_instruction", attributesKey : "_attributes", instructionKey : "_instruction", attributesKey : "_attributes",
textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype", textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype",
commentKey : "_comment", parentKey : "_parent", typeKey : "_type", commentKey : "_comment", parentKey : "_parent", typeKey : "_type",
nameKey : "_name", elementsKey : "_elements"} nameKey : "_name", elementsKey : "_elements"}
let result = JSON.stringify(conv.convert(xml, options)); let result = JSON.stringify(conv.convert(xml, options));
console.log(result) console.log(result)
``` ```
......
# Value Bucket # Value Bucket
The **ValueBucket** holds data in key-value (KV) pairs. You can use it to insert data into a database. The **ValueBucket** module holds data in key-value (KV) pairs. You can use it to insert data into a database.
>**Note** >**NOTE**
> >
>The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. >The 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.
...@@ -20,7 +20,7 @@ Enumerates the value types allowed by the database. ...@@ -20,7 +20,7 @@ Enumerates the value types allowed by the database.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core **System capability**: SystemCapability.DistributedDataManager.DataShare.Core
| Name | Description | | Type | Description |
| ------- | -------------------- | | ------- | -------------------- |
| number | The value is a number. | | number | The value is a number. |
| string | The value is a string.| | string | The value is a string.|
...@@ -28,10 +28,10 @@ Enumerates the value types allowed by the database. ...@@ -28,10 +28,10 @@ Enumerates the value types allowed by the database.
## ValuesBucket ## ValuesBucket
Holds a set of KV pairs. Defines the types of the key and value in a KV pair.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core **System capability**: SystemCapability.DistributedDataManager.DataShare.Core
| Name | Type | Mandatory| Description | | Key Type | Value Type |
| ------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | ------------- | --------------------------------------------- |
| [key: string] | [ValueType](#valuetype)\| Uint8Array \| null | Yes | KV pairs in a **ValuesBucket**. The key is of the string type. The value can be a number, string, Boolean value, Unit8Array, or **null**.| | string | [ValueType](#valuetype)\| Uint8Array \| null |
...@@ -789,7 +789,7 @@ Enumerates the value types. ...@@ -789,7 +789,7 @@ Enumerates the value types.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core **System capability**: SystemCapability.DistributedDataManager.DataShare.Core
| Name | Description | | Type | Description |
| ------- | -------------------- | | ------- | -------------------- |
| number | The value is a number. | | number | The value is a number. |
| string | The value is a string. | | string | The value is a string. |
......
...@@ -681,7 +681,7 @@ Enumerates the value types. ...@@ -681,7 +681,7 @@ Enumerates the value types.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core **System capability**: SystemCapability.DistributedDataManager.Preferences.Core
| Name | Description | | Type | Description |
| -------------- | ------------------------------ | | -------------- | ------------------------------ |
| number | The value is a number. | | number | The value is a number. |
| string | The value is a string. | | string | The value is a string. |
......
...@@ -781,13 +781,6 @@ Sets the **RdbPredicates** to filter out duplicate records. ...@@ -781,13 +781,6 @@ Sets the **RdbPredicates** to filter out duplicate records.
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose").distinct("NAME") predicates.equalTo("NAME", "Rose").distinct("NAME")
let promise = rdbStore.query(predicates, ["NAME"])
promise.then((resultSet) => {
console.log("ResultSet column names: " + resultSet.columnNames)
console.log("ResultSet column count: " + resultSet.columnCount)
}).catch((err) => {
console.log("Query err.")
})
``` ```
...@@ -1133,7 +1126,7 @@ rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { ...@@ -1133,7 +1126,7 @@ rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) {
``` ```
### update<sup>9+</sup> ### update<sup>9+</sup>
update(table: string, values: ValuesBucket, predicates: DataSharePredicates):Promise&lt;number&gt; update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates):Promise&lt;number&gt;
Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result.
...@@ -1215,7 +1208,7 @@ Deletes data from the RDB store based on the specified **RdbPredicates** object. ...@@ -1215,7 +1208,7 @@ Deletes data from the RDB store based on the specified **RdbPredicates** object.
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the number of rows updated.| | Promise&lt;number&gt; | Promise used to return the number of rows updated.|
**Example** **Example**
```js ```js
...@@ -1231,7 +1224,7 @@ promise.then((rows) => { ...@@ -1231,7 +1224,7 @@ promise.then((rows) => {
### delete<sup>9+</sup> ### delete<sup>9+</sup>
delete(table: string, predicates: DataSharePredicates, callback: AsyncCallback&lt;number&gt;):void delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;number&gt;):void
Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result.
...@@ -1275,7 +1268,7 @@ Deletes data from the RDB store based on the specified **DataSharePredicates** o ...@@ -1275,7 +1268,7 @@ Deletes data from the RDB store based on the specified **DataSharePredicates** o
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the number of rows updated.| | Promise&lt;number&gt; | Promise used to return the number of rows updated.|
**Example** **Example**
```js ```js
...@@ -1354,7 +1347,7 @@ Queries data in the RDB store based on specified conditions. This API uses a pro ...@@ -1354,7 +1347,7 @@ Queries data in the RDB store based on specified conditions. This API uses a pro
### query<sup>9+</sup> ### query<sup>9+</sup>
query(predicates: DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void
Queries data in the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. Queries data in the RDB store based on specified conditions. This API uses an asynchronous callback to return the result.
...@@ -1363,6 +1356,7 @@ Queries data in the RDB store based on specified conditions. This API uses an as ...@@ -1363,6 +1356,7 @@ Queries data in the RDB store based on specified conditions. This API uses an as
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| table | string | Yes| Name of the target table.|
| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Query conditions specified by the **DataSharePredicates** object.| | predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Query conditions specified by the **DataSharePredicates** object.|
| columns | Array&lt;string&gt; | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| | columns | Array&lt;string&gt; | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.|
| callback | AsyncCallback&lt;[ResultSet](js-apis-data-resultset.md)&gt; | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| | callback | AsyncCallback&lt;[ResultSet](js-apis-data-resultset.md)&gt; | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.|
...@@ -1384,7 +1378,7 @@ rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], ...@@ -1384,7 +1378,7 @@ rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"],
### query<sup>9+</sup> ### query<sup>9+</sup>
query(predicates: DataSharePredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSet&gt; query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSet&gt;
Queries data in the RDB store based on specified conditions. This API uses a promise to return the result. Queries data in the RDB store based on specified conditions. This API uses a promise to return the result.
...@@ -1393,6 +1387,7 @@ Queries data in the RDB store based on specified conditions. This API uses a pro ...@@ -1393,6 +1387,7 @@ Queries data in the RDB store based on specified conditions. This API uses a pro
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| table | string | Yes| Name of the target table.|
| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Query conditions specified by the **DataSharePredicates** object.| | predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Query conditions specified by the **DataSharePredicates** object.|
| columns | Array&lt;string&gt; | No| Columns to query. If this parameter is not specified, the query applies to all columns.| | columns | Array&lt;string&gt; | No| Columns to query. If this parameter is not specified, the query applies to all columns.|
...@@ -1591,7 +1586,7 @@ rdbStore.commit() ...@@ -1591,7 +1586,7 @@ rdbStore.commit()
### rollBack<sup>8+</sup> ### rollBack<sup>8+</sup>
rollBack():void; rollBack():void
Rolls back the SQL statements that have been executed. Rolls back the SQL statements that have been executed.
...@@ -1997,7 +1992,7 @@ Defines the data types allowed. ...@@ -1997,7 +1992,7 @@ Defines the data types allowed.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Name| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| number | Number.| | number | Number.|
| string | String.| | string | String.|
...@@ -2006,14 +2001,13 @@ Defines the data types allowed. ...@@ -2006,14 +2001,13 @@ Defines the data types allowed.
## ValuesBucket ## ValuesBucket
Defines a bucket to store key-value pairs. Defines the types of the key and value in a KV pair.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Name| Type| Mandatory| Description| | Key Type| Value Type|
| -------- | -------- | -------- | -------- | | -------- | -------- |
| [key:&nbsp;string] | [ValueType](#valuetype)\|&nbsp;Uint8Array&nbsp;\|&nbsp;null | Yes| Defines a bucket to store key-value pairs.| | string | [ValueType](#valuetype)\|&nbsp;Uint8Array&nbsp;\|&nbsp;null |
## SyncMode<sup>8+</sup> ## SyncMode<sup>8+</sup>
......
...@@ -793,7 +793,7 @@ Enumerates the value types. ...@@ -793,7 +793,7 @@ Enumerates the value types.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core **System capability**: SystemCapability.DistributedDataManager.Preferences.Core
| Name | Description | | Type | Description |
| ------- | -------------------- | | ------- | -------------------- |
| number | The value is a number. | | number | The value is a number. |
| string | The value is a string. | | string | The value is a string. |
......
...@@ -94,7 +94,7 @@ Updates distributed account information. This API uses an asynchronous callback ...@@ -94,7 +94,7 @@ Updates distributed account information. This API uses an asynchronous callback
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (available only to system applications) **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
- Parameters - Parameters
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -119,7 +119,7 @@ Updates distributed account information. This API uses a promise to return the r ...@@ -119,7 +119,7 @@ Updates distributed account information. This API uses a promise to return the r
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (available only to system applications) **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
- Parameters - Parameters
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
......
# Environment # Environment
This module provides JS APIs for obtaining the root directories of the storage and public files.
> **NOTE** > **NOTE**
> >
> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module are system APIs and cannot be called by third-party applications. > - The APIs of this module are system APIs and cannot be called by third-party applications.
This module provides JS APIs for obtaining the root directories of the storage and public files.
## Modules to Import ## Modules to Import
```js ```js
......
...@@ -17,15 +17,31 @@ import fileio from '@ohos.fileio'; ...@@ -17,15 +17,31 @@ import fileio from '@ohos.fileio';
Before using the APIs provided by this module to perform operations on files or directories, obtain the path of the application sandbox as follows: Before using the APIs provided by this module to perform operations on files or directories, obtain the path of the application sandbox as follows:
Stage Model
```js
import Ability from '@ohos.application.Ability';
class MainAbility extends Ability {
onWindowStageCreate(windowStage) {
let context = this.context;
let path = context.filesDir;
}
}
```
For details about how to obtain the stage model context, see [Stage Model](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-ability-context.md#abilitycontext).
FA Model
```js ```js
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context = featureAbility.getContext();
let path = '';
context.getFilesDir().then((data) => { context.getFilesDir().then((data) => {
path = data; let path = data;
}) })
``` ```
For details about how to obtain the context of the FA model, see [FA Model](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-Context.md#context).
## fileio.stat ## fileio.stat
...@@ -654,7 +670,7 @@ Reads data from a file. This API uses a promise to return the result. ...@@ -654,7 +670,7 @@ Reads data from a file. This API uses a promise to return the result.
let fd = fileio.openSync(path, 0o2); let fd = fileio.openSync(path, 0o2);
let buf = new ArrayBuffer(4096); let buf = new ArrayBuffer(4096);
fileio.read(fd, buf).then(function(readOut){ fileio.read(fd, buf).then(function(readOut){
console.info("Read file data"); console.info("Read file data successfully");
console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer)));
}).catch(function(err){ }).catch(function(err){
console.info("Failed to read file data. Error:"+ err); console.info("Failed to read file data. Error:"+ err);
...@@ -690,7 +706,7 @@ Reads data from a file. This API uses an asynchronous callback to return the res ...@@ -690,7 +706,7 @@ Reads data from a file. This API uses an asynchronous callback to return the res
let buf = new ArrayBuffer(4096); let buf = new ArrayBuffer(4096);
fileio.read(fd, buf, function (err, readOut) { fileio.read(fd, buf, function (err, readOut) {
if (readOut) { if (readOut) {
console.info("Read file data"); console.info("Read file data successfully");
console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer)));
} }
}); });
...@@ -1263,7 +1279,7 @@ Truncates a file based on the file descriptor. This API uses an asynchronous cal ...@@ -1263,7 +1279,7 @@ Truncates a file based on the file descriptor. This API uses an asynchronous cal
| -------- | ------------------------- | ---- | ---------------- | | -------- | ------------------------- | ---- | ---------------- |
| fd | number | Yes | File descriptor of the file to truncate. | | fd | number | Yes | File descriptor of the file to truncate. |
| len | number | Yes | File length, in bytes, after truncation.| | len | number | Yes | File length, in bytes, after truncation.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value.|
**Example** **Example**
...@@ -1347,7 +1363,7 @@ Truncates a file based on the file path. This API uses an asynchronous callback ...@@ -1347,7 +1363,7 @@ Truncates a file based on the file path. This API uses an asynchronous callback
| -------- | ------------------------- | ---- | -------------------------------- | | -------- | ------------------------- | ---- | -------------------------------- |
| path | string | Yes | Application sandbox path of the file to truncate.| | path | string | Yes | Application sandbox path of the file to truncate.|
| len | number | Yes | File length, in bytes, after truncation.| | len | number | Yes | File length, in bytes, after truncation.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value.|
**Example** **Example**
...@@ -1411,7 +1427,7 @@ Reads the text content of a file. This API uses a promise to return the result. ...@@ -1411,7 +1427,7 @@ Reads the text content of a file. This API uses a promise to return the result.
```js ```js
fileio.readText(path).then(function(str) { fileio.readText(path).then(function(str) {
console.info("Read text:"+ str); console.info("Read text successfully:"+ str);
}).catch(function(err){ }).catch(function(err){
console.info("Failed to read the text. Error:"+ err); console.info("Failed to read the text. Error:"+ err);
}); });
...@@ -2159,7 +2175,7 @@ Opens a file stream based on the file path. This API uses a promise to return th ...@@ -2159,7 +2175,7 @@ Opens a file stream based on the file path. This API uses a promise to return th
| Type | Description | | Type | Description |
| --------------------------------- | --------- | | --------------------------------- | --------- |
| Promise&lt;[Stream](#stream7)&gt; | Promise used to return the result.| | Promise&lt;[Stream](#stream)&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -2186,7 +2202,7 @@ Opens a file stream based on the file path. This API uses an asynchronous callba ...@@ -2186,7 +2202,7 @@ Opens a file stream based on the file path. This API uses an asynchronous callba
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| path | string | Yes | Application sandbox path of the file. | | path | string | Yes | Application sandbox path of the file. |
| mode | string | Yes | -&nbsp;**r**: Open a file for reading. The file must exist.<br>-&nbsp;**r+**: Open a file for both reading and writing. The file must exist.<br>-&nbsp;**w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.<br>-&nbsp;**w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.<br>-&nbsp;**a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).<br>-&nbsp;**a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| | mode | string | Yes | -&nbsp;**r**: Open a file for reading. The file must exist.<br>-&nbsp;**r+**: Open a file for both reading and writing. The file must exist.<br>-&nbsp;**w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.<br>-&nbsp;**w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.<br>-&nbsp;**a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).<br>-&nbsp;**a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).|
| callback | AsyncCallback&lt;[Stream](#stream7)&gt; | Yes | Callback invoked when the stream is open asynchronously. | | callback | AsyncCallback&lt;[Stream](#stream)&gt; | Yes | Callback invoked when the stream is open asynchronously. |
**Example** **Example**
...@@ -2216,7 +2232,7 @@ Synchronously opens a stream based on the file path. ...@@ -2216,7 +2232,7 @@ Synchronously opens a stream based on the file path.
| Type | Description | | Type | Description |
| ------------------ | --------- | | ------------------ | --------- |
| [Stream](#stream7) | Stream opened.| | [Stream](#stream) | Stream opened.|
**Example** **Example**
...@@ -2244,7 +2260,7 @@ Opens a file stream based on the file descriptor. This API uses a promise to ret ...@@ -2244,7 +2260,7 @@ Opens a file stream based on the file descriptor. This API uses a promise to ret
| Type | Description | | Type | Description |
| --------------------------------- | --------- | | --------------------------------- | --------- |
| Promise&lt;[Stream](#stream7)&gt; | Promise used to return the result.| | Promise&lt;[Stream](#stream)&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -2272,7 +2288,7 @@ Opens a file stream based on the file descriptor. This API uses an asynchronous ...@@ -2272,7 +2288,7 @@ Opens a file stream based on the file descriptor. This API uses an asynchronous
| -------- | ---------------------------------------- | ---- | ---------------------------------------- | | -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| fd | number | Yes | File descriptor of the target file. | | fd | number | Yes | File descriptor of the target file. |
| mode | string | Yes | -&nbsp;**r**: Open a file for reading. The file must exist.<br>-&nbsp;**r+**: Open a file for both reading and writing. The file must exist.<br>-&nbsp;**w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.<br>-&nbsp;**w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.<br>-&nbsp;**a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).<br>-&nbsp;**a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| | mode | string | Yes | -&nbsp;**r**: Open a file for reading. The file must exist.<br>-&nbsp;**r+**: Open a file for both reading and writing. The file must exist.<br>-&nbsp;**w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.<br>-&nbsp;**w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.<br>-&nbsp;**a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).<br>-&nbsp;**a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).|
| callback | AsyncCallback&nbsp;&lt;[Stream](#stream7)&gt; | Yes | Callback invoked when the stream is open asynchronously. | | callback | AsyncCallback&nbsp;&lt;[Stream](#stream)&gt; | Yes | Callback invoked when the stream is open asynchronously. |
**Example** **Example**
...@@ -2303,7 +2319,7 @@ Synchronously opens a stream based on the file descriptor. ...@@ -2303,7 +2319,7 @@ Synchronously opens a stream based on the file descriptor.
| Type | Description | | Type | Description |
| ------------------ | --------- | | ------------------ | --------- |
| [Stream](#stream7) | Stream opened.| | [Stream](#stream) | Stream opened.|
**Example** **Example**
...@@ -2720,7 +2736,7 @@ Stops the **watcher** instance. This API uses a promise to return the result. ...@@ -2720,7 +2736,7 @@ Stops the **watcher** instance. This API uses a promise to return the result.
```js ```js
let filename = path +"/test.txt"; let filename = path +"/test.txt";
let watcher = await fileio.createWatcher(filename, 1, function(number){ let watcher = fileio.createWatcher(filename, 1, function(number){
console.info("Monitoring times: "+number); console.info("Monitoring times: "+number);
}); });
watcher.stop().then(function(){ watcher.stop().then(function(){
...@@ -2747,7 +2763,7 @@ Stops the **watcher** instance. This API uses an asynchronous callback to return ...@@ -2747,7 +2763,7 @@ Stops the **watcher** instance. This API uses an asynchronous callback to return
```js ```js
let filename = path +"/test.txt"; let filename = path +"/test.txt";
let watcher = await fileio.createWatcher(filename, 1, function(number){ let watcher = fileio.createWatcher(filename, 1, function(number){
console.info("Monitoring times: "+number); console.info("Monitoring times: "+number);
}); });
watcher.stop(function(){ watcher.stop(function(){
...@@ -3124,7 +3140,6 @@ Reads the next directory entry. This API uses a promise to return the result. ...@@ -3124,7 +3140,6 @@ Reads the next directory entry. This API uses a promise to return the result.
**Example** **Example**
```js ```js
let dir = fileio.opendirSync(path);
dir.read().then(function (dirent){ dir.read().then(function (dirent){
console.log("Read the next directory entry:"+JSON.stringify(dirent)); console.log("Read the next directory entry:"+JSON.stringify(dirent));
}).catch(function(err){ }).catch(function(err){
...@@ -3150,7 +3165,6 @@ Reads the next directory entry. This API uses an asynchronous callback to return ...@@ -3150,7 +3165,6 @@ Reads the next directory entry. This API uses an asynchronous callback to return
**Example** **Example**
```js ```js
let dir = fileio.opendirSync(path);
dir.read(function (err, dirent) { dir.read(function (err, dirent) {
if (dirent) { if (dirent) {
// Do something // Do something
...@@ -3177,7 +3191,6 @@ Synchronously reads the next directory entry. ...@@ -3177,7 +3191,6 @@ Synchronously reads the next directory entry.
**Example** **Example**
```js ```js
let dir = fileio.opendirSync(path);
let dirent = dir.readSync(); let dirent = dir.readSync();
``` ```
...@@ -3193,7 +3206,6 @@ Closes a directory. This API uses a promise to return the result. After a direct ...@@ -3193,7 +3206,6 @@ Closes a directory. This API uses a promise to return the result. After a direct
**Example** **Example**
```js ```js
let dir = fileio.opendirSync(path);
dir.close().then(function(err){ dir.close().then(function(err){
console.info("close dir successfully"); console.info("close dir successfully");
}); });
...@@ -3211,7 +3223,6 @@ Closes a directory. This API uses an asynchronous callback to return the result. ...@@ -3211,7 +3223,6 @@ Closes a directory. This API uses an asynchronous callback to return the result.
**Example** **Example**
```js ```js
let dir = fileio.opendirSync(path);
dir.close(function(err){ dir.close(function(err){
console.info("close dir successfully"); console.info("close dir successfully");
}); });
...@@ -3229,7 +3240,6 @@ Closes a directory. After a directory is closed, the file descriptor in Dir will ...@@ -3229,7 +3240,6 @@ Closes a directory. After a directory is closed, the file descriptor in Dir will
**Example** **Example**
```js ```js
let dir = fileio.opendirSync(path);
dir.closeSync(); dir.closeSync();
``` ```
......
...@@ -673,6 +673,32 @@ Formats a phone number. ...@@ -673,6 +673,32 @@ Formats a phone number.
phonenumberfmt.format("15812312312"); phonenumberfmt.format("15812312312");
``` ```
### getLocationName<sup>8+</sup>
static getLocationName(number: string, locale: string): string
Obtains the home location of a phone number.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ---------- |
| number | string | Yes | Phone number.|
| locale | string | Yes | Locale ID.|
**Return value**
| Type | Description |
| ------ | ---------- |
| string | Home location of the phone number.|
**Example**
```
var location = i18n.PhoneNumberFormat.getLocationName('15812312345', 'zh-CN');
```
## PhoneNumberFormatOptions<sup>8+</sup> ## PhoneNumberFormatOptions<sup>8+</sup>
......
...@@ -127,7 +127,7 @@ ...@@ -127,7 +127,7 @@
- Canvas Components - Canvas Components
- [Canvas](ts-components-canvas-canvas.md) - [Canvas](ts-components-canvas-canvas.md)
- [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md) - [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md)
- [OffscreenCanvasRenderingConxt2D](ts-offscreencanvasrenderingcontext2d.md) - [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md)
- [Lottie](ts-components-canvas-lottie.md) - [Lottie](ts-components-canvas-lottie.md)
- [Path2D](ts-components-canvas-path2d.md) - [Path2D](ts-components-canvas-path2d.md)
- [CanvasGradient](ts-components-canvas-canvasgradient.md) - [CanvasGradient](ts-components-canvas-canvasgradient.md)
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册