提交 b161a666 编写于 作者: K king_he 提交者: Gitee

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

要显示的变更太多。

To preserve performance only 1000 of 1000+ files are displayed.
......@@ -23,11 +23,17 @@ zh-cn/device-dev/quick-start/ @li-yan339
zh-cn/device-dev/driver/ @li-yan339
zh-cn/device-dev/get-code/ @li-yan339
zh-cn/device-dev/hpm-part/ @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-build-mini-lite.md @Austin23
zh-cn/device-dev/subsystems/subsys-build-standard-large.md @Austin23
zh-cn/device-dev/subsystems/subsys-build-gn-coding-style-and-best-practice.md @Austin23
zh-cn/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guid.md @Austin23
zh-cn/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md @Austin23
zh-cn/device-dev/reference/hdi-apis/ @li-yan339
zh-cn/device-dev/quick-start/quickstart-standard-env-setup.md @li-yan339 @chenmudan
zh-cn/device-dev/quick-start/quickstart-lite-env-setup.md @li-yan339 @chenmudan
zh-cn/device-dev/porting/porting-thirdparty-overview.md @Austin23 @chenmudan
zh-cn/device-dev/porting/porting-thirdparty-makefile.md @Austin23 @chenmudan
zh-cn/device-dev/porting/porting-thirdparty-cmake.md @Austin23 @chenmudan
zh-cn/device-dev/subsystems/subsys-build-mini-lite.md @Austin23 @chenmudan
zh-cn/device-dev/subsystems/subsys-build-standard-large.md @Austin23 @chenmudan
zh-cn/device-dev/subsystems/subsys-build-gn-coding-style-and-best-practice.md @Austin23 @chenmudan
zh-cn/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guid.md @Austin23 @chenmudan
zh-cn/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md @Austin23 @chenmudan
zh-cn/device-dev/subsystems/subsys-remote-start.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-graphics-overview.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-graphics-container-guide.md @duangavin123_admin
......@@ -45,7 +51,7 @@ zh-cn/device-dev/subsystems/subsys-utils-overview.md @Austin23
zh-cn/device-dev/subsystems/subsys-utils-guide.md @Austin23
zh-cn/device-dev/subsystems/subsys-utils-faqs.md @Austin23
zh-cn/device-dev/subsystems/subsys-aiframework-guide.md @Austin23
zh-cn/device-dev/subsystems/subsys-aiframework-envbuild.md @Austin23
zh-cn/device-dev/subsystems/subsys-aiframework-envbuild.md @Austin23
zh-cn/device-dev/subsystems/subsys-aiframework-tech-codemanage.md @Austin23
zh-cn/device-dev/subsystems/subsys-aiframework-tech-name.md @Austin23
zh-cn/device-dev/subsystems/subsys-aiframework-tech-interface.md @Austin23
......@@ -79,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-communicationverify.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-standard.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-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.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-hilog-rich.md @duangavin123_admin
......@@ -200,7 +211,7 @@ zh-cn/application-dev/reference/apis/js-apis-screenshot.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-window.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-screen.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-webgl.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-webgl2.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-audio.md @zengyawen
......
......@@ -18,7 +18,7 @@
- master:最新开发版本。
- OpenHarmony 3.2 Beta1版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta1.md)了解版本详情。
- OpenHarmony 3.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta2.md)了解版本详情。
- OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。
......
此差异已折叠。
......@@ -15,7 +15,6 @@
- Development Fundamentals
- [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md)
- [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md)
- [Resource File Categories](quick-start/basic-resource-file-categories.md)
- [SysCap](quick-start/syscap.md)
- Development
- [Ability Development](ability/Readme-EN.md)
......@@ -45,8 +44,5 @@
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
- APIs
- [JS and TS APIs](reference/apis/Readme-EN.md)
- Native APIs
- [Standard Library](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md)
- Contribution
- [How to Contribute](../contribute/documentation-contribution.md)
......@@ -4,8 +4,8 @@ An ability is the abstraction of a functionality that an application can provide
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.
- 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.
- 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 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.
......
......@@ -78,29 +78,29 @@ To create Page abilities for an application in the stage model, you must impleme
onCreate(want, launchParam) {
console.log("MainAbility onCreate")
}
onDestroy() {
console.log("MainAbility onDestroy")
}
onWindowStageCreate(windowStage) {
console.log("MainAbility onWindowStageCreate")
windowStage.loadContent("pages/index").then((data) => {
console.log("MainAbility load content succeed with data: " + JSON.stringify(data))
}).catch((error) => {
console.error("MainAbility load content failed with error: " + JSON.stringify(error))
})
}
onWindowStageDestroy() {
console.log("MainAbility onWindowStageDestroy")
}
onForeground() {
console.log("MainAbility onForeground")
}
onBackground() {
console.log("MainAbility onBackground")
}
......@@ -300,7 +300,7 @@ export default class MainAbility extends Ability {
Obtain the `want` parameter that contains the page information from the custom component and process the route based on the URI.
```ts
import router from '@system.router'
import router from '@ohos.router'
@Entry
@Component
......
......@@ -54,8 +54,10 @@ 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.
They are organized as follows:
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
- APIs
- [JS and TS APIs](reference/apis/Readme-EN.md)
- Native APIs
......
......@@ -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.
They are organized as follows:
- [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)
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.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)
......@@ -19,4 +19,4 @@ In OpenHarmony documents, proxy represents the service requester, and stub repre
## Related Modules
[Distributed Scheduler](https://gitee.com/openharmony/distributedschedule_dms_fwk)
[Distributed Scheduler](https://gitee.com/openharmony/ability_dmsfwk)
# 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 {
public:
virtual void OnRemoteDied(const wptr<IRemoteObject>& remoteObject);
}
sptr<IRemoteObject::DeathRecipient> deathRecipient (new TestDeathRecipient()); // Construct a death notification recipient.
bool result = proxy->AddDeathRecipient(deathRecipient); // Add the recipient to the proxy.
result = proxy->RemoveDeathRecipient(deathRecipient); // Remove the recipient.
sptr<IRemoteObject::DeathRecipient> deathRecipient (new TestDeathRecipient());// Construct a death notification recipient.
bool result = proxy->AddDeathRecipient(deathRecipient); // Add a recipient for death notifications.
result = proxy->RemoveDeathRecipient(deathRecipient); // Remove the recipient for death notifications.
```
......@@ -3,7 +3,7 @@
## 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.
......@@ -18,14 +18,14 @@ The WebSocket connection function is mainly implemented by the WebSocket module.
| connect() | Establishes a WebSocket connection to a given URL. |
| send() | Sends data through the WebSocket connection. |
| close() | Closes a WebSocket connection. |
| on(type:&nbsp;'open') | Enables listening for **open** events of a WebSocket connection. |
| off(type:&nbsp;'open') | Disables listening for **open** events of a WebSocket connection. |
| on(type:&nbsp;'message') | Enables listening for **message** events of a WebSocket connection. |
| off(type:&nbsp;'message') | Disables listening for **message** events of a WebSocket connection. |
| on(type:&nbsp;'close') | Enables listening for **close** events of a WebSocket connection. |
| off(type:&nbsp;'close') | Disables listening for **close** events of a WebSocket connection. |
| on(type:&nbsp;'error') | Enables listening for **error** events of a WebSocket connection. |
| off(type:&nbsp;'error') | Disables listening for **error** events of a WebSocket connection. |
| on(type: 'open') | Enables listening for **open** events of a WebSocket connection. |
| off(type: 'open') | Disables listening for **open** events of a WebSocket connection. |
| on(type: 'message') | Enables listening for **message** events of a WebSocket connection. |
| off(type: 'message') | Disables listening for **message** events of a WebSocket connection. |
| on(type: 'close') | Enables listening for **close** events of a WebSocket connection. |
| off(type: 'close') | Disables listening for **close** events of a WebSocket connection. |
| on(type: 'error') | Enables listening for **error** events of a WebSocket connection. |
| off(type: 'error') | Disables listening for **error** events of a WebSocket connection. |
## How to Develop
......@@ -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.
ws.send("Hello, server!", (err, value) => {
if (!err) {
console.log("send success");
console.log("Message sent successfully");
} 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.
if (value === 'bye') {
ws.close((err, value) => {
if (!err) {
console.log("close success");
console.log("Connection closed successfully");
} 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.
});
ws.connect(defaultIpAddress, (err, value) => {
if (!err) {
console.log("connect success");
console.log("Connected successfully");
} else {
console.log("connect fail, err:" + JSON.stringify(err));
console.log("Connection failed. Err:" + JSON.stringify(err));
}
});
```
......@@ -7,6 +7,8 @@ The distributed data objects allow data across devices to be processed like loca
## Available APIs
For details about the APIs related to the distributed data object, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md).
### Creating a Distributed Data Object Instance
Call **createDistributedObject()** to create a distributed data object instance. You can specify the attributes of the instance in **source**.
......@@ -15,7 +17,7 @@ Call **createDistributedObject()** to create a distributed data object instance.
**Table 1** API for creating a distributed data object instance
| Package| API| Description|
| -------- | -------- | -------- |
| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>-&nbsp;**source**: attributes of the **distributedObject** set.<br>-&nbsp;**DistributedObject**: returns the distributed object created.|
| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>- **source**: attributes of the **distributedObject** set.<br>- **DistributedObject**: returns the distributed object created.|
### Generating a Session ID
......@@ -33,16 +35,16 @@ Call **setSessionId()** to set a session ID for a distributed data object. The s
**Table 3** API for setting a session ID
| Class| API| Description|
| -------- | -------- | -------- |
| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.<br>&nbsp;**sessionId**: session ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.<br> **sessionId**: session ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
### Observing Data Changes
Call **on()** to subscribe to data changes of a distributed data object. When the data changes, a callback will be invoked to return the data changes. You can use **off()** to unsubscribe from the data changes.
**Table 4** APIs for observing data changes of a distributed data object
| Class| API| Description|
| Class| API| Description|
| -------- | -------- | -------- |
| DistributedDataObject| on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Subscribes to data changes.|
| DistributedDataObject| on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Subscribes to data changes.|
| DistributedDataObject| off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Unsubscribes from data changes. **Callback**: specifies callback used to return changes of the distributed data object. If this parameter is not specified, all callbacks related to data changes will be unregistered.|
### Observing Online or Offline Status
......@@ -67,13 +69,13 @@ The saved data will be released in the following cases:
- The application has been uninstalled.
- Data is successfully restored.
**Table 6** APIs for saving a distributed data object and revoking the saving
**Table 6** APIs for saving a distributed data object and revoking the saving operation
| Class| API| Description|
| -------- | -------- | -------- |
| DistributedDataObject | save(deviceId: string): Promise&lt;SaveSuccessResponse&gt; | Saves a distributed data object. This API uses a promise to return the result.|
| DistributedDataObject| save(deviceId: string, callback: AsyncCallback&lt;SaveSuccessResponse&gt;): void | Saves a distributed data object. This API uses an asynchronous callback to return the result.|
| DistributedDataObject | revokeSave(callback: AsyncCallback&lt;RevokeSaveSuccessResponse&gt;): void | Revokes the data saving operation. This API uses an asynchronous callback to return the result. |
| DistributedDataObject| revokeSave(): Promise&lt;RevokeSaveSuccessResponse&gt; | Revokes the data saving operation. This API uses a promise to return the result. |
| DistributedDataObject | revokeSave(callback: AsyncCallback&lt;RevokeSaveSuccessResponse&gt;): void | Revokes the data saving operation. This API uses an asynchronous callback to return the result.|
| DistributedDataObject| revokeSave(): Promise&lt;RevokeSaveSuccessResponse&gt; | Revokes the data saving operation. This API uses a promise to return the result.|
## How to Develop
......@@ -157,7 +159,7 @@ The following example shows how to implement a distributed data object synchroni
local_object.on("change", this.changeCallback.bind(this));
```
6. Modify object attributes. <br>The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types).
6. Modify object attributes. <br>The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types).
The sample code is as follows:
```js
......@@ -205,41 +207,39 @@ The following example shows how to implement a distributed data object synchroni
10. Save a distributed data object and revoke the data saving operation.
- Callback
```js
// Save a distributed data object.
local_object.save("local", (result, data)=>{
console.log("save callback");
console.info("save sessionId " + data.sessionId);
console.info("save version " + data.version);
console.info("save deviceId " + data.deviceId);
});
// Revoke the data saving operation.
local_object.revokeSave((result, data) =>{
console.log("revokeSave callback");
console.info("revokeSave sessionId " + data.sessionId);
});
```
- Promise
```js
// Save a distributed data object.
g_object.save("local").then((result)=>{
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}, (result)=>{
console.info("save local failed.");
});
// Revoke the data saving operation.
g_object.revokeSave().then((result)=>{
console.info("revokeSave success.");
}, (result)=>{
console.info("revokeSave failed.");
});
```
11. Unsubscribe from the status changes of the distributed data object. <br>You can specify the callback to unregister. If you do not specify the callback, this API unregister all callbacks of this distributed data object.
```js
// Save a distributed data object.
local_object.save("local", (result, data)=>{
console.log("save callback");
console.info("save sessionId " + data.sessionId);
console.info("save version " + data.version);
console.info("save deviceId " + data.deviceId);
});
// Revoke the data saving operation.
local_object.revokeSave((result, data) =>{
console.log("revokeSave callback");
console.info("revokeSave sessionId " + data.sessionId);
});
```
- Promise
```js
// Save a distributed data object.
g_object.save("local").then((result)=>{
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}, (result)=>{
console.info("save local failed.");
});
// Revoke the data saving operation.
g_object.revokeSave().then((result)=>{
console.info("revokeSave success.");
}, (result)=>{
console.info("revokeSave failed.");
});
```
11. Unsubscribe from the status changes of the distributed data object. <br>You can specify the callback to unregister. If you do not specify the callback, this API unregisters all callbacks of this distributed data object.
The sample code is as follows:
```js
......
......@@ -7,19 +7,21 @@ The Distributed Data Service (DDS) implements synchronization of application dat
## Available APIs
For details about the APIs related to distributed data, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md).
The table below describes the APIs provided by the OpenHarmony DDS module.
**Table 1** APIs provided by the DDS
| Category | API | Description |
| -------- | --- | ----------- |
| Creating a distributed database | createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KVManager** object for database management.|
| Obtaining a distributed KV store | getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Obtains the KV store with the specified **Options** and **storeId**. |
| Managing data in a distributed KV store | put(key: string, value: Uint8Array \| string \| number \| boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array \| string \| number \| boolean): Promise&lt;void> | Inserts and updates data. |
| Category | API | Description |
| ------------ | ------------- | ------------- |
| Creating a distributed database| createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KVManager** object for database management.|
| Obtaining a distributed KV store| getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Obtains the KV store with the specified **Options** and **storeId**.|
| Managing data in a distributed KV store| put(key: string, value: Uint8Array \| string \| number \| boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array \| string \| number \| boolean): Promise&lt;void> | Inserts and updates data.|
| Managing data in a distributed KV store| delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. |
| Managing data in a distributed KV store | get(key: string, callback: AsyncCallback&lt;Uint8Array \| string \| boolean \| number&gt;): void<br>get(key: string): Promise&lt;Uint8Array \| string \| boolean \| number> | Queries data. |
| Subscribing to changes in the distributed data | on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;ChangeNotification&gt;): void<br>on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string, number]&gt;&gt;): void | Subscribes to data changes in the KV store. |
| Synchronizing data across devices | sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. |
| Managing data in a distributed KV store| get(key: string, callback: AsyncCallback&lt;Uint8Array \| string \| boolean \| number&gt;): void<br>get(key: string): Promise&lt;Uint8Array \| string \| boolean \| number> | Queries data. |
| Subscribing to changes in the distributed data| on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;ChangeNotification&gt;): void<br>on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string, number]&gt;&gt;): void | Subscribes to data changes in the KV store.|
| Synchronizing data across devices| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. |
......@@ -29,14 +31,13 @@ The table below describes the APIs provided by the OpenHarmony DDS module.
The following uses a single KV store as an example to describe the development procedure.
1. Import the distributed data module.
```js
import distributedData from '@ohos.data.distributedData';
```
2. Create a **KvManager** instance based on the specified **KvManagerConfig** object.
1. Create a **KvManagerConfig** object based on the application context.
2. Create a **KvManager** instance.
(1) Create a **KvManagerConfig** object based on the application context.
(2) Create a **KvManager** instance.
The sample code is as follows:
```js
......@@ -63,8 +64,8 @@ The following uses a single KV store as an example to describe the development p
```
3. Create and obtain a single KV store.
1. Declare the ID of the single KV store to create.
2. Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required.
(1) Declare the ID of the single KV store to create.
(2) Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required.
The sample code is as follows:
```js
......@@ -91,12 +92,11 @@ The following uses a single KV store as an example to describe the development p
}
```
> ![icon-note.gif](../public_sys-resources/icon-note.gif) **NOTE**<br/>
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (**kvStore** in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle.
4. Subscribe to changes in the distributed data.<br/>
4. Subscribe to changes in the distributed data.<br/>
The following is the sample code for subscribing to the data changes of a single KV store:
```js
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
console.log("dataChange callback call data: " + JSON.stringify(data));
......@@ -104,8 +104,8 @@ The following uses a single KV store as an example to describe the development p
```
5. Write data to the single KV store.
1. Construct the key and value to be written into the single KV store.
2. Write key-value pairs into the single KV store.
(1) Construct the key and value to be written into the single KV store.
(2) Write key-value pairs into the single KV store.
The following is the sample code for writing key-value pairs of the string type into the single KV store:
......@@ -126,11 +126,10 @@ The following uses a single KV store as an example to describe the development p
```
6. Query data in the single KV store.
1. Construct the key to be queried from the single KV store.
2. Query data from the single KV store.
(1) Construct the key to be queried from the single KV store.
(2) Query data from the single KV store.
The following is the sample code for querying data of the string type from the single KV store:
```js
const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
......@@ -178,3 +177,7 @@ The following uses a single KV store as an example to describe the development p
}
});
```
## Samples
The following samples are provided to help you better understand the distributed data development:
- [`KvStore`: Distributed Database (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Kvstore)
- [Distributed Database](https://gitee.com/openharmony/codelabs/tree/master/Data/JsDistributedData)
......@@ -34,7 +34,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
| Class| API| Description|
| -------- | -------- | -------- |
| RdbStore | insert(table: string, values: ValuesBucket, callback: AsyncCallback&lt;number&gt;):void | Inserts a row of data into a table. This API uses a callback to return the result.<br>- **table**: name of the target table.<br>- **values**: data to be inserted into the table.<br>- **callback**: callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.|
| RdbStore | insert(table: string, values: ValuesBucket, callback: AsyncCallback&lt;number&gt;):void | Inserts a row of data into a table. This API uses a callback to return the result.<br>- **table**: name of the target table.<br>- **values**: data to be inserted into the table.<br>- **callback**: callback invoked to return the result. If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.|
| RdbStore | insert(table: string, values: ValuesBucket): Promise&lt;number&gt; | Inserts a row of data into a table. This API uses a promise to return the result.<br>- **table**: name of the target table.<br>- **values**: data to be inserted into the table.|
- **Updating data**
......@@ -190,7 +190,7 @@ You can obtain the distributed table name for a remote device based on the local
| -------- | -------- | -------- |
| RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback\<Array\<string>>): void;| Unregisters the observer of the specified type for the RDB store. This API uses a callback to return the result.<br>- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** means to subscribe to remote data changes.<br>- **observer**: observer to unregister.|
### Backing Up and Restore an RDB Store
### Backing Up and Restoring an RDB Store
**Backing Up an RDB Store**
......@@ -198,8 +198,8 @@ You can obtain the distributed table name for a remote device based on the local
| Class| API| Description|
| -------- | -------- | -------- |
| RdbStore |backup(destName:string, callback: AsyncCallback&lt;void&gt;):void| Backs up the RDB store with the specified name. This API uses an asynchronous callback to return the result.<br>- **destName**: name of the RDB backup file.<br>- **callback**: callback invoked to return the result.|
| RdbStore |backup(destName:string): Promise&lt;void&gt;| Backs up the RDB store with the specified name. This API uses a promise to return the result.<br>- **destName**: name of the RDB backup file.|
| RdbStore |backup(destName:string, callback: AsyncCallback&lt;void&gt;):void| Backs up an RDB store. This API uses an asynchronous callback to return the result.<br>- **destName**: name of the RDB backup file.<br>- **callback**: callback invoked to return the result.|
| RdbStore |backup(destName:string): Promise&lt;void&gt;| Backs up an RDB store. This API uses a promise to return the result.<br>- **destName**: name of the RDB backup file.|
**Restoring an RDB Store**
......@@ -207,8 +207,8 @@ You can obtain the distributed table name for a remote device based on the local
| Class| API| Description|
| -------- | -------- | -------- |
| RdbStore |restore(srcName:string, callback: AsyncCallback&lt;void&gt;):void| Restores an RDB store using the specified backup file. This API uses an asynchronous callback to return the result.<br>- **srcName**: name of the RDB backup file.<br>- **callback**: callback invoked to return the result.|
| RdbStore |restore(srcName:string): Promise&lt;void&gt;| Restores an RDB store using the specified backup file. This API uses a promise to return the result.<br>- **srcName**: name of the RDB backup file.|
| RdbStore |restore(srcName:string, callback: AsyncCallback&lt;void&gt;):void| Restores an RDB store using a backup file. This API uses an asynchronous callback to return the result.<br>- **srcName**: name of the RDB backup file.<br>- **callback**: callback invoked to return the result.|
| RdbStore |restore(srcName:string): Promise&lt;void&gt;| Restores an RDB store using a backup file. This API uses a promise to return the result.<br>- **srcName**: name of the RDB backup file.|
## How to Develop
......@@ -270,7 +270,7 @@ You can obtain the distributed table name for a remote device based on the local
const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType"))
resultSet.close()
})
```
```
4. Set the distributed tables to be synchronized.
......
......@@ -3,7 +3,6 @@
## When to Use
With device usage statistics APIs, you can have a better understanding of the application, notification, and system usage. For example, in application usage statistics, you can query the application usage, event log, and bundle group.
The application records (usage history statistics and event records) cached by components are updated to the database for persistent storage within 30 minutes after an event is reported.
## Available APIs
......@@ -23,7 +22,7 @@ import stats from '@ohos.bundleState';
| function queryAppUsagePriorityGroup(callback: AsyncCallback&lt;number&gt;): void | Queries the priority group of this application. This API uses an asynchronous callback to return the result.|
| function queryAppUsagePriorityGroup(): Promise&lt;number&gt;; | Queries the priority group of this application. This API uses a promise to return the result.|
| function isIdleState(bundleName: string, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether the application specified by **bundleName** is in the idle state. |
| function getRecentlyUsedModules(maxNum: number, callback: AsyncCallback&lt;BundleActiveModuleInfo&gt;): void | Obtains the number of FA usage records specified by **maxNum**.|
| function getRecentlyUsedModules(maxNum? : number, callback: AsyncCallback&lt;BundleActiveModuleInfo&gt;): void | Obtains the number of FA usage records specified by **maxNum**. If **maxNum** is not specified, the default value **1000** is used.|
| function queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback&lt;Array&lt;BundleActiveEventState&gt;&gt;): void | Queries the number of notifications from all applications based on the specified start time and end time.|
| function queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback&lt;Array&lt;BundleActiveEventState&gt;&gt;): void | Queries statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time.|
| function queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback&lt;number&gt;): void | Queries the priority group of the application specified by **bundleName**. If **bundleName** is not specified, the priority group of the current application is queried. This API uses an asynchronous callback to return the result.|
......@@ -45,7 +44,7 @@ import stats from '@ohos.bundleState';
...,
"reqPermissions": [
{
"name": "ohos.permission.BUNDLE_ACTIVE_INFO"
"name": "ohos.permission.BUNDLE_ACTIVE_INFO"
}
]
}
......@@ -57,13 +56,13 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState'
// Promise mode
stats.queryBundleActiveStates(0, 20000000000000).then( res => {
stats.queryBundleActiveStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise success.');
for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise result ' + JSON.stringify(res[i]));
}
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise failed, because: ' + err.code);
});
......@@ -87,7 +86,7 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState'
// Promise mode
stats.queryBundleStateInfos(0, 20000000000000).then( res => {
stats.queryBundleStateInfos(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise success.');
let i = 1;
for (let key in res){
......@@ -95,7 +94,7 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise result ' + JSON.stringify(res[key]));
i++;
}
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise failed, because: ' + err.code);
});
......@@ -121,13 +120,13 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState'
// Promise mode
stats.queryCurrentBundleActiveStates(0, 20000000000000).then( res => {
stats.queryCurrentBundleActiveStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.');
for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise result ' + JSON.stringify(res[i]));
}
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise failed, because: ' + err.code);
});
......@@ -151,13 +150,13 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState'
// Promise mode
stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then( res => {
stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.');
for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise result ' + JSON.stringify(res[i]));
}
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise failed, because: ' + err.code);
});
......@@ -179,14 +178,14 @@ import stats from '@ohos.bundleState';
```js
import stats from '@ohos.bundleState'
// Promise mode
stats.queryAppUsagePriorityGroup().then( res => {
stats.queryAppUsagePriorityGroup().then(res => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code);
});
// Callback mode
stats.queryAppUsagePriorityGroup((err, res) => {
if (err) {
......@@ -196,16 +195,16 @@ import stats from '@ohos.bundleState';
}
});
```
7. Check whether the application specified by **bundleName** is in the idle state. This requires no permission to be configured in the **config.json** file. A third-party application can only check the idle status of itself.
```js
import stats from '@ohos.bundleState'
// Promise mode
stats.isIdleState("com.ohos.camera").then( res => {
stats.isIdleState("com.ohos.camera").then(res => {
console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res));
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE isIdleState promise failed, because: ' + err.code);
});
......@@ -225,18 +224,18 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState'
// Promise mode
stats.getRecentlyUsedModules(1000).then( res => {
stats.getRecentlyUsedModules(1000).then(res => {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded');
for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise result ' + JSON.stringify(res[i]));
}
}).catch( err=> {
}).catch(err=> {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise failed, because: ' + err.code);
});
// Promise mode when maxNum is not specified
stats.getRecentlyUsedModules().then( res => {
stats.getRecentlyUsedModules().then(res => {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded');
for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1));
......@@ -247,7 +246,7 @@ import stats from '@ohos.bundleState';
});
// Asynchronous callback mode
stats.getRecentlyUsedModules(1000,(err, res) => {
stats.getRecentlyUsedModules(1000, (err, res) => {
if(err) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code);
} else {
......@@ -261,7 +260,7 @@ import stats from '@ohos.bundleState';
// Asynchronous callback mode when maxNum is not specified
stats.getRecentlyUsedModules((err, res) => {
if(err) {
if (err) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code);
} else {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback succeeded.');
......@@ -279,10 +278,10 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState'
// Promise mode
stats.queryAppNotificationNumber(0, 20000000000000).then( res => {
stats.queryAppNotificationNumber(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise success.');
console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise result ' + JSON.stringify(res));
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise failed, because: ' + err.code);
});
......@@ -301,15 +300,15 @@ import stats from '@ohos.bundleState';
```js
import stats from '@ohos.bundleState'
// Promise mode
stats.queryBundleActiveEventStates(0, 20000000000000).then( res => {
stats.queryBundleActiveEventStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise success.');
console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise result ' + JSON.stringify(res));
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise failed, because: ' + err.code);
});
// Asynchronous callback mode
stats.queryBundleActiveEventStates(0, 20000000000000, (err, res) => {
if (err) {
......@@ -325,14 +324,14 @@ import stats from '@ohos.bundleState';
```js
import stats from '@ohos.bundleState'
// Promise mode without parameters
stats.queryAppUsagePriorityGroup().then( res => {
stats.queryAppUsagePriorityGroup().then(res => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code);
});
// Asynchronous callback mode without parameters
stats.queryAppUsagePriorityGroup((err, res) => {
if (err) {
......@@ -341,17 +340,17 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res));
}
});
// Promise mode with parameters
stats.queryAppUsagePriorityGroup(this.bundleName).then( res => {
stats.queryAppUsagePriorityGroup(this.bundleName).then(res => {
console.log('BUNDLE_ACTIVE QueryPackageGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE QueryPackageGroup promise failed. because: ' + err.code);
});
// Asynchronous callback mode with parameters
stats.queryAppUsagePriorityGroup(this.bundleName, (err, res) => {
if(err) {
if (err) {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code);
} else {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback succeeded. result: ' + JSON.stringify(res));
......@@ -363,16 +362,16 @@ import stats from '@ohos.bundleState';
```javascript
import stats from '@ohos.bundleState'
// Promise mode
stats.setBundleGroup(this.bundleName, this.newGroup).then( () => {
stats.setBundleGroup(this.bundleName, this.newGroup).then(() => {
console.log('BUNDLE_ACTIVE SetBundleGroup promise succeeded.');
}).catch( err => {
console.log('BUNDLE_ACTIVE SetBundleGroup promise failed. because: ' + err.code);
});
// Asynchronous callback mode
stats.setBundleGroup(this.bundleName, this.newGroup, (err) => {
if(err) {
if (err) {
console.log('BUNDLE_ACTIVE SetBundleGroup callback failed. because: ' + err.code);
} else {
console.log('BUNDLE_ACTIVE SetBundleGroup callback succeeded.');
......@@ -384,9 +383,9 @@ import stats from '@ohos.bundleState';
```javascript
import stats from '@ohos.bundleState'
// Promise mode
let onBundleGroupChanged = (err,res) =>{
let onBundleGroupChanged = (err,res) => {
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.');
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result oldGroup is : ' + res.oldGroup);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result newGroup is : ' + res.newGroup);
......@@ -394,13 +393,13 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result userId is : ' + res.userId);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result bundleName is : ' + res.bundleName);
};
stats.registerGroupCallBack(onBundleGroupChanged).then( () => {
stats.registerGroupCallBack(onBundleGroupChanged).then(() => {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise succeeded.');
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise failed. because: ' + err.code);
});
// Asynchronous callback mode
let onBundleGroupChanged = (err,res) =>{
let onBundleGroupChanged = (err,res) => {
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.');
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's oldGroup is : ' + res.oldGroup);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's newGroup is : ' + res.newGroup);
......@@ -408,29 +407,29 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's userId is : ' + res.userId);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's bundleName is : ' + res.bundleName);
};
stats.registerGroupCallBack(onBundleGroupChanged, (err)=>{
if(err) {
stats.registerGroupCallBack(onBundleGroupChanged, (err) => {
if (err) {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback failed, because: ' + err.code);
} else {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback success.');
}
});
```
13. Deregister the callback for application group changes.
```javascript
import stats from '@ohos.bundleState'
//promise
stats.unRegisterGroupCallBack().then( () => {
stats.unRegisterGroupCallBack().then(() => {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise succeeded.');
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise failed. because: ' + err.code);
});
//callback
stats.unRegisterGroupCallBack((err)=>{
if(err) {
stats.unRegisterGroupCallBack((err) => {
if (err) {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback failed, because: ' + err.code);
} else {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback success.');
......
......@@ -3,9 +3,9 @@
## When to Use
Describing a location using coordinates is accurate, but neither intuitive nor user-friendly.
Describing a location using coordinates is accurate, but neither intuitive nor user-friendly. With the geocoding and reverse geocoding capabilities, you will be able to convert geographic description into specific coordinates and vice versa.
With the geocoding and reverse geocoding capabilities, you will be able to convert geographic description into specific coordinates and vice versa. The geocoding information describes a location using several attributes, including the country, administrative region, street, house number, and address, etc.
The geographic description helps users understand a location easily by providing several key attributes, for example, country, administrative region, street, house number, and address.
## Available APIs
......@@ -36,13 +36,29 @@ The following table describes APIs available for mutual conversion between coord
import geolocation from '@ohos.geolocation';
```
2. Obtain the conversion result.
2. Query whether geocoder service is available.
- Call **isGeoServiceAvailable** to query whether the geocoder service is available. If the service is available, continue with step 3.
```
geolocation.isGeoServiceAvailable((err, data) => {
if (err) {
console.log('isGeoServiceAvailable err: ' + JSON.stringify(err));
} else {
console.log('isGeoServiceAvailable data: ' + JSON.stringify(data));
}
});
```
3. Obtain the conversion result.
- Call **getAddressesFromLocation** to convert coordinates into geographical location information.
```
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
geolocation.getAddressesFromLocation(reverseGeocodeRequest, (data) => {
console.log('getAddressesFromLocation: ' + JSON.stringify(data));
geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
if (err) {
console.log('getAddressesFromLocation err: ' + JSON.stringify(err));
} else {
console.log('getAddressesFromLocation data: ' + JSON.stringify(data));
}
});
```
......@@ -51,8 +67,12 @@ The following table describes APIs available for mutual conversion between coord
```
var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
geolocation.getAddressesFromLocationName(geocodeRequest, (data) => {
console.log('getAddressesFromLocationName: ' + JSON.stringify(data));
geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => {
if (err) {
console.log('getAddressesFromLocationName err: ' + JSON.stringify(err));
} else {
console.log('getAddressesFromLocationName data: ' + JSON.stringify(data));
}
});
```
......
......@@ -2,13 +2,13 @@
## 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
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 |
| ------------------------------------------------------------ | -------------- | ------------------------------------------------------------ |
......@@ -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).
**APIs for Event Logging Configuration**
**Table 2** APIs for event logging configuration
| API | Return Value | Description |
| ------------------------------ | ------------ | ------------------------------------------------------------ |
......
......@@ -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.
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
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.
......@@ -6,9 +6,9 @@ HiTraceMeter provides APIs for system performance tracing. You can call the APIs
## Available APIs
The performance tracing APIs are provided by the **hiTraceMeter** module. For details, see [API Reference]( ../reference/apis/js-apis-hitracemeter.md).
The performance tracing APIs are provided by the **hiTraceMeter** module. For details, see [API Reference](../reference/apis/js-apis-hitracemeter.md).
**APIs for performance tracing**
**Table 1** APIs for performance tracing
| API| Return Value| Description|
| ---------------------------------------------------------------------------- | --------- | ------------ |
......
......@@ -15,4 +15,4 @@ hiTraceMeter is a tool for you to trace service processes and monitor system per
## 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
### 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).
```
```js
var language = i18n.getSystemLanguage();
```
2. Obtain the system region.<br>
2. Obtain the system region.
Call the **getSystemRegion** method to obtain the system region.
```
```js
var region = i18n.getSystemRegion();
```
3. Obtain the system locale.<br>
3. Obtain the system locale.
Call the **getSystemLocale** method to obtain the system locale.
```
```js
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.
```
```js
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.
```
```js
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.
```
```js
var language = "en";
var locale = "zh-CN";
var sentenceCase = false;
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.
```
```js
var country = "US";
var locale = "zh-CN";
var sentenceCase = false;
......@@ -106,70 +113,78 @@ You can use APIs provided in the following table to obtain the system language a
### 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.
```
```js
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.
```
```js
var date1 = new Date();
calendar.setTime(date1);
var date2 = 1000;
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.
```
```js
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.
```
```js
calendar.setTimeZone("Asia/Shanghai");
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.
```
```js
calendar.setFirstDayOfWeek(1);
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.
```
```js
calendar.setMinimalDaysInFirstWeek(3);
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.
```
```js
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.
```
```js
var date = new 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
### 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**.
```
```js
var phoneNumberFormat = new i18n.PhoneNumberFormat("CN", {type: "E164"});
```
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.
```
```js
var validNumber = phoneNumberFormat.isValidNumber("15812341234");
```
3. Format a phone number.
Call the **format** method of **PhoneNumberFormat** to format the input phone number.
```
```js
var formattedNumber = phoneNumberFormat.format("15812341234");
```
......@@ -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.
```
```js
var fromUnit = {unit: "cup", measureSystem: "US"};
var toUnit = {unit: "liter", measureSystem: "SI"};
var number = 1000;
......@@ -259,32 +275,36 @@ The **unitConvert** API is provided to help you implement measurement conversion
### 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.
```
```js
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.
```
```js
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.
```
```js
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.
```
```js
var text = "access index";
indexUtil.getIndex(text);
```
......@@ -313,38 +333,42 @@ When a text is displayed in more than one line, [BreakIterator](../reference/api
### How to Develop
1. Instantiate a **BreakIterator** object.<br>
1. Instantiate a **BreakIterator** object.
Call the **getLineInstance** method to instantiate a **BreakIterator** object.
```
```js
var locale = "en-US"
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.
```
```js
var text = "Apple is my favorite fruit";
breakIterator.setLineBreakText(text);
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.
```
```js
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.
```
```js
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.
// 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
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.
```
```js
var isboundary = breakIterator.isBoundary(5);
```
......@@ -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.
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.
## Setting Locale Information
......@@ -24,7 +25,8 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc
### 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.
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
| kf | Whether upper case or lower case is considered when sorting or comparing strings.|
```
```js
var locale = "zh-CN";
var options = {caseFirst: false, calendar: "chinese", collation: pinyin};
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.
```
```js
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.
```
```js
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.
```
```js
var minimizedLocale = localeObj.minimize();
```
......@@ -88,42 +93,46 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
### 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.
```
```js
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).
```
```js
var options = {dateStyle: "full", timeStyle: "full"};
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.
```
```js
Date date = new 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.
```
```js
Date startDate = new Date();
Date endDate = new Date();
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.
```
```js
var options = dateTimeFormat.resolvedOptions();
```
......@@ -145,33 +154,36 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for
### 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.
```
```js
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).
```
```js
var options = {compactDisplay: "short", notation: "compact"};
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.
```
```js
var number = 1234.5678
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.
```
```js
var options = numberFormat.resolvedOptions();
```
......@@ -193,33 +205,36 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on
### 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.
```
```js
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).
```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.
```
```js
var str1 = "first string";
var str2 = "second string";
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.
```
```js
var options = collator.resolvedOptions();
```
......@@ -240,24 +255,26 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu
### 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.
```
```js
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).
```
var plurals = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"};
```js
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**.
```
```js
var number = 1234.5678
var categoryResult = plurals.select(number);
```
......@@ -281,41 +298,45 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r
### 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.
```
```js
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).
```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.
```
```js
var number = 2;
var unit = "year"
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.
```
```js
var number = 2;
var unit = "year"
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).
```
```js
var options = numberFormat.resolvedOptions();
```
# Media
- Audio
- [Audio Overview](audio-overview.md)
- [Audio Playback Development](audio-playback.md)
- [Audio Recording Development](audio-recorder.md)
......@@ -15,9 +14,9 @@
- [Video Playback Development](video-playback.md)
- [Video Recording Development](video-recorder.md)
- Image
- Image
- [Image Development](image.md)
- Camera
- Camera
- [Camera Development](camera.md)
......@@ -48,7 +48,7 @@ For details about the APIs, see [AudioRenderer in Audio Management](../reference
```js
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");
});
```
......@@ -39,38 +39,38 @@ function printfDescription(obj) {
// Set the player callbacks.
function setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
audioPlayer.on('dataLoad', () => { // Set the `dataLoad` event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success');
audioPlayer.play(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is then triggered.
audioPlayer.play(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is then triggered.
});
audioPlayer.on('play', () => { // Set the 'play' event callback.
audioPlayer.on('play', () => { // Set the `play` event callback.
console.info('audio play success');
audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback.
audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback.
});
audioPlayer.on('pause', () => { // Set the 'pause' event callback.
audioPlayer.on('pause', () => { // Set the `pause` event callback.
console.info('audio pause success');
audioPlayer.seek(5000); // Trigger the 'timeUpdate' event callback, and seek to 5000 ms for playback.
audioPlayer.seek(5000); // Trigger the 'timeUpdate' event callback, and seek to 5000 ms for playback.
});
audioPlayer.on('stop', () => { // Set the 'stop' event callback.
audioPlayer.on('stop', () => { // Set the `stop` event callback.
console.info('audio stop success');
audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song.
audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song.
});
audioPlayer.on('reset', () => { // Set the 'reset' event callback.
audioPlayer.on('reset', () => { // Set the `reset` event callback.
console.info('audio reset success');
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined;
});
audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback.
audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the `timeUpdate` event callback.
if (typeof(seekDoneTime) == 'undefined') {
console.info('audio seek fail');
return;
}
console.info('audio seek success, and seek time is ' + seekDoneTime);
audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback.
audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback.
});
audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback.
audioPlayer.on('volumeChange', () => { // Set the `volumeChange` event callback.
console.info('audio volumeChange success');
audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode.
audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode.
if (typeof (arrlist) != 'undefined') {
for (let i = 0; i < arrlist.length; i++) {
printfDescription(arrlist[i]);
......@@ -78,13 +78,13 @@ function setCallBack(audioPlayer) {
} else {
console.log(`audio getTrackDescription fail, error:${error.message}`);
}
audioPlayer.stop(); // Trigger the 'stop' event callback to stop the playback.
audioPlayer.stop(); // Trigger the 'stop' event callback to stop the playback.
});
});
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish');
});
audioPlayer.on('error', (error) => { // Set the 'error' event callback.
audioPlayer.on('error', (error) => { // Set the 'error' event callback.
console.info(`audio error called, errName is ${error.name}`);
console.info(`audio error called, errCode is ${error.code}`);
console.info(`audio error called, errMessage is ${error.message}`);
......@@ -94,7 +94,7 @@ function setCallBack(audioPlayer) {
async function audioPlayerDemo() {
// 1. Create an AudioPlayer instance.
let audioPlayer = media.createAudioPlayer();
setCallBack(audioPlayer); // Set the event callbacks.
setCallBack(audioPlayer); // Set the event callbacks.
// 2. Set the URI of the audio file.
let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
......@@ -107,7 +107,7 @@ async function audioPlayerDemo() {
}).catch((err) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
audioPlayer.src = fdPath; // Set the src attribute and trigger the `dataLoad` event callback.
}
```
......@@ -119,23 +119,23 @@ import fileIO from '@ohos.fileio'
export class AudioDemo {
// Set the player callbacks.
setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
audioPlayer.on('dataLoad', () => { // Set the `dataLoad` event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success');
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
});
audioPlayer.on('play', () => { // Set the 'play' event callback.
audioPlayer.on('play', () => { // Set the `play` event callback.
console.info('audio play success');
});
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish');
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined;
});
}
async audioPlayerDemo() {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks.
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
......@@ -147,7 +147,7 @@ export class AudioDemo {
}).catch((err) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
audioPlayer.src = fdPath; // Set the src attribute and trigger the `dataLoad` event callback.
}
}
```
......@@ -161,20 +161,20 @@ export class AudioDemo {
// Set the player callbacks.
private isNextMusic = false;
setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
audioPlayer.on('dataLoad', () => { // Set the `dataLoad` event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success');
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
});
audioPlayer.on('play', () => { // Set the 'play' event callback.
audioPlayer.on('play', () => { // Set the `play` event callback.
console.info('audio play success');
audioPlayer.reset(); // Call the reset() API and trigger the 'reset' event callback.
audioPlayer.reset(); // Call the reset() API and trigger the 'reset' event callback.
});
audioPlayer.on('reset', () => { // Set the 'reset' event callback.
audioPlayer.on('reset', () => { // Set the `reset` event callback.
console.info('audio play success');
if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented.
this.nextMusic(audioPlayer); // Changing songs is implemented.
if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented.
this.nextMusic(audioPlayer); // Changing songs is implemented.
} else {
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined;
}
});
......@@ -197,8 +197,8 @@ export class AudioDemo {
}
async audioPlayerDemo() {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks.
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
......@@ -223,19 +223,19 @@ import fileIO from '@ohos.fileio'
export class AudioDemo {
// Set the player callbacks.
setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
audioPlayer.on('dataLoad', () => { // Set the `dataLoad` event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success');
audioPlayer.loop = true; // Set the loop playback attribute.
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
audioPlayer.loop = true; // Set the loop playback attribute.
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
});
audioPlayer.on('play', () => { // Set the 'play' event callback to start loop playback.
audioPlayer.on('play', () => { // Set the 'play' event callback to start loop playback.
console.info('audio play success');
});
}
async audioPlayerDemo() {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks.
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
......@@ -247,7 +247,7 @@ export class AudioDemo {
}).catch((err) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
audioPlayer.src = fdPath; // Set the src attribute and trigger the `dataLoad` event callback.
}
}
```
# Using Native APIs in Application Projects
OpenHarmony applications use JavaScript (JS) when calling native APIs. The native APIs (NAPIs) provided by the **arkui_napi** repository are used to implement the interaction with JS. Currently, the **arkui_napi** repository supports some third-party **Node.js** interfaces. The names of the NAPIs are the same as those in the third-party **Node.js**. For details about the interfaces supported, see `libnapi.ndk.json` in this repository.
OpenHarmony applications use JavaScript (JS) when calling native APIs. The native APIs (NAPIs) provided by the [ace_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository are used to implement interaction with JS. Currently, the **ace_napi** repository supports some third-party **Node.js** interfaces. The names of the NAPIs are the same as those in the third-party **Node.js**. For details about the interfaces supported, see `libnapi.ndk.json` in this repository.
## How to Develop
The IDE has a default project that uses NAPIs. You can choose `File` > `New` > `Create Project` to create a `Native C++` project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **arkui_napi** repository for development.
The IDE has a default project that uses NAPIs. You can choose `File` > `New` > `Create Project` to create a `Native C++` project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **ace_napi** repository for development.
You can `import` the native .so that contains the JS processing logic. For example, `import hello from 'libhello.so'` to use the **libhello.so** capability. Then, the JS object created using the NAPI can be passed to the `hello` object of the application to call the native capability.
......@@ -74,7 +74,7 @@ export default storage;
### Implementation
You can obtain the complete code from `sample/native_module_storage/` in the **arkui_napi** repository.
You can obtain the complete code from `sample/native_module_storage/` in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository.
#### Registering the Module
......@@ -212,7 +212,7 @@ static napi_value JSStorageGet(napi_env env, napi_callback_info info)
napi_create_async_work(
env, nullptr, resource,
// Callback 1: This callback contains the service logic to be asynchronously executed and is asynchronously executed by the NAPI. Do not operate JS objects using theNAPI because the execution is asynchronous.
// Callback 1: This callback contains the service logic to be asynchronously executed and is asynchronously executed by the NAPI. Do not operate JS objects using the NAPI because the execution is asynchronous.
[](napi_env env, void* data) {
StorageAsyncContext* asyncContext = (StorageAsyncContext*)data;
auto itr = gKeyValueStorage.find(asyncContext->key);
......@@ -307,7 +307,7 @@ export class NetServer {
### Implementation
You can obtain the complete code from `sample/native_module_netserver/` in the **arkui_napi** repository.
You can obtain the complete code from `sample/native_module_netserver/` in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository.
#### Registering the Module
......@@ -494,7 +494,7 @@ This example describes how to invoke a JS callback in a non-JS thread. For examp
### Implementation
You can obtain the complete code from `sample/native_module_callback/` in the **arkui_napi** repository.
You can obtain the complete code from `sample/native_module_callback/` in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository.
#### Registering the Module
......@@ -562,7 +562,7 @@ void callbackTest(CallbackContext* context)
uv_queue_work(
loop,
work,
// This callback is executed in another common thread to process tasks asynchronously. After the callback is complete, execute the next callback. In this scenario, the callback does not need to execute any task.
// This callback is executed in another common thread to process tasks asynchronously. After the callback is complete, execute the next callback. In this scenario, this callback does not need to execute any task.
[](uv_work_t* work) {},
// This callback is executed in the JS thread bound to env.
[](uv_work_t* work, int status) {
......
......@@ -9,6 +9,5 @@
- Development Fundamentals
- [Application Package Structure Configuration File (FA Model)](package-structure.md)
- [Application Package Structure Configuration File (Stage Model)](stage-structure.md)
- [Resource File Categories](basic-resource-file-categories.md)
- [SysCap](syscap.md)
- [HarmonyAppProvision Configuration File](app-provision-structure.md)
# 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)
# Development References
- [JavaScript-based Web-like Development Paradigm](arkui-js/Readme-EN.md)
- [TypeScript-based Declarative Development Paradigm](arkui-ts/Readme-EN.md)
- [Component Reference(TypeScript-based Declarative Development Paradigm)](arkui-ts/Readme-EN.md)
- [Component Reference(JavaScript-based Web-like Development Paradigm)](arkui-js/Readme-EN.md)
- [APIs](apis/Readme-EN.md)
- [JS (eTS Included) APIs](apis/Readme-EN.md)
- Native APIs
- [Standard Library](native-lib/third_party_libc/musl.md)
......
# APIs
- [API Reference Document Description](development-intro.md)
- Ability Framework
- [@ohos.ability.dataUriUtils](js-apis-DataUriUtils.md)
- [@ohos.ability.errorCode](js-apis-ability-errorCode.md)
- [@ohos.ability.wantConstant](js-apis-ability-wantConstant.md)
- [@ohos.application.Ability](js-apis-application-ability.md)
- [@ohos.application.AbilityConstant](js-apis-application-abilityConstant.md)
- [@ohos.application.abilityDelegatorRegistry](js-apis-abilityDelegatorRegistry.md)
- [@ohos.application.AbilityStage ](js-apis-application-abilitystage.md)
- [@ohos.application.abilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md)
- [@ohos.application.appManager](js-apis-appmanager.md)
- [@ohos.application.Configuration](js-apis-configuration.md)
- [@ohos.application.ConfigurationConstant](js-apis-configurationconstant.md)
- [@ohos.ability.featureAbility](js-apis-featureAbility.md)
- [@ohos.application.formBindingData](js-apis-formbindingdata.md)
- [@ohos.application.FormExtension](js-apis-formextension.md)
- [@ohos.application.formError](js-apis-formerror.md)
- [@ohos.application.formHost](js-apis-formhost.md)
- [@ohos.application.formInfo](js-apis-formInfo.md)
- [@ohos.application.missionManager](js-apis-missionManager.md)
- [@ohos.application.formProvider](js-apis-formprovider.md)
- [@ohos.ability.particleAbility](js-apis-particleAbility.md)
- [@ohos.application.ServiceExtensionAbility](js-apis-service-extension-ability.md)
- [@ohos.application.StartOptions](js-apis-application-StartOptions.md)
- [@ohos.application.StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md)
- [@ohos.application.uriPermissionManager](js-apis-uripermissionmanager.md)
- [@ohos.application.Want](js-apis-application-Want.md)
- [@ohos.wantAgent](js-apis-wantAgent.md)
- ability/[dataAbilityHelper](js-apis-dataAbilityHelper.md)
- app/[context](js-apis-Context.md)
- application/[AbilityContext](js-apis-ability-context.md)
- application/[ApplicationContext](js-apis-application-applicationContext.md)
- application/[abilityDelegator](js-apis-application-abilityDelegator.md)
- application/[abilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md)
- application/[abilityMonitor](js-apis-application-abilityMonitor.md)
- application/[AbilityRunningInfo](js-apis-abilityrunninginfo.md)
- application/[AbilityStageContext](js-apis-abilitystagecontext.md)
- application/[Context](js-apis-application-context.md)
- application/[ExtensionContext](js-apis-extension-context.md)
- application/[ExtensionRunningInfo](js-apis-extensionrunninginfo.md)
- application/[FormExtensionContext](js-apis-formextensioncontext.md)
- application/[MissionSnapshot](js-apis-application-MissionSnapshot.md)
- application/[PermissionRequestResult](js-apis-permissionrequestresult.md)
- application/[ProcessRunningInfo](js-apis-processrunninginfo.md)
- application/[ServiceExtensionContext](js-apis-service-extension-context.md)
- application/[shellCmdResult](js-apis-application-shellCmdResult.md)
- application/[MissionInfo](js-apis-application-missionInfo.md)
- FA Model
- [@ohos.ability.featureAbility](js-apis-featureAbility.md)
- [@ohos.ability.particleAbility](js-apis-particleAbility.md)
- ability/[dataAbilityHelper](js-apis-dataAbilityHelper.md)
- app/[context](js-apis-Context.md)
- Stage Model
- [@ohos.application.Ability](js-apis-application-ability.md)
- [@ohos.application.AbilityConstant](js-apis-application-abilityConstant.md)
- [@ohos.application.AbilityStage](js-apis-application-abilitystage.md)
- [@ohos.application.abilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md)
- [@ohos.application.DataShareExtensionAbility](js-apis-application-DataShareExtensionAbility.md)
- [@ohos.application.FormExtension](js-apis-formextension.md)
- [@ohos.application.ServiceExtensionAbility](js-apis-service-extension-ability.md)
- [@ohos.application.StartOptions](js-apis-application-StartOptions.md)
- [@ohos.application.StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md)
- application/[AbilityContext](js-apis-ability-context.md)
- application/[ApplicationContext](js-apis-application-applicationContext.md)
- application/[AbilityStageContext](js-apis-abilitystagecontext.md)
- application/[Context](js-apis-application-context.md)
- application/[ExtensionContext](js-apis-extension-context.md)
- application/[FormExtensionContext](js-apis-formextensioncontext.md)
- application/[PermissionRequestResult](js-apis-permissionrequestresult.md)
- application/[ServiceExtensionContext](js-apis-service-extension-context.md)
- FA and Stage Models
- [@ohos.ability.dataUriUtils](js-apis-DataUriUtils.md)
- [@ohos.ability.errorCode](js-apis-ability-errorCode.md)
- [@ohos.ability.wantConstant](js-apis-ability-wantConstant.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.Configuration](js-apis-configuration.md)
- [@ohos.application.ConfigurationConstant](js-apis-configurationconstant.md)
- [@ohos.application.EnvironmentCallback](js-apis-application-EnvironmentCallback.md)
- [@ohos.application.formBindingData](js-apis-formbindingdata.md)
- [@ohos.application.formError](js-apis-formerror.md)
- [@ohos.application.formHost](js-apis-formhost.md)
- [@ohos.application.formInfo](js-apis-formInfo.md)
- [@ohos.application.formProvider](js-apis-formprovider.md)
- [@ohos.application.missionManager](js-apis-missionManager.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)
- application/[abilityDelegator](js-apis-application-abilityDelegator.md)
- application/[abilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md)
- application/[abilityMonitor](js-apis-application-abilityMonitor.md)
- application/[AbilityRunningInfo](js-apis-abilityrunninginfo.md)
- application/[ExtensionRunningInfo](js-apis-extensionrunninginfo.md)
- application/[MissionSnapshot](js-apis-application-MissionSnapshot.md)
- application/[ProcessRunningInfo](js-apis-processrunninginfo.md)
- application/[shellCmdResult](js-apis-application-shellCmdResult.md)
- continuation/[ContinuationResult](js-apis-continuation-continuationResult.md)
- Common Event and Notification
- [@ohos.commonEvent](js-apis-commonEvent.md)
......@@ -55,7 +63,7 @@
- [@ohos.notification](js-apis-notification.md)
- [@ohos.reminderAgent](js-apis-reminderAgent.md)
- application/[EventHub](js-apis-eventhub.md)
- Bundle Management
- [@ohos.bundle](js-apis-Bundle.md)
......@@ -66,26 +74,30 @@
- bundle/[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)
- bundle/[BundleInfo](js-apis-bundle-BundleInfo.md)
- bundle/[CustomizeData](js-apis-bundle-CustomizeData.md)
- bundle/[ElementName](js-apis-bundle-ElementName.md)
- bundle/[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)
- bundle/[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)
- bundle/[Metadata](js-apis-bundle-Metadata.md)
- bundle/[ModuleInfo](js-apis-bundle-ModuleInfo.md)
- UI Page
- [@ohos.animator](js-apis-animator.md)
- [@ohos.mediaquery](js-apis-mediaquery.md)
- [@ohos.prompt](js-apis-prompt.md)
- [@ohos.router](js-apis-router.md)
- [@ohos.uiAppearance](js-apis-uiappearance.md)
- Graphics
- [@ohos.display ](js-apis-display.md)
- [@ohos.effectKit](js-apis-effectKit.md)
- [@ohos.screen](js-apis-screen.md)
- [@ohos.screenshot](js-apis-screenshot.md)
- [@ohos.window](js-apis-window.md)
- [webgl](js-apis-webgl.md)
- [webgl2](js-apis-webgl2.md)
- Media
- [@ohos.multimedia.audio](js-apis-audio.md)
......@@ -93,41 +105,46 @@
- [@ohos.multimedia.image](js-apis-image.md)
- [@ohos.multimedia.media](js-apis-media.md)
- [@ohos.multimedia.medialibrary](js-apis-medialibrary.md)
- Resource Management
- [@ohos.i18n](js-apis-i18n.md)
- [@ohos.intl](js-apis-intl.md)
- [@ohos.resourceManager](js-apis-resource-manager.md)
- Resource Scheduling
- [@ohos.backgroundTaskManager](js-apis-backgroundTaskManager.md)
- [@ohos.workScheduler ](js-apis-workScheduler.md)
- [@ohos.WorkSchedulerExtensionAbility](js-apis-WorkSchedulerExtensionAbility.md)
- Custom Management
- [@ohos.configPolicy](js-apis-config-policy.md)
- [@ohos.enterpriseDeviceManager](js-apis-enterprise-device-manager.md)
- [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md)
- Security
- [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md)
- [@ohos.privacyManager](js-apis-privacyManager.md)
- [@ohos.security.huks ](js-apis-huks.md)
- [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md)
- [@system.cipher](js-apis-system-cipher.md)
- Data Management
- [@ohos.data.dataAbility ](js-apis-data-ability.md)
- [@ohos.data.dataShare](js-apis-data-dataShare.md)
- [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md)
- [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md)
- [@ohos.data.distributedData](js-apis-distributed-data.md)
- [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md)
- [@ohos.data.preferences](js-apis-data-preferences.md)
- [@ohos.data.rdb](js-apis-data-rdb.md)
- [@ohos.settings](js-apis-settings.md)
- [@ohos.data.ValuesBucket](js-apis-data-ValuesBucket.md)
- data/rdb/[resultSet](js-apis-data-resultset.md)
- File Management
- [@ohos.document](js-apis-document.md)
......@@ -138,7 +155,7 @@
- [@ohos.storageStatistics](js-apis-storage-statistics.md)
- [@ohos.volumeManager](js-apis-volumemanager.md)
- [@ohos.securityLabel](js-apis-securityLabel.md)
- Telephony Service
- [@ohos.contact](js-apis-contact.md)
......@@ -148,14 +165,15 @@
- [@ohos.telephony.sim](js-apis-sim.md)
- [@ohos.telephony.sms](js-apis-sms.md)
- [@ohos.telephony.data](js-apis-telephony-data.md)
- Network Management
- [@ohos.net.connection](js-apis-net-connection.md)
- [@ohos.net.http](js-apis-http.md)
- [@ohos.request](js-apis-request.md)
- [@ohos.net.socket](js-apis-socket.md)
- [@ohos.net.webSocket](js-apis-webSocket.md)
- Connectivity
- [@ohos.bluetooth](js-apis-bluetooth.md)
......@@ -166,7 +184,7 @@
- [@ohos.rpc](js-apis-rpc.md)
- [@ohos.wifi](js-apis-wifi.md)
- [@ohos.wifiext](js-apis-wifiext.md)
- Basic Features
- [@ohos.accessibility](js-apis-accessibility.md)
......@@ -185,7 +203,7 @@
- [@ohos.systemTime](js-apis-system-time.md)
- [@ohos.wallpaper](js-apis-wallpaper.md)
- [Timer](js-apis-timer.md)
- Device Management
- [@ohos.batteryInfo ](js-apis-battery-info.md)
......@@ -205,18 +223,19 @@
- [@ohos.power](js-apis-power.md)
- [@ohos.runningLock](js-apis-runninglock.md)
- [@ohos.sensor](js-apis-sensor.md)
- [@ohos.settings](js-apis-settings.md)
- [@ohos.systemParameter](js-apis-system-parameter.md)
- [@ohos.thermal](js-apis-thermal.md)
- [@ohos.update](js-apis-update.md)
- [@ohos.usb](js-apis-usb.md)
- [@ohos.vibrator](js-apis-vibrator.md)
- Account Management
- [@ohos.account.appAccount](js-apis-appAccount.md)
- [@ohos.account.distributedAccount](js-apis-distributed-account.md)
- [@ohos.account.osAccount](js-apis-osAccount.md)
- Language Base Class Library
- [@ohos.convertxml](js-apis-convertxml.md)
......@@ -240,11 +259,12 @@
- [@ohos.util.Vector](js-apis-vector.md)
- [@ohos.worker](js-apis-worker.md)
- [@ohos.xml](js-apis-xml.md)
- Test
- [@ohos.application.testRunner](js-apis-testRunner.md)
- [@ohos.uitest](js-apis-uitest.md)
- APIs No Longer Maintained
- [@ohos.bytrace](js-apis-bytrace.md)
......
# API Reference Document Description
API references provide the description of APIs used for application development. This topic describes common fields in the API references to help you better use the reference document.
## Version Description
In API references, the earliest versions of APIs and components are specified in the following ways:
- For a new API or component, the version information is provided at the beginning of the reference document. Example: "The initial APIs of this module are supported since API version 7."
- For a new feature of an existing API or component, a superscript is added following the feature. For example, "uid<sup>8+</sup>" indicates that the **uid** attribute is supported since API version 8.
## Ability Framework Model Description
Ability is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances. Ability framework models are classified into the FA model and stage model. For details, see [Ability Framework Overview](../../ability/ability-brief.md).
- If all the APIs of a module support only one model, the following description is provided at the beginning of the reference document: "The APIs of this module can be used only in the FA model." or "The APIs of this module can be used only in the stage model."
- If certain APIs of a module support only one model, the following description is provided individually for these APIs: "This API can be used only in the FA model." or "This API can be used only in the stage model."
- If both models are supported, no special description is provided.
## Available APIs
Certain APIs provided by OpenHarmony are system APIs, which can be used only by original equipment manufacturers (OEMs) and cannot be used by non-system applications.
A description regarding system APIs will be provided in the document.
- If all the APIs of a module are system APIs, the following description is provided at the beginning of the reference document: "All the APIs of this module are system APIs."
- If a specific API of a module is a system API, the following description is provided individually for the API: "This is a system API."
## Permission Description
By default, applications can access limited system resources. However, in some cases, an application needs to access excess data (including personal data) and functions of the system or another application to implement extended functions. For details, see [Access Control Overview](../../security/accesstoken-overview.md).
To call APIs to access these resources, you must apply for the corresponding permissions by following the instructions provided in [Access Control Development](../../security/accesstoken-guidelines.md).
- If an application can call an API only after it has obtained a specific permission, the following description is provided for the API: "**Required permissions**: ohos.permission.xxxx"
- If an application can call an API without any permission, no special description is provided.
To determine whether an application can apply for a specific permission, see [Permission List](../../security/permission-list.md).
## System Capability Description
System capability refers to a relatively independent feature in the operating system. Different devices provide different system capabilities, and multiple APIs implement a system capability. You can determine whether an API can be used based on system capabilities. For details, see [SysCap](../../quick-start/syscap.md).
The following description is provided for each API in the reference document to describe the system capability of the API: "**System capability**: SystemCapability.xxx.xxx"
## Sample Code Language Description
OpenHarmony supports two development languages: JS and TS.
- When a code block is labeled with `js`, the sample code can be used in the JS and eTS projects.
- When a code block is labeled with `ts`, the sample code can be used only in the eTS project.
# DataUriUtils Module
# DataUriUtils
The **DataUriUtils** module provides APIs to handle utility classes for objects using the **DataAbilityHelper** schema. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI.
> **NOTE**
>
......
# EnterpriseAdminExtentionAbility
# EnterpriseAdminExtensionAbility
The **EnterpriseAdminExtentionAbility** module provides APIs for Extension abilities of enterprise administrators.
The **EnterpriseAdminExtensionAbility** module provides Extension abilities for enterprise administrators.
To have the capabilities provided by the module, for example, receiving the application activation or deactivation notification sent by the system, an enterprise administrator application must have an **EnterpriseAdminExtensionAbility** instance and override the APIs in it.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The APIs of this module can be used only in the stage model.
## Modules to Import
```ts
import EnterpriseAdminExtentionAbility from '@ohos.EnterpriseAdminExtentionAbility'
import EnterpriseAdminExtensionAbility from '@ohos.EnterpriseAdminExtensionAbility'
```
## EnterpriseAdminExtentionAbility.onAdminEnabled
## EnterpriseAdminExtensionAbility.onAdminEnabled
onAdminEnabled(): void
......@@ -22,14 +26,14 @@ Called when an enterprise administrator is enabled.
**Example**
```ts
```ts
export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility {
onAdminEnabled() {
}
onAdminEnabled() {
}
};
```
```
## EnterpriseAdminExtentionAbility.onAdminDisabled
## EnterpriseAdminExtensionAbility.onAdminDisabled
onAdminDisabled(): void
......@@ -38,11 +42,10 @@ Called when an enterprise administrator is disabled.
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
**Example**
```ts
```ts
export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility {
onAdminDisabled() {
}
onAdminDisabled() {
}
};
```
```
# ErrorCode
The **ErrorCode** module defines the error codes that can be used when the ability is started.
> **NOTE**
>
> The initial APIs of this module are supported since API 6. 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 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......@@ -12,7 +14,7 @@ import errorCode from '@ohos.ability.errorCode'
## ErrorCode
Defines the error code used when the ability is started.
Defines the error codes used when the ability is started.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......
# wantConstant
The **wantConstant** module provides the action, entity, and flags used in **Want** objects.
> **NOTE**
>
> The initial APIs of this module are supported since API version 6. 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 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......@@ -12,73 +14,75 @@ import wantConstant from '@ohos.ability.wantConstant'
## wantConstant.Action
**System capability**: SystemCapability.Ability.AbilityBase
Enumerates the action constants of the **Want** object.
Lists the permissions.
**System capability**: SystemCapability.Ability.AbilityBase
| Common Event Macro | Common Event Name | Subscriber Permission |
| Name | Value | Description |
| ------------ | ------------------ | ---------------------- |
| ACTION_HOME | ohos.want.action.home | None |
| ACTION_DIAL | ohos.want.action.dial | None |
| ACTION_SEARCH | ohos.want.action.search | None |
| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | None |
| ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | None |
| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | None |
| ACTION_SET_ALARM | ohos.want.action.setAlarm | None |
| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | None |
| ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | None |
| ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | None |
| ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | None |
| ACTION_SEND_SMS | ohos.want.action.sendSms | None |
| ACTION_CHOOSE | ohos.want.action.choose | None |
| ACTION_IMAGE_CAPTURE<sup>8+</sup> | ohos.want.action.imageCapture | None |
| ACTION_VIDEO_CAPTUR<sup>8+</sup> | ohos.want.action.videoCapture | None |
| ACTION_SELECT | ohos.want.action.select | None |
| ACTION_SEND_DATA | ohos.want.action.sendData | None |
| ACTION_SEND_MULTIPLE_DATA | ohos.want.action.sendMultipleData | None |
| ACTION_SCAN_MEDIA_FILE | ohos.want.action.scanMediaFile | None |
| ACTION_VIEW_DATA | ohos.want.action.viewData | None |
| ACTION_EDIT_DATA | ohos.want.action.editData | None |
| INTENT_PARAMS_INTENT | ability.want.params.INTENT | None |
| INTENT_PARAMS_TITLE | ability.want.params.TITLE | None |
| ACTION_FILE_SELECT<sup>7+</sup> | ohos.action.fileSelect | None |
| PARAMS_STREAM<sup>7+</sup> | ability.params.stream | None |
| ACTION_APP_ACCOUNT_OAUTH <sup>8+</sup> | ohos.account.appAccount.action.oauth | None |
| ACTION_HOME | ohos.want.action.home | Action of returning to the home page. |
| ACTION_DIAL | ohos.want.action.dial | Action of launching the numeric keypad. |
| ACTION_SEARCH | ohos.want.action.search | Action of launching the search function. |
| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | Action of launching the UI that provides radio network settings, for example, Wi-Fi option. |
| ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | Action of launching the UI for managing installed applications. |
| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | Action of launching the UI that displays the details of an application. |
| ACTION_SET_ALARM | ohos.want.action.setAlarm | Action of launching the UI for setting the alarm clock. |
| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | Action of launching the UI that displays all clock alarms. |
| ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | Action of launching the UI for snoozing an alarm. |
| ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | Action of launching the UI for deleting an alarm. |
| ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | Action of launching the UI for dismissing a timer. |
| ACTION_SEND_SMS | ohos.want.action.sendSms | Action of launching the UI for sending an SMS. |
| ACTION_CHOOSE | ohos.want.action.choose | Action of launching the UI for openning a contact or picture. |
| ACTION_IMAGE_CAPTURE<sup>8+</sup> | ohos.want.action.imageCapture | Action of launching the UI for photographing. |
| ACTION_VIDEO_CAPTURE<sup>8+</sup> | ohos.want.action.videoCapture | Action of launching the UI for shooting a video. |
| ACTION_SELECT | ohos.want.action.select | Action of launching the UI for application selection. |
| ACTION_SEND_DATA | ohos.want.action.sendData | Action of launching the UI for sending a single data record. |
| ACTION_SEND_MULTIPLE_DATA | ohos.want.action.sendMultipleData | Action of launching the UI for sending multiple data records. |
| ACTION_SCAN_MEDIA_FILE | ohos.want.action.scanMediaFile | Action of requesting a media scanner to scan a file and add the file to the media library. |
| ACTION_VIEW_DATA | ohos.want.action.viewData | Action of viewing data. |
| ACTION_EDIT_DATA | ohos.want.action.editData | Action of editing data. |
| INTENT_PARAMS_INTENT | ability.want.params.INTENT | Action of displaying selection options with an action selector. |
| INTENT_PARAMS_TITLE | ability.want.params.TITLE | Title of the character sequence dialog box used with the action selector. |
| ACTION_FILE_SELECT<sup>7+</sup> | ohos.action.fileSelect | Action of selecting a file. |
| PARAMS_STREAM<sup>7+</sup> | ability.params.stream | URI of the data stream associated with the target when the data is sent. |
| ACTION_APP_ACCOUNT_OAUTH <sup>8+</sup> | ohos.account.appAccount.action.oauth | Action of providing the OAuth service. |
| ACTION_MARKER_DOWNLOAD <sup>9+</sup> | ohos.want.action.marketDownload | Action of downloading an application from the application market.<br>**System API**: This is a system API and cannot be called by third-party applications. |
## wantConstant.Entity
**System capability**: SystemCapability.Ability.AbilityBase
Enumerates the entity constants of the **Want** object.
Lists the permissions.
**System capability**: SystemCapability.Ability.AbilityBase
| Common Event Macro | Common Event Name | Subscriber Permission |
| Name | Value | Description |
| ------------ | ------------------ | ---------------------- |
| ENTITY_DEFAULT | entity.system.default | None |
| ENTITY_HOME | entity.system.homel | None |
| ENTITY_VOICE | ENTITY_VOICE | None |
| ENTITY_BROWSABLE | entity.system.browsable | None |
| ENTITY_VIDEO | entity.system.video | None |
| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | None |
| ENTITY_DEFAULT | entity.system.default | Default entity. The default entity is used if no entity is specified. |
| ENTITY_HOME | entity.system.home | Home screen entity. |
| ENTITY_VOICE | entity.system.voice | Voice interaction entity. |
| ENTITY_BROWSABLE | entity.system.browsable | Browser type entity. |
| ENTITY_VIDEO | entity.system.video | Video type entity. |
## wantConstant.Flags
## flags
Describes flags.
**System capability**: SystemCapability.Ability.AbilityBase
| Name | Value | Description |
| ------------------------------------ | ---------- | ------------------------------------------------------------ |
| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. |
| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write the URI. |
| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write data to the URI. |
| FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. |
| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be continued on a remote device. |
| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. |
| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates that an ability is enabled. |
| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent. |
| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching. |
| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching.<br>**System API**: This is a system API and cannot be called by third-party applications.|
| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. |
| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. |
| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible. |
| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. |
| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. |
| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**.|
......
# Ability Access Control
Provides program permission management capabilities, including authentication, authorization, and revocation.
The **AbilityAccessCtrl** module provides APIs for application permission management, including authentication, authorization, and revocation.
> **NOTE**
>
......@@ -69,6 +69,36 @@ promise.then(data => {
});
```
### verifyAccessTokenSync<sup>9+</sup>
verifyAccessTokenSync(tokenID: number, permissionName: string): GrantStatus
Checks whether an application has been granted the specified permission. This API synchronously returns the result.
**System capability**: SystemCapability.Security.AccessToken
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------- | ---- | ------------------------------------------ |
| tokenID | number | Yes | ID of the application. |
| permissionName | string | Yes | Name of the permission to verify.|
**Return value**
| Type | Description |
| :------------ | :---------------------------------- |
| [GrantStatus](#grantstatus) | Permission grant state.|
**Example**
```js
var AtManager = abilityAccessCtrl.createAtManager();
let tokenID = 0;
let data = verifyAccessTokenSync(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS");
console.log(`data->${JSON.stringify(data)}`);
```
### grantUserGrantedPermission
grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number): Promise&lt;number&gt;
......
# AbilityDelegatorRegistry
The **AbilityDelegatorRegistry** module provides APIs for storing the global registers of the registered **AbilityDelegator** and **AbilityDelegatorArgs** objects. You can use the APIs to obtain the **AbilityDelegator** and **AbilityDelegatorArgs** objects of an application.
> **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.
......@@ -24,8 +26,6 @@ Enumerates the ability lifecycle states.
| BACKGROUND | 3 | The ability is running in the background. |
| DESTROY | 4 | The ability is destroyed.|
## AbilityDelegatorRegistry.getAbilityDelegator
getAbilityDelegator(): AbilityDelegator
......
# AbilityRunningInfo
The **AbilityRunningInfo** module implements ability running information and ability states.
> **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.
Provides ability running information.
## Modules to Import
```js
import abilitymanager from '@ohos.application.abilityManager';
```
## Usage
The ability running information is obtained by using the **getAbilityRunningInfos** API in **abilityManager**.
......@@ -27,26 +21,13 @@ abilitymanager.getAbilityRunningInfos((err,data) => {
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| ability | ElementName | Yes| No| Information that matches an ability. |
| pid | number | Yes| No| Process ID.|
| uid | number | Yes| No| User ID. |
| processName | string | Yes| No| Process name. |
| startTime | number | Yes| No| Ability start time. |
| abilityState | [abilityManager.AbilityState](#abilitymanagerabilitystate) | Yes| No| Ability state. |
## abilityManager.AbilityState
Enumerates the ability states.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name| Value| Description|
| -------- | -------- | -------- |
| INITIAL | 0 | The ability is in the initial state.|
| FOREGROUND | 9 | The ability is in the foreground state. |
| BACKGROUND | 10 | The ability is in the background state. |
| FOREGROUNDING | 11 | The ability is in the foregrounding state. |
| BACKGROUNDING | 12 | The ability is in the backgrounding state. |
| ability | ElementName | Yes| No| Information that matches an ability. |
| pid | number | Yes| No| Process ID.|
| uid | number | Yes| No| User ID. |
| processName | string | Yes| No| Process name. |
| startTime | number | Yes| No| Ability start time. |
| abilityState | [abilityManager.AbilityState](js-apis-application-abilityManager.md#abilitystate) | Yes| No| Ability state. |
# AbilityStageContext
The **AbilityStageContext** module, inherited from [Context](js-apis-application-context.md), implements the context of an ability stage.
This module provides APIs for accessing a specific ability stage. You can use the APIs to obtain the **ModuleInfo** object and environment configuration of an ability stage.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
Implements the context of an ability stage. This module is inherited from [Context](js-apis-application-context.md).
## Modules to Import
```js
import AbilityStage from '@ohos.application.AbilityStage';
```
## Usage
The ability stage context is obtained through an **AbilityStage** instance.
......
......@@ -21,7 +21,7 @@ Creates an **AppAccountManager** instance.
**System capability**: SystemCapability.Account.AppAccount
**Return Value**
**Return value**
| Type | Description |
| ----------------- | ------------ |
......@@ -102,7 +102,7 @@ Adds an app account name and additional information (information that can be con
| name | string | Yes | Name of the app account to add. |
| extraInfo | string | Yes | Additional information to add. The additional information cannot contain sensitive information, such as the app account password.|
**Return Value**
**Return value**
| Type | Description |
| ------------------- | --------------------- |
......@@ -198,7 +198,7 @@ Deletes an app account from the **AppAccountManager** service. This API uses a p
| ---- | ------ | ---- | ----------- |
| name | string | Yes | Name of the app account to delete.|
**Return Value**
**Return value**
| Type | Description |
| :------------------ | :-------------------- |
......@@ -255,7 +255,7 @@ Disables an app account from accessing an app with the given bundle name. This A
| name | string | Yes | Name of the target app account.|
| bundleName | string | Yes | Bundle name of the app. |
**Return Value**
**Return value**
| Type | Description |
| :------------------ | :-------------------- |
......@@ -312,7 +312,7 @@ Enables an app account to access an app with the given bundle name. This API use
| name | string | Yes | Name of the target app account. |
| bundleName | string | Yes | Bundle name of the app.|
**Return Value**
**Return value**
| Type | Description |
| :------------------ | :-------------------- |
......@@ -371,7 +371,7 @@ Checks whether an app account allows app data synchronization. This API uses a p
| ---- | ------ | ---- | ------- |
| name | string | Yes | Name of the target app account.|
**Return Value**
**Return value**
| Type | Description |
| :--------------------- | :-------------------- |
......@@ -430,7 +430,7 @@ Sets a credential for an app account. This API uses a promise to return the resu
| credentialType | string | Yes | Type of the credential to set.|
| credential | string | Yes | Credential to set. |
**Return Value**
**Return value**
| Type | Description |
| :------------------ | :-------------------- |
......@@ -487,7 +487,7 @@ Sets additional information for an app account. This API uses a promise to retur
| name | string | Yes | Name of the target app account. |
| extraInfo | string | Yes | Additional information to set.|
**Return Value**
**Return value**
| Type | Description |
| :------------------ | :-------------------- |
......@@ -548,7 +548,7 @@ Sets whether to enable app data synchronization for an app account. This API use
| name | string | Yes | Name of the target app account. |
| isEnable | boolean | Yes | Whether to enable app data synchronization.|
**Return Value**
**Return value**
| Type | Description |
| :------------------ | :-------------------- |
......@@ -606,7 +606,7 @@ Sets data to be associated with an app account. This API uses a promise to retur
| key | string | Yes | Key of the data to set. The private key can be customized.|
| value | string | Yes | Value of the data to be set. |
**Return Value**
**Return value**
| Type | Description |
| :------------------ | :-------------------- |
......@@ -664,7 +664,7 @@ Obtains the credential of an app account. This API uses a promise to return the
| name | string | Yes | Name of the target app account. |
| credentialType | string | Yes | Type of the credential to obtain.|
**Return Value**
**Return value**
| Type | Description |
| :-------------------- | :-------------------- |
......@@ -720,7 +720,7 @@ Obtains additional information of an app account. This API uses a promise to ret
| ---- | ------ | ---- | ------- |
| name | string | Yes | Name of the target app account.|
**Return Value**
**Return value**
| Type | Description |
| :-------------------- | :-------------------- |
......@@ -778,7 +778,7 @@ Obtains data associated with an app account. This API uses a promise to return t
| name | string | Yes | Name of the target app account. |
| key | string | Yes | Key of the data to obtain.|
**Return Value**
**Return value**
| Type | Description |
| :-------------------- | :-------------------- |
......
# EnvironmentCallback
The **EnvironmentCallback** module provides the **onConfigurationUpdated** API for the application context to listen for system environment changes.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
## Modules to Import
```js
import EnvironmentCallback from "@ohos.application.EnvironmentCallback";
```
## EnvironmentCallback.onConfigurationUpdated
onConfigurationUpdated(config: Configuration): void;
Called when the system environment changes.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [Configuration](js-apis-configuration.md) | Yes| **Configuration** object after the change.|
**Example**
```js
import AbilityStage from "@ohos.application.AbilityStage";
var callbackId;
export default class MyAbilityStage extends AbilityStage {
onCreate() {
console.log("MyAbilityStage onCreate")
globalThis.applicationContext = this.context.getApplicationContext();
let EnvironmentCallback = {
onConfigurationUpdated(config){
console.log("onConfigurationUpdated config:" + JSON.stringify(config));
},
}
// 1. Obtain an applicationContext object.
let applicationContext = globalThis.applicationContext;
// 2. Register a listener for the environment changes through the applicationContext object.
callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback);
console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId));
}
onDestroy() {
let applicationContext = globalThis.applicationContext;
applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => {
console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error));
});
}
}
```
# MissionSnapshot
The **MissionSnapshot** module provides the mission snapshot information of an ability.
> **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 APIs of this module are system APIs and cannot be called by third-party applications.
Provides the snapshot of a mission.
## Usage
## Modules to Import
The mission snapshot information can be obtained by using **getMissionSnapShot** in **missionManager**.
```
import missionManager from '@ohos.application.missionManager'
```js
import ElementName from '@ohos.bundle';
import image from '@ohos.multimedia.image';
```
import missionManager from '@ohos.application.missionManager'
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
missionManager.getMissionSnapShot("", id, (error, snapshot) => {
console.log("getMissionSnapShot is called, error.code = " + error.code);
console.log("bundleName = " + snapshot.ability.bundleName);
})
})
```
## MissionSnapshot
Describes the mission snapshot.
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| ability | ElementName | Yes| Yes| Information that matches an ability.|
......
# StartOptions
The **StartOptions** module implements ability startup options.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
**StartOptions** is the basic communication component of the system.
## Modules to Import
```
......@@ -15,10 +15,9 @@ import StartOptions from '@ohos.application.StartOptions';
## Attributes
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name| Readable| Writable| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- | -------- |
| [windowMode](js-apis-window.md#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.|
# Want
The **Want** module provides the basic communication component of the system.
> **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.
**Want** is the basic communication component of the system.
## Modules to Import
```
......@@ -20,11 +20,26 @@ import Want from '@ohos.application.Want';
| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| deviceId | Read only | string | No | ID of the device running the ability. |
| bundleName | Read only | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.|
| abilityName | Read only | string | No | Name of the ability. If both **package** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.|
| abilityName | Read only | string | No | Name of the ability. If both **package** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.|
| uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.|
| type | Read only | string | No | MIME type, for example, **text/plain** or **image/***. |
| flags | Read only | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-featureAbility.md#flags).|
| action | Read only | string | No | Action option. |
| parameters | Read only | {[key: string]: any} | No | List of parameters in the **Want** object. |
| parameters | Read only | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:<br>**ohos.aafwk.callerPid**: PID of the caller.<br>**ohos.aafwk.param.callerToken**: token of the caller.<br>**ohos.aafwk.param.callerUid**: UID of the caller. The **userId** parameter in the [Bundle](js-apis-Bundle.js) module can be used to obtain application and bundle information. |
| entities | Read only | Array\<string> | No | List of entities. |
| moduleName<sup>9+</sup> | Read only | string | No | Module to which the ability belongs. Different abilities among HAP files in an application may use the same name. If the abilities cannot be distinguished by the combination of **bundleName** and **abilityName**, you can set **moduleName** for better distinguishing.| |
| moduleName<sup>9+</sup> | Read only | string | No | Module to which the ability belongs.|
**Example**
``` js
var want = {
"deviceId": "", // An empty deviceId indicates the local device.
"bundleName": "com.extreme.test",
"abilityName": "MainAbility",
"moduleName": "entry" // moduleName is optional.
};
this.context.startAbility(want, (error) => {
// Start an ability explicitly. The bundleName, abilityName, and moduleName parameters uniquely identify an ability.
console.log("error.code = " + error.code)
})
```
# AbilityConstant
The **AbilityConstant** module provides ability launch parameters.
The parameters include the initial launch reasons, reasons for the last exit, and ability continuation results.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
Provides parameters related to ability launch.
## Modules to Import
```js
......@@ -17,10 +19,10 @@ import AbilityConstant from '@ohos.application.AbilityConstant';
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name| Type| Readable| Writable| Description|
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| launchReason | LaunchReason| Yes| Yes| Ability launch reason.|
| lastExitReason | LastExitReason | Yes| Yes| Reason for the last exit.|
| launchReason | LaunchReason| Yes| Yes| Ability launch reason.|
| lastExitReason | LastExitReason | Yes| Yes| Reason for the last exit.|
## AbilityConstant.LaunchReason
......@@ -60,3 +62,17 @@ Enumerates ability continuation results.
| AGREE | 0 | Continuation agreed.|
| REJECT | 1 | Continuation denied.|
| 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.|
......@@ -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.
Provides the Extension ability information.
The **ExtensionAbilityInfo** module provides Extension ability information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**.
## ExtensionAbilityInfo
......@@ -28,5 +26,5 @@ Provides the Extension ability information.
| 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. |
| 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. |
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册