提交 fd14ed3d 编写于 作者: X xuzhihao

Merge branch 'master' of https://gitee.com/xuzhihao666/docs

Signed-off-by: Nxuzhihao <xuzhihao16@huawei.com>
...@@ -200,7 +200,7 @@ zh-cn/application-dev/reference/apis/js-apis-screenshot.md @ge-yafang ...@@ -200,7 +200,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-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-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-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-webgl.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-webgl2.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 zh-cn/application-dev/reference/apis/js-apis-audio.md @zengyawen
......
...@@ -7,6 +7,8 @@ The distributed data objects allow data across devices to be processed like loca ...@@ -7,6 +7,8 @@ The distributed data objects allow data across devices to be processed like loca
## Available APIs ## 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 ### 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**. 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. ...@@ -15,7 +17,7 @@ Call **createDistributedObject()** to create a distributed data object instance.
**Table 1** API for creating a distributed data object instance **Table 1** API for creating a distributed data object instance
| Package| API| Description| | 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 ### Generating a Session ID
...@@ -33,16 +35,16 @@ Call **setSessionId()** to set a session ID for a distributed data object. The s ...@@ -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 **Table 3** API for setting a session ID
| Class| API| Description| | 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 ### 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. 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 **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.| | 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 ### Observing Online or Offline Status
...@@ -67,13 +69,13 @@ The saved data will be released in the following cases: ...@@ -67,13 +69,13 @@ The saved data will be released in the following cases:
- The application has been uninstalled. - The application has been uninstalled.
- Data is successfully restored. - 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| | 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): 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| 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(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(): Promise&lt;RevokeSaveSuccessResponse&gt; | Revokes the data saving operation. This API uses a promise to return the result.|
## How to Develop ## How to Develop
...@@ -157,7 +159,7 @@ The following example shows how to implement a distributed data object synchroni ...@@ -157,7 +159,7 @@ The following example shows how to implement a distributed data object synchroni
local_object.on("change", this.changeCallback.bind(this)); 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: The sample code is as follows:
```js ```js
...@@ -205,41 +207,39 @@ The following example shows how to implement a distributed data object synchroni ...@@ -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. 10. Save a distributed data object and revoke the data saving operation.
- Callback - Callback
```js
```js // Save a distributed data object.
// Save a distributed data object. local_object.save("local", (result, data)=>{
local_object.save("local", (result, data)=>{ console.log("save callback");
console.log("save callback"); console.info("save sessionId " + data.sessionId);
console.info("save sessionId " + data.sessionId); console.info("save version " + data.version);
console.info("save version " + data.version); console.info("save deviceId " + data.deviceId);
console.info("save deviceId " + data.deviceId); });
}); // Revoke the data saving operation.
// Revoke the data saving operation. local_object.revokeSave((result, data) =>{
local_object.revokeSave((result, data) =>{ console.log("revokeSave callback");
console.log("revokeSave callback"); console.info("revokeSave sessionId " + data.sessionId);
console.info("revokeSave sessionId " + data.sessionId); });
}); ```
``` - Promise
- Promise ```js
// Save a distributed data object.
```js g_object.save("local").then((result)=>{
// Save a distributed data object. console.info("save sessionId " + result.sessionId);
g_object.save("local").then((result)=>{ console.info("save version " + result.version);
console.info("save sessionId " + result.sessionId); console.info("save deviceId " + result.deviceId);
console.info("save version " + result.version); }, (result)=>{
console.info("save deviceId " + result.deviceId); console.info("save local failed.");
}, (result)=>{ });
console.info("save local failed."); // Revoke the data saving operation.
}); g_object.revokeSave().then((result)=>{
// Revoke the data saving operation. console.info("revokeSave success.");
g_object.revokeSave().then((result)=>{ }, (result)=>{
console.info("revokeSave success."); console.info("revokeSave failed.");
}, (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.
```
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.
The sample code is as follows: The sample code is as follows:
```js ```js
......
...@@ -7,19 +7,21 @@ The Distributed Data Service (DDS) implements synchronization of application dat ...@@ -7,19 +7,21 @@ The Distributed Data Service (DDS) implements synchronization of application dat
## Available APIs ## 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. The table below describes the APIs provided by the OpenHarmony DDS module.
**Table 1** APIs provided by the DDS **Table 1** APIs provided by the DDS
| Category | API | Description | | 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.| | 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**. | | 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| 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| 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. | | 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. | | 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. | | 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. ...@@ -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. The following uses a single KV store as an example to describe the development procedure.
1. Import the distributed data module. 1. Import the distributed data module.
```js ```js
import distributedData from '@ohos.data.distributedData'; import distributedData from '@ohos.data.distributedData';
``` ```
2. Create a **KvManager** instance based on the specified **KvManagerConfig** object. 2. Create a **KvManager** instance based on the specified **KvManagerConfig** object.
1. Create a **KvManagerConfig** object based on the application context. (1) Create a **KvManagerConfig** object based on the application context.
2. Create a **KvManager** instance. (2) Create a **KvManager** instance.
The sample code is as follows: The sample code is as follows:
```js ```js
...@@ -63,8 +64,8 @@ The following uses a single KV store as an example to describe the development p ...@@ -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. 3. Create and obtain a single KV store.
1. Declare the ID of the single KV store to create. (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. (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: The sample code is as follows:
```js ```js
...@@ -91,12 +92,11 @@ The following uses a single KV store as an example to describe the development p ...@@ -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. > 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: The following is the sample code for subscribing to the data changes of a single KV store:
```js ```js
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
console.log("dataChange callback call data: " + JSON.stringify(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 ...@@ -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. 5. Write data to the single KV store.
1. Construct the key and value to be written 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. (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: 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 ...@@ -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. 6. Query data in the single KV store.
1. Construct the key to be queried 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. (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: The following is the sample code for querying data of the string type from the single KV store:
```js ```js
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-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 ...@@ -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 ...@@ -34,7 +34,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
| Class| API| Description| | 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.| | 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** - **Updating data**
...@@ -190,7 +190,7 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -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.| | 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** **Backing Up an RDB Store**
...@@ -198,8 +198,8 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -198,8 +198,8 @@ You can obtain the distributed table name for a remote device based on the local
| Class| API| Description| | 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, 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 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): 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** **Restoring an RDB Store**
...@@ -207,8 +207,8 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -207,8 +207,8 @@ You can obtain the distributed table name for a remote device based on the local
| Class| API| Description| | 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, 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 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): 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 ## How to Develop
...@@ -270,7 +270,7 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -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")) const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType"))
resultSet.close() resultSet.close()
}) })
``` ```
4. Set the distributed tables to be synchronized. 4. Set the distributed tables to be synchronized.
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
## When to Use ## 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. 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. 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 ## Available APIs
...@@ -23,7 +22,7 @@ import stats from '@ohos.bundleState'; ...@@ -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(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 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 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 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 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.| | 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'; ...@@ -45,7 +44,7 @@ import stats from '@ohos.bundleState';
..., ...,
"reqPermissions": [ "reqPermissions": [
{ {
"name": "ohos.permission.BUNDLE_ACTIVE_INFO" "name": "ohos.permission.BUNDLE_ACTIVE_INFO"
} }
] ]
} }
...@@ -57,13 +56,13 @@ import stats from '@ohos.bundleState'; ...@@ -57,13 +56,13 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryBundleActiveStates(0, 20000000000000).then( res => { stats.queryBundleActiveStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise success.'); console.log('BUNDLE_ACTIVE queryBundleActiveStates promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleActiveStates promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise result ' + JSON.stringify(res[i])); 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); console.log('BUNDLE_ACTIVE queryBundleActiveStates promise failed, because: ' + err.code);
}); });
...@@ -87,7 +86,7 @@ import stats from '@ohos.bundleState'; ...@@ -87,7 +86,7 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryBundleStateInfos(0, 20000000000000).then( res => { stats.queryBundleStateInfos(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise success.'); console.log('BUNDLE_ACTIVE queryBundleStateInfos promise success.');
let i = 1; let i = 1;
for (let key in res){ for (let key in res){
...@@ -95,7 +94,7 @@ import stats from '@ohos.bundleState'; ...@@ -95,7 +94,7 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise result ' + JSON.stringify(res[key])); console.log('BUNDLE_ACTIVE queryBundleStateInfos promise result ' + JSON.stringify(res[key]));
i++; i++;
} }
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryBundleStateInfos promise failed, because: ' + err.code);
}); });
...@@ -121,13 +120,13 @@ import stats from '@ohos.bundleState'; ...@@ -121,13 +120,13 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryCurrentBundleActiveStates(0, 20000000000000).then( res => { stats.queryCurrentBundleActiveStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.'); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise result ' + JSON.stringify(res[i])); 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); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise failed, because: ' + err.code);
}); });
...@@ -151,13 +150,13 @@ import stats from '@ohos.bundleState'; ...@@ -151,13 +150,13 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then( res => { stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.'); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise result ' + JSON.stringify(res[i])); 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); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise failed, because: ' + err.code);
}); });
...@@ -179,14 +178,14 @@ import stats from '@ohos.bundleState'; ...@@ -179,14 +178,14 @@ import stats from '@ohos.bundleState';
```js ```js
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryAppUsagePriorityGroup().then( res => { stats.queryAppUsagePriorityGroup().then(res => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(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); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code);
}); });
// Callback mode // Callback mode
stats.queryAppUsagePriorityGroup((err, res) => { stats.queryAppUsagePriorityGroup((err, res) => {
if (err) { if (err) {
...@@ -196,16 +195,16 @@ import stats from '@ohos.bundleState'; ...@@ -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. 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 ```js
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // 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)); 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); console.log('BUNDLE_ACTIVE isIdleState promise failed, because: ' + err.code);
}); });
...@@ -225,18 +224,18 @@ import stats from '@ohos.bundleState'; ...@@ -225,18 +224,18 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.getRecentlyUsedModules(1000).then( res => { stats.getRecentlyUsedModules(1000).then(res => {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded'); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise result ' + JSON.stringify(res[i])); 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); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise failed, because: ' + err.code);
}); });
// Promise mode when maxNum is not specified // Promise mode when maxNum is not specified
stats.getRecentlyUsedModules().then( res => { stats.getRecentlyUsedModules().then(res => {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded'); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1));
...@@ -247,7 +246,7 @@ import stats from '@ohos.bundleState'; ...@@ -247,7 +246,7 @@ import stats from '@ohos.bundleState';
}); });
// Asynchronous callback mode // Asynchronous callback mode
stats.getRecentlyUsedModules(1000,(err, res) => { stats.getRecentlyUsedModules(1000, (err, res) => {
if(err) { if(err) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code); console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code);
} else { } else {
...@@ -261,7 +260,7 @@ import stats from '@ohos.bundleState'; ...@@ -261,7 +260,7 @@ import stats from '@ohos.bundleState';
// Asynchronous callback mode when maxNum is not specified // Asynchronous callback mode when maxNum is not specified
stats.getRecentlyUsedModules((err, res) => { stats.getRecentlyUsedModules((err, res) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code); console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback succeeded.'); console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback succeeded.');
...@@ -279,10 +278,10 @@ import stats from '@ohos.bundleState'; ...@@ -279,10 +278,10 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // 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 success.');
console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise result ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise result ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise failed, because: ' + err.code);
}); });
...@@ -301,15 +300,15 @@ import stats from '@ohos.bundleState'; ...@@ -301,15 +300,15 @@ import stats from '@ohos.bundleState';
```js ```js
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // 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 success.');
console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise result ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise result ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise failed, because: ' + err.code);
}); });
// Asynchronous callback mode // Asynchronous callback mode
stats.queryBundleActiveEventStates(0, 20000000000000, (err, res) => { stats.queryBundleActiveEventStates(0, 20000000000000, (err, res) => {
if (err) { if (err) {
...@@ -325,14 +324,14 @@ import stats from '@ohos.bundleState'; ...@@ -325,14 +324,14 @@ import stats from '@ohos.bundleState';
```js ```js
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode without parameters // Promise mode without parameters
stats.queryAppUsagePriorityGroup().then( res => { stats.queryAppUsagePriorityGroup().then(res => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(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); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code);
}); });
// Asynchronous callback mode without parameters // Asynchronous callback mode without parameters
stats.queryAppUsagePriorityGroup((err, res) => { stats.queryAppUsagePriorityGroup((err, res) => {
if (err) { if (err) {
...@@ -341,17 +340,17 @@ import stats from '@ohos.bundleState'; ...@@ -341,17 +340,17 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res));
} }
}); });
// Promise mode with parameters // 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)); 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); console.log('BUNDLE_ACTIVE QueryPackageGroup promise failed. because: ' + err.code);
}); });
// Asynchronous callback mode with parameters // Asynchronous callback mode with parameters
stats.queryAppUsagePriorityGroup(this.bundleName, (err, res) => { stats.queryAppUsagePriorityGroup(this.bundleName, (err, res) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code); console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE QueryPackageGroup callback succeeded. result: ' + JSON.stringify(res));
...@@ -363,16 +362,16 @@ import stats from '@ohos.bundleState'; ...@@ -363,16 +362,16 @@ import stats from '@ohos.bundleState';
```javascript ```javascript
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.setBundleGroup(this.bundleName, this.newGroup).then( () => { stats.setBundleGroup(this.bundleName, this.newGroup).then(() => {
console.log('BUNDLE_ACTIVE SetBundleGroup promise succeeded.'); console.log('BUNDLE_ACTIVE SetBundleGroup promise succeeded.');
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE SetBundleGroup promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE SetBundleGroup promise failed. because: ' + err.code);
}); });
// Asynchronous callback mode // Asynchronous callback mode
stats.setBundleGroup(this.bundleName, this.newGroup, (err) => { stats.setBundleGroup(this.bundleName, this.newGroup, (err) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE SetBundleGroup callback failed. because: ' + err.code); console.log('BUNDLE_ACTIVE SetBundleGroup callback failed. because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE SetBundleGroup callback succeeded.'); console.log('BUNDLE_ACTIVE SetBundleGroup callback succeeded.');
...@@ -384,9 +383,9 @@ import stats from '@ohos.bundleState'; ...@@ -384,9 +383,9 @@ import stats from '@ohos.bundleState';
```javascript ```javascript
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
let onBundleGroupChanged = (err,res) =>{ let onBundleGroupChanged = (err,res) => {
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.'); 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 oldGroup is : ' + res.oldGroup);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result newGroup is : ' + res.newGroup); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result newGroup is : ' + res.newGroup);
...@@ -394,13 +393,13 @@ import stats from '@ohos.bundleState'; ...@@ -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 userId is : ' + res.userId);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result bundleName is : ' + res.bundleName); 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.'); console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise succeeded.');
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise failed. because: ' + err.code);
}); });
// Asynchronous callback mode // 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 callback success.');
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's oldGroup is : ' + res.oldGroup); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's oldGroup is : ' + res.oldGroup);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's newGroup is : ' + res.newGroup); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's newGroup is : ' + res.newGroup);
...@@ -408,29 +407,29 @@ import stats from '@ohos.bundleState'; ...@@ -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 userId is : ' + res.userId);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's bundleName is : ' + res.bundleName); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's bundleName is : ' + res.bundleName);
}; };
stats.registerGroupCallBack(onBundleGroupChanged, (err)=>{ stats.registerGroupCallBack(onBundleGroupChanged, (err) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback failed, because: ' + err.code); console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback failed, because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback success.');
} }
}); });
``` ```
13. Deregister the callback for application group changes. 13. Deregister the callback for application group changes.
```javascript ```javascript
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
//promise //promise
stats.unRegisterGroupCallBack().then( () => { stats.unRegisterGroupCallBack().then(() => {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise succeeded.'); console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise succeeded.');
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise failed. because: ' + err.code);
}); });
//callback //callback
stats.unRegisterGroupCallBack((err)=>{ stats.unRegisterGroupCallBack((err) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback failed, because: ' + err.code); console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback failed, because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback success.');
......
...@@ -3,9 +3,9 @@ ...@@ -3,9 +3,9 @@
## When to Use ## 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 ## Available APIs
......
...@@ -2273,7 +2273,43 @@ Writes the buffer. This API uses an asynchronous callback to return the result. ...@@ -2273,7 +2273,43 @@ Writes the buffer. This API uses an asynchronous callback to return the result.
``` ```
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility'
var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000,
channels: audio.AudioChannel.CHANNEL_2,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}
var audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_SPEECH,
usage: audio.streamUsage.STREAM_USAGE_VOICE_COMMUNICATION
rendererFlags: 1
}
var audioRendererOptions = {
streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo
}
var audioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data)=> {
audioRenderer = data;
console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS');
}).catch((err) => {
console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message);
});
var bufferSize;
audioRenderer.getBufferSize().then((data)=> {
console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data);
bufferSize = data;
}).catch((err) => {
console.info.('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message);
});
console.info('Buffer size:'+bufferSize);
var context = featureAbility.getContext();
var path = await context.getCacheDir();
var filePath = path+"/StarWars10s-2C-48000-4SW.wav"
let ss = fileio.createStreamSync(filePath, 'r'); let ss = fileio.createStreamSync(filePath, 'r');
let buf = new ArrayBuffer(bufferSize); let buf = new ArrayBuffer(bufferSize);
ss.readSync(buf); ss.readSync(buf);
...@@ -2305,7 +2341,42 @@ Writes the buffer. This API uses a promise to return the result. ...@@ -2305,7 +2341,42 @@ Writes the buffer. This API uses a promise to return the result.
``` ```
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility'
var audioStreamInfo = {
samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000,
channels:audio.AudioChannel.CHANNEL_2,
sampleFormat.audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE,
encodingType.audio.AudioEncodingType.ENCODING_TYPE_RAW
}
var audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_SPEECH,
usage: audio.streamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
rendererFlags: 1
}
var audioRendererOptions = {
streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo
}
var audioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data) => {
audioRenderer = data;
console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS');
}).catch((err) => {
console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message);
});
var bufferSize;
audioRenderer.getBufferSize().then((data) => {
console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data);
bufferSize = data;
}).catch((err) => {
console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message);
});
console.info('BufferSize: ' + bufferSize);
var context = featureAbility.getContext();
var path = await context.getCacheDir();
var filePath = 'data/StarWars10s-2C-48000-4SW.wav'; var filePath = 'data/StarWars10s-2C-48000-4SW.wav';
let ss = fileio.createStreamSync(filePath, 'r'); let ss = fileio.createStreamSync(filePath, 'r');
let buf = new ArrayBuffer(bufferSize); let buf = new ArrayBuffer(bufferSize);
...@@ -2408,12 +2479,39 @@ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a ...@@ -2408,12 +2479,39 @@ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a
**Example** **Example**
``` ```
import audio from '@ohos.multimedia.audio';
import fileio from '@ohos.fileio';
var audioStreamInfo = {
samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000,
channels:audio.AudioChannel.CHANNEL_2,
sampleFormat.audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE,
encodingType.audio.AudioEncodingType.ENCODING_TYPE_RAW
}
var audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_SPEECH,
usage: audio.streamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
rendererFlags: 1
}
var audioRendererOptions = {
streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo
}
var audioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data) => {
audioRenderer = data;
console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS');
}).catch((err) => {
console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message);
});
var bufferSize; var bufferSize;
await audioRenderer.getBufferSize().then(async function (data) => { audioRenderer.getBufferSize().then((data) => {
console.info('AudioFrameworkRenderLog: getBufferSize :SUCCESS '+data); console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data);
bufferSize=data; bufferSize=data;
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRenderLog: getBufferSize :ERROR : '+err.message); console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message);
}); });
``` ```
...@@ -2542,7 +2640,8 @@ Sets the audio interruption mode for the application. This API uses a promise to ...@@ -2542,7 +2640,8 @@ Sets the audio interruption mode for the application. This API uses a promise to
**Example** **Example**
``` ```
audioManager.setInterruptMode(audio.InterruptType.SHARE_MODE).then(() => { const audioManager = audio.getAudioManager();
audioManager.setInterruptMode(audio.InterruptMode.SHARE_MODE).then(() => {
console.log('Promise returned to indicate a successful volume setting.'); console.log('Promise returned to indicate a successful volume setting.');
}); });
``` ```
...@@ -2564,7 +2663,8 @@ Sets the audio interruption mode for the application. This API uses a callback t ...@@ -2564,7 +2663,8 @@ Sets the audio interruption mode for the application. This API uses a callback t
**Example** **Example**
``` ```
audioManager.setInterruptMode(audio.InterruptType.SHARE_MODE,()=>{ const audioManager = audio.getAudioManager();
audioManager.setInterruptMode(audio.InterruptMode.SHARE_MODE,()=>{
console.log('Callback returned to indicate a successful volume setting.'); console.log('Callback returned to indicate a successful volume setting.');
}); });
``` ```
...@@ -2654,7 +2754,7 @@ Subscribes to mark reached events. When the number of frames rendered reaches th ...@@ -2654,7 +2754,7 @@ Subscribes to mark reached events. When the number of frames rendered reaches th
``` ```
audioRenderer.on('markReach', 1000, (position) => { audioRenderer.on('markReach', 1000, (position) => {
if (position == "1000") { if (position == 1000) {
console.log('ON Triggered successfully'); console.log('ON Triggered successfully');
} }
}); });
...@@ -2701,7 +2801,7 @@ Subscribes to period reached events. When the period of frame rendering reaches ...@@ -2701,7 +2801,7 @@ Subscribes to period reached events. When the period of frame rendering reaches
``` ```
audioRenderer.on('periodReach', 1000, (position) => { audioRenderer.on('periodReach', 1000, (position) => {
if (position == "1000") { if (position == 1000) {
console.log('ON Triggered successfully'); console.log('ON Triggered successfully');
} }
}); });
...@@ -2935,13 +3035,35 @@ Starts capturing. This API uses a promise to return the result. ...@@ -2935,13 +3035,35 @@ Starts capturing. This API uses a promise to return the result.
**Example** **Example**
``` ```
import audio from '@ohos.multimedia.audio';
import fileio from '@ohos.fileio';
var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_2,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}
var audioCapturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags = 1
}
var audioCapturer;
audio.createAudioCapturer(audioCapturerOptions).then((data) => {
audioCapturer = data;
console.info('AudioFrameworkRecLog: AudioCapturer Created: SUCCESS');
}).catch((err) => {
console.info('AudioFrameworkRecLog: AudioCapturer Created: ERROR: '+err.message);
});
audioCapturer.start().then(() => { audioCapturer.start().then(() => {
console.info('AudioFrameworkRecLog: ---------START---------'); console.info('AudioFrameworkRecLog: ---------START---------');
console.info('AudioFrameworkRecLog: Capturer started :SUCCESS '); console.info('AudioFrameworkRecLog: Capturer started: SUCCESS');
console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state); console.info('AudioFrameworkRecLog: AudioCapturer: STATE: '+audioCapturer.state);
console.info('AudioFrameworkRecLog: Capturer started :SUCCESS '); console.info('AudioFrameworkRecLog: Capturer started: SUCCESS ');
if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) {
stateFlag = true; console.info('AudioFrameworkRecLog: AudioCapturer is in Running State');
} }
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecLog: Capturer start :ERROR : '+err.message); console.info('AudioFrameworkRecLog: Capturer start :ERROR : '+err.message);
...@@ -2994,15 +3116,13 @@ Stops capturing. This API uses a promise to return the result. ...@@ -2994,15 +3116,13 @@ Stops capturing. This API uses a promise to return the result.
``` ```
audioCapturer.stop().then(() => { audioCapturer.stop().then(() => {
console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); console.info('AudioFrameworkRecLog: ---------STOP RECORD---------');
console.info('AudioFrameworkRecLog: Capturer stopped : SUCCESS'); console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS');
if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){
stateFlag=true; console.info('AudioFrameworkRecLog: State is Stopped': ');
console.info('AudioFrameworkRecLog: resultFlag : '+stateFlag);
} }
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecLog: Capturer stop:ERROR : '+err.message); console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+err.message);
stateFlag=false;
}); });
``` ```
...@@ -3054,11 +3174,9 @@ audioCapturer.release().then(() => { ...@@ -3054,11 +3174,9 @@ audioCapturer.release().then(() => {
console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------');
console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); console.info('AudioFrameworkRecLog: Capturer release : SUCCESS');
console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state); console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state);
stateFlag=true;
console.info('AudioFrameworkRecLog: stateFlag : '+stateFlag); console.info('AudioFrameworkRecLog: stateFlag : '+stateFlag);
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecLog: Capturer stop:ERROR : '+err.message); console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+err.message);
stateFlag=false
}); });
``` ```
...@@ -3082,6 +3200,13 @@ Reads the buffer. This API uses an asynchronous callback to return the result. ...@@ -3082,6 +3200,13 @@ Reads the buffer. This API uses an asynchronous callback to return the result.
**Example** **Example**
``` ```
var bufferSize;
audioCapturer.getBufferSize().then((data) => {
console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS '+data);
bufferSize = data;
}).catch((err) => {
console.info('AudioFrameworkRecLog: getBufferSize: EROOR: '+err.message);
});
audioCapturer.read(bufferSize, true, async(err, buffer) => { audioCapturer.read(bufferSize, true, async(err, buffer) => {
if (!err) { if (!err) {
console.log("Success in reading the buffer data"); console.log("Success in reading the buffer data");
...@@ -3114,6 +3239,14 @@ Reads the buffer. This API uses a promise to return the result. ...@@ -3114,6 +3239,14 @@ Reads the buffer. This API uses a promise to return the result.
**Example** **Example**
``` ```
var bufferSize;
audioCapturer.getBufferSize().then((data) => {
console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS '+data);
bufferSize = data;
}).catch((err) => {
console.info('AudioFrameworkRecLog: getBufferSize: ERROR '+err.message);
});
console.info('Buffer size: ' + bufferSize);
audioCapturer.read(bufferSize, true).then((buffer) => { audioCapturer.read(bufferSize, true).then((buffer) => {
console.info('buffer read successfully'); console.info('buffer read successfully');
}).catch((err) => { }).catch((err) => {
...@@ -3217,12 +3350,12 @@ Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a ...@@ -3217,12 +3350,12 @@ Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a
**Example** **Example**
``` ```
await audioCapturer.getBufferSize().then(async function (bufferSize) { var bufferSize;
console.info('AudioFrameworkRecordLog: getBufferSize :SUCCESS '+ bufferSize); audioCapturer.getBufferSize().then((data) => {
var buffer = await audioCapturer.read(bufferSize, true); console.info('AudioFrameworkRecLog: getBufferSize :SUCCESS '+ data);
console.info('Buffer read is ' + buffer ); bufferSize = data;
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecordLog: getBufferSize :ERROR : '+err.message); console.info('AudioFrameworkRecLog: getBufferSize :ERROR : '+ err.message);
}); });
``` ```
...@@ -3247,7 +3380,7 @@ Subscribes to mark reached events. When the number of frames captured reaches th ...@@ -3247,7 +3380,7 @@ Subscribes to mark reached events. When the number of frames captured reaches th
``` ```
audioCapturer.on('markReach', 1000, (position) => { audioCapturer.on('markReach', 1000, (position) => {
if (position == "1000") { if (position == 1000) {
console.log('ON Triggered successfully'); console.log('ON Triggered successfully');
} }
}); });
...@@ -3293,7 +3426,7 @@ Subscribes to mark reached events. When the period of frame capturing reaches th ...@@ -3293,7 +3426,7 @@ Subscribes to mark reached events. When the period of frame capturing reaches th
``` ```
audioCapturer.on('periodReach', 1000, (position) => { audioCapturer.on('periodReach', 1000, (position) => {
if (position == "1000") { if (position == 1000) {
console.log('ON Triggered successfully'); console.log('ON Triggered successfully');
} }
}); });
......
# DefaultAppManager
The **DefaultAppManager** module provides APIs to query whether the current application is the default application of a specific type.
> **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.
## Modules to Import
```
import defaultAppMgr from '@ohos.bundle.defaultAppManager'
```
## defaultAppMgr.ApplicationType
Enumerates the application types.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Description |
| -------- | -------- | -------------------------------------- |
| BROWSER | string | Default browser. |
| IMAGE | string | Default image viewer. |
| AUDIO | string | Default audio player. |
| VIDEO | string | Default video player. |
| PDF | string | Default PDF reader. |
| WORD | string | Default Word viewer. |
| EXCEL | string | Default Excel viewer. |
| PPT | string | Default PowerPoint viewer. |
## defaultAppMgr.isDefaultApplication
isDefaultApplication(type: string): Promise\<boolean>
Checks whether this application is the default application of a system-defined application type. This API uses a promise to return the result.
**System capability**: SystemCapability.BundleManager.BundleFramework
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype). |
**Return value**
| Type | Description |
| ------------------------- | ------------------ |
| Promise\<boolean> | Promise used to return the result. If the application is the default application, `true` is returned; otherwise, `false` is returned.|
**Example**
```js
defaultAppMgr.isDefaultApplication(defaultAppMgr.ApplicationType.BROWSER)
.then((data) => {
console.info('Operation successful. IsDefaultApplication ? ' + JSON.stringify(data));
}).catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
```
## defaultAppMgr.isDefaultApplication
isDefaultApplication(type: string, callback: AsyncCallback\<boolean>): void
Checks whether this application is the default application of a system-defined application type. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.BundleManager.BundleFramework
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------------------------------- | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype). |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. If the application is the default application, `true` is returned; otherwise, `false` is returned.|
**Example**
```js
defaultAppMgr.isDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful. IsDefaultApplication ? ' + JSON.stringify(data));
});
```
## defaultAppMgr.getDefaultApplication
getDefaultApplication(type: string, userId?: number): Promise\<BundleInfo>
Obtains the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| userId | number | No | User ID. The default value is the user ID of the caller. |
**Return value**
| Type | Description |
| ------------------------- | ------------------ |
| Promise\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Promise used to return the default application.|
**Example**
```js
defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER)
.then((data) => {
console.info('Operation successful. bundleInfo: ' + JSON.stringify(data));
})
.catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
defaultAppMgr.getDefaultApplication("image/png")
.then((data) => {
console.info('Operation successful. bundleInfo: ' + JSON.stringify(data));
})
.catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
```
## defaultAppMgr.getDefaultApplication
getDefaultApplication(type: string, userId: number, callback: AsyncCallback\<BundleInfo>) : void
Obtains the default application of a user based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| userId | number | Yes | User ID. |
| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the default application. |
**Example**
```js
defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, 100, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful. bundleInfo:' + JSON.stringify(data));
});
defaultAppMgr.getDefaultApplication("image/png", 100, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful. bundleInfo:' + JSON.stringify(data));
});
```
## defaultAppMgr.getDefaultApplication
getDefaultApplication(type: string, callback: AsyncCallback\<BundleInfo>) : void
Obtains the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the default application. |
**Example**
```js
defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful. bundleInfo:' + JSON.stringify(data));
});
defaultAppMgr.getDefaultApplication("image/png", (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful. bundleInfo:' + JSON.stringify(data));
});
```
## defaultAppMgr.setDefaultApplication
setDefaultApplication(type: string, elementName: ElementName, userId?: number): Promise\<void>
Sets the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses a promise to return the result.
**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | Information about the element to be set as the default application. |
| userId | number | No | User ID. The default value is the user ID of the caller. |
**Example**
```js
defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, {
bundleName: "com.test.app",
moduleName: "module01",
abilityName: "MainAbility"
})
.then((data) => {
console.info('Operation successful.');
})
.catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
defaultAppMgr.setDefaultApplication("image/png", {
bundleName: "com.test.app",
moduleName: "module01",
abilityName: "MainAbility"
})
.then((data) => {
console.info('Operation successful.');
})
.catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
```
## defaultAppMgr.setDefaultApplication
setDefaultApplication(type: string, elementName: ElementName, userId: number, callback: AsyncCallback\<void>) : void;
Sets the default application for a user based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | Information about the element to be set as the default application. |
| userId | number | Yes | User ID. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, {
bundleName: "com.test.app",
moduleName: "module01",
abilityName: "MainAbility"
}, 100, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
defaultAppMgr.setDefaultApplication("image/png", {
bundleName: "com.test.app",
moduleName: "module01",
abilityName: "MainAbility"
}, 100, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
```
## defaultAppMgr.setDefaultApplication
setDefaultApplication(type: string, elementName: ElementName, callback: AsyncCallback\<void>) : void;
Sets the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | Information about the element to be set as the default application. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, {
bundleName: "com.test.app",
moduleName: "module01",
abilityName: "MainAbility"
}, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
defaultAppMgr.setDefaultApplication("image/png", {
bundleName: "com.test.app",
moduleName: "module01",
abilityName: "MainAbility"
}, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
```
## defaultAppMgr.resetDefaultApplication
resetDefaultApplication(type: string, userId?: number): Promise\<void>
Resets the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses a promise to return the result.
**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| userId | number | No | User ID. The default value is the user ID of the caller. |
**Example**
```js
defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER)
.then((data) => {
console.info('Operation successful.');
})
.catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
defaultAppMgr.resetDefaultApplication("image/png")
.then((data) => {
console.info('Operation successful.');
})
.catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
```
## defaultAppMgr.resetDefaultApplication
resetDefaultApplication(type: string, userId: number, callback: AsyncCallback\<void>) : void;
Resets the default application for a user based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| userId | number | Yes | User ID. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, 100, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
defaultAppMgr.resetDefaultApplication("image/png", 100, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
```
## defaultAppMgr.resetDefaultApplication
resetDefaultApplication(type: string, callback: AsyncCallback\<void>) : void;
Resets the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
defaultAppMgr.resetDefaultApplication("image/png", (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
```
# Distributed Data Object # Distributed Data Object
Provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices. The distributedDataObject module provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices.
> **NOTE**<br/> > **NOTE**<br/>
> >
...@@ -23,9 +23,9 @@ Creates a distributed data object. ...@@ -23,9 +23,9 @@ Creates a distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| source | object | Yes| Attribute of the distributed data object to create.| | source | object | Yes| Attribute of the distributed data object to create.|
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -33,12 +33,11 @@ Creates a distributed data object. ...@@ -33,12 +33,11 @@ Creates a distributed data object.
| [DistributedObject](#distributedobject) | Distributed data object created.| | [DistributedObject](#distributedobject) | Distributed data object created.|
**Example** **Example**
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
// Create a distributed data object, which contains attributes of four types, namely, string, number, boolean, and object. // Create a distributed data object, which contains attributes of four types, namely, string, number, boolean, and object.
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
parent:{mother:"jack mom",father:"jack Dad"}}); ```
```
## distributedObject.genSessionId ## distributedObject.genSessionId
...@@ -50,15 +49,15 @@ Creates a random session ID. ...@@ -50,15 +49,15 @@ Creates a random session ID.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| string | Session ID created.| | string | Session ID created.|
**Example** **Example**
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var sessionId = distributedObject.genSessionId(); var sessionId = distributedObject.genSessionId();
``` ```
## SaveSuccessResponse<sup>9+</sup> ## SaveSuccessResponse<sup>9+</sup>
...@@ -98,27 +97,26 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo ...@@ -98,27 +97,26 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| | sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the session ID is set successfully;<br>returns **false** otherwise. | | boolean | Returns **true** if the session ID is set successfully;<br>returns **false** otherwise. |
**Example** **Example**
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});;
parent:{mother:"jack mom",father:"jack Dad"}}); // Add g_object to the distributed network.
// Add g_object to the distributed network. g_object.setSessionId(distributedObject.genSessionId());
g_object.setSessionId(distributedObject.genSessionId()); // Remove g_object from the distributed network.
// Remove g_object from the distributed network. g_object.setSessionId("");
g_object.setSessionId(""); ```
```
### on('change') ### on('change')
...@@ -130,15 +128,15 @@ Subscribes to the changes of this distributed data object. ...@@ -130,15 +128,15 @@ Subscribes to the changes of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback used to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.| | callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback used to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example** **Example**
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
globalThis.changeCallback = (sessionId, changeData) => { globalThis.changeCallback = (sessionId, changeData) => {
console.info("change" + sessionId); console.info("change" + sessionId);
if (changeData != null && changeData != undefined) { if (changeData != null && changeData != undefined) {
...@@ -159,16 +157,16 @@ Unsubscribes from the changes of this distributed data object. ...@@ -159,16 +157,16 @@ Unsubscribes from the changes of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.| | type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.| | callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example** **Example**
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
// Unregister the specified data change callback. // Unregister the specified data change callback.
g_object.off("change", globalThis.changeCallback); g_object.off("change", globalThis.changeCallback);
// Unregister all data change callbacks. // Unregister all data change callbacks.
...@@ -184,10 +182,10 @@ Subscribes to the status change (online or offline) of this distributed data obj ...@@ -184,10 +182,10 @@ Subscribes to the status change (online or offline) of this distributed data obj
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| | type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.<br>**sessionId**: session ID of the distributed data object.<br>**networkId**: object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline. | | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.<br>**sessionId**: session ID of the distributed data object.<br>**networkId**: object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline.|
**Example** **Example**
```js ```js
...@@ -195,7 +193,7 @@ import distributedObject from '@ohos.data.distributedDataObject'; ...@@ -195,7 +193,7 @@ import distributedObject from '@ohos.data.distributedDataObject';
globalThis.statusCallback = (sessionId, networkId, status) => { globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
} }
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
g_object.on("status", globalThis.statusCallback); g_object.on("status", globalThis.statusCallback);
``` ```
...@@ -209,16 +207,16 @@ Unsubscribes from the status change (online or offline) of this distributed data ...@@ -209,16 +207,16 @@ Unsubscribes from the status change (online or offline) of this distributed data
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| | type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.<br>**sessionId**: session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the status, which can be online or offline.| | callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.<br>**sessionId**: session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the status, which can be online or offline.|
**Example** **Example**
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
globalThis.statusCallback = (sessionId, networkId, status) => { globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
} }
...@@ -245,24 +243,24 @@ The saved data will be released in the following cases: ...@@ -245,24 +243,24 @@ The saved data will be released in the following cases:
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.| | deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.|
| callback | AsyncCallback&lt;[SaveSuccessResponse](#savesuccessresponse)&gt; | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| | callback | AsyncCallback&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
**Example** **Example**
```js
```ts import distributedObject from '@ohos.data.distributedDataObject';
import distributedObject from '@ohos.data.distributedDataObject'; var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); g_object.setSessionId("123456");
g_object.setSessionId("123456"); g_object.save("local", (status, result)=>{
g_object.save("local", (result)=>{ console.log("save status = " + status);
console.log("save callback"); console.log("save callback");
console.info("save sessionId " + result.sessionId); console.info("save sessionId: " + result.sessionId);
console.info("save version " + result.version); console.info("save version: " + result.version);
console.info("save deviceId " + result.deviceId); console.info("save deviceId: " + result.deviceId);
}); });
``` ```
### save<sup>9+</sup> ### save<sup>9+</sup>
...@@ -281,31 +279,31 @@ The saved data will be released in the following cases: ...@@ -281,31 +279,31 @@ The saved data will be released in the following cases:
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. | | deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. |
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[SaveSuccessResponse](#savesuccessresponse)&gt; | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| | Promise&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
**Example** **Example**
```ts ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456"); g_object.setSessionId("123456");
g_object.save("local").then((result)=>{ g_object.save("local").then((result)=>{
console.log("save callback"); console.log("save callback");
console.info("save sessionId " + result.sessionId); console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version); console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId); console.info("save deviceId " + result.deviceId);
}, ()=>{ }, ()=>{
console.error("save failed"); console.error("save failed");
}); });
``` ```
### revokeSave<sup>9+</sup> ### revokeSave<sup>9+</sup>
...@@ -319,20 +317,20 @@ If the object is stored on another device, the data on the local device will be ...@@ -319,20 +317,20 @@ If the object is stored on another device, the data on the local device will be
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse)&gt; | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.| | callback | AsyncCallback&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
**Example** **Example**
```ts ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456"); g_object.setSessionId("123456");
g_object.revokeSave((result, data) =>{ g_object.revokeSave((result, data) =>{
console.log("revokeSave callback"); console.log("revokeSave callback");
}); });
``` ```
### revokeSave<sup>9+</sup> ### revokeSave<sup>9+</sup>
...@@ -345,22 +343,22 @@ If the object is stored on another device, the data on the local device will be ...@@ -345,22 +343,22 @@ If the object is stored on another device, the data on the local device will be
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse)&gt; | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.| | Promise&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
**Example** **Example**
```ts ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456"); g_object.setSessionId("123456");
g_object.revokeSave("local").then((result)=>{ g_object.revokeSave().then((result)=>{
console.log("revokeSave callback"); console.log("revokeSave callback");
console.log("sessionId" + result.sessionId); console.log("sessionId" + result.sessionId);
}, ()=>{ }, ()=>{
console.error("revokeSave failed"); console.error("revokeSave failed");
}); });
``` ```
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
The distributedAccount module provides basic functions for managing distributed accounts, including querying and updating account login status. The distributedAccount module provides basic functions for managing distributed accounts, including querying and updating account login status.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br> > **NOTE**<br>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
......
...@@ -775,7 +775,7 @@ let kvStore; ...@@ -775,7 +775,7 @@ let kvStore;
try { try {
let resultSet; let resultSet;
kvStore.getResultSet('batch_test_string_key').then((result) => { kvStore.getResultSet('batch_test_string_key').then((result) => {
console.log('getResultSet succeeed.'); console.log('getResultSet succeeded.');
resultSet = result; resultSet = result;
}).catch((err) => { }).catch((err) => {
console.log('getResultSet failed: ' + err); console.log('getResultSet failed: ' + err);
...@@ -2453,10 +2453,10 @@ try { ...@@ -2453,10 +2453,10 @@ try {
console.log('entries: ' + JSON.stringify(entries)); console.log('entries: ' + JSON.stringify(entries));
kvStore.putBatch(entries, async function (err,data) { kvStore.putBatch(entries, async function (err,data) {
console.log('putBatch success'); console.log('putBatch success');
kvStore.getEntries('batch_test_string_key', function (err,entrys) { kvStore.getEntries('batch_test_string_key', function (err,entries) {
console.log('getEntries success'); console.log('getEntries success');
console.log('entrys.length: ' + entrys.length); console.log('entries.length: ' + entries.length);
console.log('entrys[0]: ' + JSON.stringify(entrys[0])); console.log('entries[0]: ' + JSON.stringify(entries[0]));
}); });
}); });
}catch(e) { }catch(e) {
...@@ -2505,7 +2505,7 @@ try { ...@@ -2505,7 +2505,7 @@ try {
console.log('entries: ' + JSON.stringify(entries)); console.log('entries: ' + JSON.stringify(entries));
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('putBatch success'); console.log('putBatch success');
kvStore.getEntries('batch_test_string_key').then((entrys) => { kvStore.getEntries('batch_test_string_key').then((entries) => {
console.log('getEntries success'); console.log('getEntries success');
console.log('PutBatch ' + JSON.stringify(entries)); console.log('PutBatch ' + JSON.stringify(entries));
}).catch((err) => { }).catch((err) => {
...@@ -3245,10 +3245,10 @@ try { ...@@ -3245,10 +3245,10 @@ try {
} }
kvStore.putBatch(entries, async function (err,data) { kvStore.putBatch(entries, async function (err,data) {
console.log('putBatch success'); console.log('putBatch success');
kvStore.getEntries('batch_test_number_key', function (err,entrys) { kvStore.getEntries('batch_test_number_key', function (err,entries) {
console.log('getEntries success'); console.log('getEntries success');
console.log('entrys.length: ' + entrys.length); console.log('entries.length: ' + entries.length);
console.log('entrys[0]: ' + JSON.stringify(entrys[0])); console.log('entries[0]: ' + JSON.stringify(entries[0]));
}); });
}); });
}catch(e) { }catch(e) {
...@@ -3297,12 +3297,12 @@ try { ...@@ -3297,12 +3297,12 @@ try {
console.log('entries: ' + entries); console.log('entries: ' + entries);
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('putBatch success'); console.log('putBatch success');
kvStore.getEntries('batch_test_string_key').then((entrys) => { kvStore.getEntries('batch_test_string_key').then((entries) => {
console.log('getEntries success'); console.log('getEntries success');
console.log('entrys.length: ' + entrys.length); console.log('entries.length: ' + entries.length);
console.log('entrys[0]: ' + JSON.stringify(entrys[0])); console.log('entries[0]: ' + JSON.stringify(entries[0]));
console.log('entrys[0].value: ' + JSON.stringify(entrys[0].value)); console.log('entries[0].value: ' + JSON.stringify(entries[0].value));
console.log('entrys[0].value.value: ' + entrys[0].value.value); console.log('entries[0].value.value: ' + entries[0].value.value);
}).catch((err) => { }).catch((err) => {
console.log('getEntries fail ' + JSON.stringify(err)); console.log('getEntries fail ' + JSON.stringify(err));
}); });
...@@ -3353,10 +3353,10 @@ try { ...@@ -3353,10 +3353,10 @@ try {
console.log('putBatch success'); console.log('putBatch success');
const query = new distributedData.Query(); const query = new distributedData.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getEntries(query, function (err,entrys) { kvStore.getEntries(query, function (err,entries) {
console.log('getEntries success'); console.log('getEntries success');
console.log('entrys.length: ' + entrys.length); console.log('entries.length: ' + entries.length);
console.log('entrys[0]: ' + JSON.stringify(entrys[0])); console.log('entries[0]: ' + JSON.stringify(entries[0]));
}); });
}); });
console.log('GetEntries success'); console.log('GetEntries success');
...@@ -3409,7 +3409,7 @@ try { ...@@ -3409,7 +3409,7 @@ try {
console.log('putBatch success'); console.log('putBatch success');
const query = new distributedData.Query(); const query = new distributedData.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getEntries(query).then((entrys) => { kvStore.getEntries(query).then((entries) => {
console.log('getEntries success'); console.log('getEntries success');
}).catch((err) => { }).catch((err) => {
console.log('getEntries fail ' + JSON.stringify(err)); console.log('getEntries fail ' + JSON.stringify(err));
...@@ -3650,7 +3650,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Predicates** ...@@ -3650,7 +3650,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Predicates**
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| predicates | Predicates | Yes |**Predicates** object to match. If this parameter is **null**, define the processing logic. | | predicates | Predicates | Yes |**Predicates** object to match. If this parameter is **null**, define the processing logic. |
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)&gt; | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.| | callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)&gt; | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.|
**Example** **Example**
...@@ -4134,7 +4134,7 @@ Synchronizes the KV store manually. This API uses a synchronous mode. For detail ...@@ -4134,7 +4134,7 @@ Synchronizes the KV store manually. This API uses a synchronous mode. For detail
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. | | deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. |
| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | | mode |[SyncMode](#syncmode) | Yes |Synchronization mode. |
| query |[Query](#querysup8sup) | Yes |**Query** object to match. | | query |[Query](#query8) | Yes |**Query** object to match. |
| delayMs |number | No |Allowed synchronization delay time, in ms. | | delayMs |number | No |Allowed synchronization delay time, in ms. |
**Example** **Example**
...@@ -4412,10 +4412,10 @@ try { ...@@ -4412,10 +4412,10 @@ try {
console.log('entries: ' + entries); console.log('entries: ' + entries);
kvStore.putBatch(entries, async function (err,data) { kvStore.putBatch(entries, async function (err,data) {
console.log('putBatch success'); console.log('putBatch success');
kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entrys) { kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entries) {
console.log('getEntries success'); console.log('getEntries success');
console.log('entrys.length: ' + entrys.length); console.log('entries.length: ' + entries.length);
console.log('entrys[0]: ' + JSON.stringify(entrys[0])); console.log('entries[0]: ' + JSON.stringify(entries[0]));
}); });
}); });
}catch(e) { }catch(e) {
...@@ -4465,12 +4465,12 @@ try { ...@@ -4465,12 +4465,12 @@ try {
console.log('entries: ' + entries); console.log('entries: ' + entries);
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('putBatch success'); console.log('putBatch success');
kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entrys) => { kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => {
console.log('getEntries success'); console.log('getEntries success');
console.log('entrys.length: ' + entrys.length); console.log('entries.length: ' + entries.length);
console.log('entrys[0]: ' + JSON.stringify(entrys[0])); console.log('entries[0]: ' + JSON.stringify(entries[0]));
console.log('entrys[0].value: ' + JSON.stringify(entrys[0].value)); console.log('entries[0].value: ' + JSON.stringify(entries[0].value));
console.log('entrys[0].value.value: ' + entrys[0].value.value); console.log('entries[0].value.value: ' + entries[0].value.value);
}).catch((err) => { }).catch((err) => {
console.log('getEntries fail ' + JSON.stringify(err)); console.log('getEntries fail ' + JSON.stringify(err));
}); });
...@@ -4522,10 +4522,10 @@ try { ...@@ -4522,10 +4522,10 @@ try {
const query = new distributedData.Query(); const query = new distributedData.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
query.deviceId('localDeviceId'); query.deviceId('localDeviceId');
kvStore.getEntries(query, function (err,entrys) { kvStore.getEntries(query, function (err,entries) {
console.log('getEntries success'); console.log('getEntries success');
console.log('entrys.length: ' + entrys.length); console.log('entries.length: ' + entries.length);
console.log('entrys[0]: ' + JSON.stringify(entrys[0])); console.log('entries[0]: ' + JSON.stringify(entries[0]));
}); });
}); });
console.log('GetEntries success'); console.log('GetEntries success');
...@@ -4578,7 +4578,7 @@ try { ...@@ -4578,7 +4578,7 @@ try {
console.log('putBatch success'); console.log('putBatch success');
const query = new distributedData.Query(); const query = new distributedData.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getEntries(query).then((entrys) => { kvStore.getEntries(query).then((entries) => {
console.log('getEntries success'); console.log('getEntries success');
}).catch((err) => { }).catch((err) => {
console.log('getEntries fail ' + JSON.stringify(err)); console.log('getEntries fail ' + JSON.stringify(err));
...@@ -4633,10 +4633,10 @@ try { ...@@ -4633,10 +4633,10 @@ try {
var query = new distributedData.Query(); var query = new distributedData.Query();
query.deviceId('localDeviceId'); query.deviceId('localDeviceId');
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getEntries('localDeviceId', query, function (err,entrys) { kvStore.getEntries('localDeviceId', query, function (err,entries) {
console.log('getEntries success'); console.log('getEntries success');
console.log('entrys.length: ' + entrys.length); console.log('entries.length: ' + entries.length);
console.log('entrys[0]: ' + JSON.stringify(entrys[0])); console.log('entries[0]: ' + JSON.stringify(entries[0]));
}) })
}); });
console.log('GetEntries success'); console.log('GetEntries success');
...@@ -4691,7 +4691,7 @@ try { ...@@ -4691,7 +4691,7 @@ try {
var query = new distributedData.Query(); var query = new distributedData.Query();
query.deviceId('localDeviceId'); query.deviceId('localDeviceId');
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getEntries('localDeviceId', query).then((entrys) => { kvStore.getEntries('localDeviceId', query).then((entries) => {
console.log('getEntries success'); console.log('getEntries success');
}).catch((err) => { }).catch((err) => {
console.log('getEntries fail ' + JSON.stringify(err)); console.log('getEntries fail ' + JSON.stringify(err));
......
...@@ -14,21 +14,21 @@ import document from '@ohos.document'; ...@@ -14,21 +14,21 @@ import document from '@ohos.document';
choose(types? : string[]): Promise&lt;string&gt; choose(types? : string[]): Promise&lt;string&gt;
Chooses a file of the specified type using the file manager. This API uses a promise to return the result. Chooses files of the specified types using the file manager. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.UserFileService **System capability**: SystemCapability.FileManagement.UserFileService
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------------- | | ------ | ------ | ---- | ---------------------------- |
| types | string[] | No | Type of the file to choose.| | types | string[] | No | Types of the files to choose. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | -------------- | | --------------------- | -------------- |
| Promise&lt;string&gt; | Promise used to return the result. An error code is returned.| | Promise&lt;string&gt; | Promise used to return the result. An error code is returned.|
**Example** **Example**
...@@ -46,9 +46,9 @@ Chooses a file using the file manager. This API uses an asynchronous callback to ...@@ -46,9 +46,9 @@ Chooses a file using the file manager. This API uses an asynchronous callback to
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- | | -------- | --------------------------- | ---- | ---------------------------- |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result. An error code is returned.| | callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result. An error code is returned.|
**Example** **Example**
...@@ -62,16 +62,16 @@ Chooses a file using the file manager. This API uses an asynchronous callback to ...@@ -62,16 +62,16 @@ Chooses a file using the file manager. This API uses an asynchronous callback to
choose(types:string[], callback:AsyncCallback&lt;string&gt;): void choose(types:string[], callback:AsyncCallback&lt;string&gt;): void
Chooses a file using the file manager. This API uses an asynchronous callback to return the result. Chooses files using the file manager. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileService **System capability**: SystemCapability.FileManagement.UserFileService
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- | | -------- | --------------------------- | ---- | ---------------------------- |
| types | string[] | No | Type of the file to choose.| | types | string[] | No | Types of the files to choose.|
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result. An error code is returned.| | callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result. An error code is returned.|
**Example** **Example**
...@@ -93,16 +93,16 @@ Opens a file. This API uses a promise to return the result. ...@@ -93,16 +93,16 @@ Opens a file. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ---- | ------ | ---- | ---------------------------- | | ---- | ------ | ---- | ---------------------------- |
| uri | string | Yes | URI of the file to open.| | uri | string | Yes | URI of the file to open.|
| type | string | Yes | Type of the file to open.| | type | string | Yes | Type of the file to open.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ------------ | | --------------------- | ------------ |
| Promise&lt;void&gt; | Promise used to return the result. An error code is returned.| | Promise&lt;void&gt; | Promise used to return the result. An error code is returned.|
**Example** **Example**
...@@ -122,11 +122,11 @@ Opens a file. This API uses an asynchronous callback to return the result. ...@@ -122,11 +122,11 @@ Opens a file. This API uses an asynchronous callback to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- | | -------- | --------------------------- | ---- | ---------------------------- |
| uri | string | Yes | URI of the file to open.| | uri | string | Yes | URI of the file to open.|
| type | string | Yes | Type of the file to open.| | type | string | Yes | Type of the file to open.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. An error code is returned. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. An error code is returned. |
**Example** **Example**
......
...@@ -16,6 +16,7 @@ import fileio from '@ohos.fileio'; ...@@ -16,6 +16,7 @@ import fileio from '@ohos.fileio';
## Guidelines ## Guidelines
Before using the APIs provided by this module to perform operations on files or directories, obtain the path of the application sandbox as follows: Before using the APIs provided by this module to perform operations on files or directories, obtain the path of the application sandbox as follows:
```js ```js
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context = featureAbility.getContext();
...@@ -353,58 +354,11 @@ Synchronously closes a file. ...@@ -353,58 +354,11 @@ Synchronously closes a file.
**Example** **Example**
```js ```js
let fd = fileio.openSync(path);
fileio.closeSync(fd); fileio.closeSync(fd);
``` ```
## fileio.close<sup>7+</sup>
close(): Promise&lt;void&gt;
Closes the stream. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Return value**
| Type | Description |
| ------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```js
fileio.close().then(function(){
console.info("File stream closed");
}).catch(function(err){
console.info("Failed to close the file stream. Error:"+ err);
});
```
## fileio.close<sup>7+</sup>
close(callback: AsyncCallback&lt;void&gt;): void
Closes the stream. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ------------- |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the stream is closed asynchronously.|
**Example**
```js
fileio.close(function(err){
// Do something.
});
```
## fileio.copyFile ## fileio.copyFile
copyFile(src:string | number, dest:string | number, mode?:number):Promise&lt;void&gt; copyFile(src:string | number, dest:string | number, mode?:number):Promise&lt;void&gt;
...@@ -430,6 +384,8 @@ Copies a file. This API uses a promise to return the result. ...@@ -430,6 +384,8 @@ Copies a file. This API uses a promise to return the result.
**Example** **Example**
```js ```js
let src = path;
let dest = src + 'tgt';
fileio.copyFile(src, dest).then(function(){ fileio.copyFile(src, dest).then(function(){
console.info("File copied"); console.info("File copied");
}).catch(function(err){ }).catch(function(err){
...@@ -458,6 +414,8 @@ Copies a file. This API uses an asynchronous callback to return the result. ...@@ -458,6 +414,8 @@ Copies a file. This API uses an asynchronous callback to return the result.
**Example** **Example**
```js ```js
let src = path;
let dest = src + 'tgt';
fileio.copyFile(src, dest, function (err) { fileio.copyFile(src, dest, function (err) {
// Do something. // Do something.
}); });
...@@ -483,6 +441,8 @@ Synchronously copies a file. ...@@ -483,6 +441,8 @@ Synchronously copies a file.
**Example** **Example**
```js ```js
let src = path;
let dest = src + 'tgt';
fileio.copyFileSync(src, dest); fileio.copyFileSync(src, dest);
``` ```
...@@ -957,7 +917,7 @@ Writes data into a file. This API uses a promise to return the result. ...@@ -957,7 +917,7 @@ Writes data into a file. This API uses a promise to return the result.
```js ```js
let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); let fd = fileio.openSync(path, 0o100 | 0o2, 0o666);
fileio.write(fd, "hello, world").then(function(number){ fileio.write(fd, "hello, world").then(function(number){
console.info("Data written to file and size is:"+ number); console.info("Data written to the file. Size is:"+ number);
}).catch(function(err){ }).catch(function(err){
console.info("Failed to write data to the file. Error:"+ err); console.info("Failed to write data to the file. Error:"+ err);
}); });
...@@ -992,7 +952,7 @@ Writes data into a file. This API uses an asynchronous callback to return the re ...@@ -992,7 +952,7 @@ Writes data into a file. This API uses an asynchronous callback to return the re
let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); let fd = fileio.openSync(path, 0o100 | 0o2, 0o666);
fileio.write(fd, "hello, world", function (err, bytesWritten) { fileio.write(fd, "hello, world", function (err, bytesWritten) {
if (bytesWritten) { if (bytesWritten) {
console.info("Data written to file and size is:"+ bytesWritten); console.info("Data written to the file. Size is:"+ bytesWritten);
} }
}); });
``` ```
...@@ -1059,7 +1019,7 @@ Calculates the hash value of a file. This API uses a promise to return the resul ...@@ -1059,7 +1019,7 @@ Calculates the hash value of a file. This API uses a promise to return the resul
```js ```js
fileio.hash(path, "sha256").then(function(str){ fileio.hash(path, "sha256").then(function(str){
console.info("Calculated file hash:"+ str); console.info("Calculated file hash:"+ str);
}).catch(function(error){ }).catch(function(err){
console.info("Failed to calculate the file hash. Error:"+ err); console.info("Failed to calculate the file hash. Error:"+ err);
}); });
``` ```
...@@ -1116,7 +1076,7 @@ Changes file permissions. This API uses a promise to return the result. ...@@ -1116,7 +1076,7 @@ Changes file permissions. This API uses a promise to return the result.
**Example** **Example**
```js ```js
fileio.chmod(path, mode).then(function() { fileio.chmod(path, 0o700).then(function() {
console.info("File permissions changed"); console.info("File permissions changed");
}).catch(function(err){ }).catch(function(err){
console.info("Failed to change file permissions. Error:"+ err); console.info("Failed to change file permissions. Error:"+ err);
...@@ -1143,7 +1103,7 @@ Changes file permissions. This API uses an asynchronous callback to return the r ...@@ -1143,7 +1103,7 @@ Changes file permissions. This API uses an asynchronous callback to return the r
**Example** **Example**
```js ```js
fileio.chmod(path, mode, function (err) { fileio.chmod(path, 0o700, function (err) {
// Do something. // Do something.
}); });
``` ```
...@@ -1167,7 +1127,7 @@ Synchronously changes file permissions. ...@@ -1167,7 +1127,7 @@ Synchronously changes file permissions.
**Example** **Example**
```js ```js
fileio.chmodSync(path, mode); fileio.chmodSync(path, 0o700);
``` ```
...@@ -1194,10 +1154,11 @@ Obtains file information based on the file descriptor. This API uses a promise t ...@@ -1194,10 +1154,11 @@ Obtains file information based on the file descriptor. This API uses a promise t
**Example** **Example**
```js ```js
let fd = fileio.openSync(path);
fileio.fstat(fd).then(function(stat){ fileio.fstat(fd).then(function(stat){
console.info("File information obtained:"+ JSON.stringify(stat)); console.info("Obtained file info:"+ JSON.stringify(stat));
}).catch(function(err){ }).catch(function(err){
console.info("Failed to obtain file information. Error:"+ err); console.info("Failed to obtain file info. Error:"+ err);
}); });
``` ```
...@@ -1307,7 +1268,9 @@ Truncates a file based on the file descriptor. This API uses an asynchronous cal ...@@ -1307,7 +1268,9 @@ Truncates a file based on the file descriptor. This API uses an asynchronous cal
**Example** **Example**
```js ```js
fileio.ftruncate(fd, len, function(err){ let fd = fileio.openSync(path);
let len = 5;
fileio.ftruncate(fd, 5, function(err){
// Do something. // Do something.
}); });
``` ```
...@@ -1331,6 +1294,8 @@ Synchronously truncates a file based on the file descriptor. ...@@ -1331,6 +1294,8 @@ Synchronously truncates a file based on the file descriptor.
**Example** **Example**
```js ```js
let fd = fileio.openSync(path);
let len = 5;
fileio.ftruncateSync(fd, len); fileio.ftruncateSync(fd, len);
``` ```
...@@ -1347,7 +1312,7 @@ Truncates a file based on the file path. This API uses a promise to return the r ...@@ -1347,7 +1312,7 @@ Truncates a file based on the file path. This API uses a promise to return the r
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------------------- | | ------ | ------ | ---- | -------------------------------- |
| path | string | Yes | Application sandbox path of the file to truncate. | | path | string | Yes | Application sandbox path of the file to truncate.|
| len | number | No | File length, in bytes, after truncation.| | len | number | No | File length, in bytes, after truncation.|
**Return value** **Return value**
...@@ -1359,6 +1324,7 @@ Truncates a file based on the file path. This API uses a promise to return the r ...@@ -1359,6 +1324,7 @@ Truncates a file based on the file path. This API uses a promise to return the r
**Example** **Example**
```js ```js
let len = 5;
fileio.truncate(path, len).then(function(){ fileio.truncate(path, len).then(function(){
console.info("File truncated"); console.info("File truncated");
}).catch(function(err){ }).catch(function(err){
...@@ -1386,6 +1352,7 @@ Truncates a file based on the file path. This API uses an asynchronous callback ...@@ -1386,6 +1352,7 @@ Truncates a file based on the file path. This API uses an asynchronous callback
**Example** **Example**
```js ```js
let len = 5;
fileio.truncate(path, len, function(err){ fileio.truncate(path, len, function(err){
// Do something. // Do something.
}); });
...@@ -1410,6 +1377,7 @@ Synchronously truncates a file based on the file path. ...@@ -1410,6 +1377,7 @@ Synchronously truncates a file based on the file path.
**Example** **Example**
```js ```js
let len = 5;
fileio.truncateSync(path, len); fileio.truncateSync(path, len);
``` ```
...@@ -1443,9 +1411,9 @@ Reads the text content of a file. This API uses a promise to return the result. ...@@ -1443,9 +1411,9 @@ Reads the text content of a file. This API uses a promise to return the result.
```js ```js
fileio.readText(path).then(function(str) { fileio.readText(path).then(function(str) {
console.info("Read file text:"+ str); console.info("Read text:"+ str);
}).catch(function(err){ }).catch(function(err){
console.info("Failed to read text. Error:"+ err); console.info("Failed to read the text. Error:"+ err);
}); });
``` ```
...@@ -1467,13 +1435,13 @@ Reads the text content of a file. This API uses an asynchronous callback to retu ...@@ -1467,13 +1435,13 @@ Reads the text content of a file. This API uses an asynchronous callback to retu
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ------------------------------------------------------------ | | -------- | --------------------------- | ---- | ------------------------------------------------------------ |
| filePath | string | Yes | Application sandbox path of the file to read. | | filePath | string | Yes | Application sandbox path of the file to read. |
| options | Object | No | The options are as follows:<br>-&nbsp;**position** (number): position of the data to read in the file. By default, data is read from the current position.<br>-&nbsp;**length** (number): length of the data to read. The default value is the buffer length minus the offset.<br>- &nbsp;**encoding**: format of the string to be encoded. The default value is &nbsp;**utf-8**, which is the only value supported.| | options | Object | Yes | The options are as follows:<br>-&nbsp;**position** (number): position of the data to read in the file. By default, data is read from the current position.<br>-&nbsp;**length** (number): length of the data to read. The default value is the buffer length minus the offset.<br>- &nbsp;**encoding**: format of the string to be encoded. The default value is &nbsp;**utf-8**, which is the only value supported.|
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the content read. | | callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the content read. |
**Example** **Example**
```js ```js
fileio.readText(path, function(err, str){ fileio.readText(path, { position: 1, encoding: 'UTF-8' }, function(err, str){
// Do something. // Do something.
}); });
``` ```
...@@ -1537,7 +1505,7 @@ Obtains link information. This API uses a promise to return the result. ...@@ -1537,7 +1505,7 @@ Obtains link information. This API uses a promise to return the result.
fileio.lstat(path).then(function(stat){ fileio.lstat(path).then(function(stat){
console.info("Got link info:"+ JSON.stringify(stat)); console.info("Got link info:"+ JSON.stringify(stat));
}).catch(function(err){ }).catch(function(err){
console.info("Failed to obtain the link status. Error:"+ err); console.info("Failed to obtain link info. Error:"+ err);
}); });
``` ```
...@@ -1593,76 +1561,6 @@ Synchronously obtains the link information. ...@@ -1593,76 +1561,6 @@ Synchronously obtains the link information.
``` ```
## fileio.read<sup>7+</sup>
read(buffer: ArrayBuffer, options?: {
position?: number;
offset?: number;
length?: number;
}): Promise&lt;ReadOut&gt;
Reads data from a file. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ----------- | ---- | ------------------------------------------------------------ |
| buffer | ArrayBuffer | Yes | Buffer used to store the file data read. |
| options | Object | No | The options are as follows:<br>-&nbsp;**offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.<br>-&nbsp;**length** (number): length of the data to read. The default value is the buffer length minus the offset.<br>Constraints: offset + length <= Buffer size|
**Return value**
| Type | Description |
| ---------------------------------- | ------ |
| Promise&lt;[ReadOut](#readout)&gt; | Promise used to return the data read.|
**Example**
```js
fileio.read(new ArrayBuffer(4096)).then(function(readout){
console.info("Read file data");
console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer)));
}).catch(function(err){
console.info("Failed to read file data. Error:"+ err);
});
```
## fileio.read<sup>7+</sup>
read(buffer: ArrayBuffer, options: {
position?: number;
offset?: number;
length?: number;
}, callback: AsyncCallback&lt;ReadOut&gt;): void
Reads data from a file. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| buffer | ArrayBuffer | Yes | Buffer used to store the file data read. |
| options | Object | No | The options are as follows:<br>-&nbsp;**offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.<br>-&nbsp;**length** (number): length of the data to read. The default value is the buffer length minus the offset.<br>Constraints: offset + length <= Buffer size|
| callback | AsyncCallback&lt;[ReadOut](#readout)&gt; | Yes | Callback invoked when the data is read asynchronously from the file. |
**Example**
```js
let buf = new ArrayBuffer(4096);
fileio.read(buf, function (err, readOut) {
if (readOut) {
console.info("Read file data");
console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer)));
}
});
```
## fileio.rename<sup>7+</sup> ## fileio.rename<sup>7+</sup>
rename(oldPath: string, newPath: string): Promise&lt;void&gt; rename(oldPath: string, newPath: string): Promise&lt;void&gt;
...@@ -1687,6 +1585,8 @@ Renames a file. This API uses a promise to return the result. ...@@ -1687,6 +1585,8 @@ Renames a file. This API uses a promise to return the result.
**Example** **Example**
```js ```js
let oldPath = path;
let newPath = oldPath + '123';
fileio.rename(oldPath, newPath).then(function() { fileio.rename(oldPath, newPath).then(function() {
console.info("File renamed"); console.info("File renamed");
}).catch(function(err){ }).catch(function(err){
...@@ -1714,6 +1614,8 @@ Renames a file. This API uses an asynchronous callback to return the result. ...@@ -1714,6 +1614,8 @@ Renames a file. This API uses an asynchronous callback to return the result.
**Example** **Example**
```js ```js
let oldPath = path;
let newPath = oldPath + '123';
fileio.rename(oldPath, newPath, function(err){ fileio.rename(oldPath, newPath, function(err){
}); });
``` ```
...@@ -1737,6 +1639,8 @@ Synchronously renames a file. ...@@ -1737,6 +1639,8 @@ Synchronously renames a file.
**Example** **Example**
```js ```js
let oldPath = path;
let newPath = oldPath + '123';
fileio.renameSync(oldPath, newPath); fileio.renameSync(oldPath, newPath);
``` ```
...@@ -1764,6 +1668,7 @@ Flushes data of a file to disk. This API uses a promise to return the result. ...@@ -1764,6 +1668,7 @@ Flushes data of a file to disk. This API uses a promise to return the result.
**Example** **Example**
```js ```js
let fd = fileio.openSync(path);
fileio.fsync(fd).then(function(){ fileio.fsync(fd).then(function(){
console.info("Data flushed"); console.info("Data flushed");
}).catch(function(err){ }).catch(function(err){
...@@ -1790,6 +1695,7 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return ...@@ -1790,6 +1695,7 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return
**Example** **Example**
```js ```js
let fd = fileio.openSync(path);
fileio.fsync(fd, function(err){ fileio.fsync(fd, function(err){
// Do something. // Do something.
}); });
...@@ -1813,6 +1719,7 @@ Flushes data of a file to disk in synchronous mode. ...@@ -1813,6 +1719,7 @@ Flushes data of a file to disk in synchronous mode.
**Example** **Example**
```js ```js
let fd = fileio.openSync(path);
fileio.fsyncSync(fd); fileio.fsyncSync(fd);
``` ```
...@@ -1840,6 +1747,7 @@ Flushes data of a file to disk. This API uses a promise to return the result. ** ...@@ -1840,6 +1747,7 @@ Flushes data of a file to disk. This API uses a promise to return the result. **
**Example** **Example**
```js ```js
let fd = fileio.openSync(path);
fileio.fdatasync(fd).then(function(err) { fileio.fdatasync(fd).then(function(err) {
console.info("Data flushed"); console.info("Data flushed");
}).catch(function(err){ }).catch(function(err){
...@@ -1866,6 +1774,7 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return ...@@ -1866,6 +1774,7 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return
**Example** **Example**
```js ```js
let fd = fileio.openSync(path);
fileio.fdatasync (fd, function (err) { fileio.fdatasync (fd, function (err) {
// Do something. // Do something.
}); });
...@@ -1889,6 +1798,7 @@ Synchronizes data in a file in synchronous mode. ...@@ -1889,6 +1798,7 @@ Synchronizes data in a file in synchronous mode.
**Example** **Example**
```js ```js
let fd = fileio.openSync(path);
let stat = fileio.fdatasyncSync(fd); let stat = fileio.fdatasyncSync(fd);
``` ```
...@@ -1917,6 +1827,8 @@ Creates a symbolic link based on the file path. This API uses a promise to retur ...@@ -1917,6 +1827,8 @@ Creates a symbolic link based on the file path. This API uses a promise to retur
**Example** **Example**
```js ```js
let target = path;
let srcPath = target + 'aaa';
fileio.symlink(target, srcPath).then(function() { fileio.symlink(target, srcPath).then(function() {
console.info("Symbolic link created"); console.info("Symbolic link created");
}).catch(function(err){ }).catch(function(err){
...@@ -1944,6 +1856,8 @@ Creates a symbolic link based on the file path. This API uses an asynchronous ca ...@@ -1944,6 +1856,8 @@ Creates a symbolic link based on the file path. This API uses an asynchronous ca
**Example** **Example**
```js ```js
let target = path;
let srcPath = target + 'aaa';
fileio.symlink(target, srcPath, function (err) { fileio.symlink(target, srcPath, function (err) {
// Do something. // Do something.
}); });
...@@ -1968,6 +1882,8 @@ Synchronously creates a symbolic link based on a specified path. ...@@ -1968,6 +1882,8 @@ Synchronously creates a symbolic link based on a specified path.
**Example** **Example**
```js ```js
let target = path;
let srcPath = target + 'aaa';
fileio.symlinkSync(target, srcPath); fileio.symlinkSync(target, srcPath);
``` ```
...@@ -2083,7 +1999,7 @@ Creates a temporary directory. This API uses a promise to return the result. ...@@ -2083,7 +1999,7 @@ Creates a temporary directory. This API uses a promise to return the result.
fileio.mkdtemp(path + "XXXX").then(function(path){ fileio.mkdtemp(path + "XXXX").then(function(path){
console.info("Temporary directory created:"+ path); console.info("Temporary directory created:"+ path);
}).catch(function(err){ }).catch(function(err){
console.info("Failed to create a temporary directory. Error:"+ err); console.info("Failed to create the temporary directory. Error:"+ err);
}); });
``` ```
...@@ -2163,6 +2079,8 @@ Changes file permissions based on the file descriptor. This API uses a promise t ...@@ -2163,6 +2079,8 @@ Changes file permissions based on the file descriptor. This API uses a promise t
**Example** **Example**
```js ```js
let fd = fileio.openSync(path);
let mode = 0o700;
fileio.fchmod(fd, mode).then(function() { fileio.fchmod(fd, mode).then(function() {
console.info("File permissions changed"); console.info("File permissions changed");
}).catch(function(err){ }).catch(function(err){
...@@ -2190,6 +2108,8 @@ Changes file permissions based on the file descriptor. This API uses an asynchro ...@@ -2190,6 +2108,8 @@ Changes file permissions based on the file descriptor. This API uses an asynchro
**Example** **Example**
```js ```js
let fd = fileio.openSync(path);
let mode = 0o700;
fileio.fchmod(fd, mode, function (err) { fileio.fchmod(fd, mode, function (err) {
// Do something. // Do something.
}); });
...@@ -2214,6 +2134,8 @@ Synchronously changes the file permissions based on the file descriptor. ...@@ -2214,6 +2134,8 @@ Synchronously changes the file permissions based on the file descriptor.
**Example** **Example**
```js ```js
let fd = fileio.openSync(path);
let mode = 0o700;
fileio.fchmodSync(fd, mode); fileio.fchmodSync(fd, mode);
``` ```
...@@ -2416,6 +2338,7 @@ Changes the file owner based on the file descriptor. This API uses a promise to ...@@ -2416,6 +2338,7 @@ Changes the file owner based on the file descriptor. This API uses a promise to
**Example** **Example**
```js ```js
let fd = fileio.openSync(path);
let stat = fileio.statSync(path); let stat = fileio.statSync(path);
fileio.fchown(fd, stat.uid, stat.gid).then(function() { fileio.fchown(fd, stat.uid, stat.gid).then(function() {
console.info("File owner changed"); console.info("File owner changed");
...@@ -2445,6 +2368,7 @@ Changes the file owner based on the file descriptor. This API uses an asynchrono ...@@ -2445,6 +2368,7 @@ Changes the file owner based on the file descriptor. This API uses an asynchrono
**Example** **Example**
```js ```js
let fd = fileio.openSync(path);
let stat = fileio.statSync(path); let stat = fileio.statSync(path);
fileio.fchown(fd, stat.uid, stat.gid, function (err){ fileio.fchown(fd, stat.uid, stat.gid, function (err){
// Do something. // Do something.
...@@ -2471,6 +2395,7 @@ Synchronously changes the file owner based on the file descriptor. ...@@ -2471,6 +2395,7 @@ Synchronously changes the file owner based on the file descriptor.
**Example** **Example**
```js ```js
let fd = fileio.openSync(path);
let stat = fileio.statSync(path); let stat = fileio.statSync(path);
fileio.fchownSync(fd, stat.uid, stat.gid); fileio.fchownSync(fd, stat.uid, stat.gid);
``` ```
...@@ -2854,7 +2779,7 @@ Closes the stream. This API uses a promise to return the result. ...@@ -2854,7 +2779,7 @@ Closes the stream. This API uses a promise to return the result.
```js ```js
let ss= fileio.createStreamSync(path, "r+"); let ss= fileio.createStreamSync(path, "r+");
ss.close().then(function(){ ss.close().then(function(){
console.info("Stream closed"); console.info("File stream closed");
}).catch(function(err){ }).catch(function(err){
console.info("Failed to close the file stream. Error:"+ err); console.info("Failed to close the file stream. Error:"+ err);
}); });
...@@ -3102,7 +3027,7 @@ Reads data from the stream. This API uses a promise to return the result. ...@@ -3102,7 +3027,7 @@ Reads data from the stream. This API uses a promise to return the result.
```js ```js
let ss = fileio.createStreamSync(path, "r+"); let ss = fileio.createStreamSync(path, "r+");
ss.read(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}).then(function (readout){ ss.read(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}).then(function (readOut){
console.info("Read data successfully"); console.info("Read data successfully");
console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer)));
}).catch(function(err){ }).catch(function(err){
...@@ -3179,7 +3104,7 @@ Synchronously reads data from the stream. ...@@ -3179,7 +3104,7 @@ Synchronously reads data from the stream.
## Dir ## Dir
Manages directories. Before calling a method of the **Dir** class, use the [opendir()](#fileioopendir) method synchronously or asynchronously to create a **Dir** instance. Manages directories. Before calling a method of the **Dir** class, use the **opendir()** method synchronously or asynchronously to create a **Dir** instance.
### read ### read
...@@ -3449,7 +3374,7 @@ Checks whether a directory entry is a socket. ...@@ -3449,7 +3374,7 @@ Checks whether a directory entry is a socket.
**Example** **Example**
```js ```js
let dir = fileio.opendirSync(dpath); let dir = fileio.opendirSync(path);
let isSocket = dir.readSync().isSocket(); let isSocket = dir.readSync().isSocket();
``` ```
......
...@@ -287,7 +287,7 @@ Defines the information about an input device. ...@@ -287,7 +287,7 @@ Defines the information about an input device.
| Name | Type | Description | | Name | Type | Description |
| -------- | ------------------------- | --------------------------------- | | -------- | ------------------------- | --------------------------------- |
| type | [ChangeType](#changetype) | Device change type, which indicates whether an input device is inserted or removed. | | type | [ChangedType](#changedtype) | Device change type, which indicates whether an input device is inserted or removed. |
| deviceId | number | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| | deviceId | number | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.|
## InputDeviceData ## InputDeviceData
......
...@@ -20,7 +20,7 @@ Obtains an **AccountManager** instance. ...@@ -20,7 +20,7 @@ Obtains an **AccountManager** instance.
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| --------------------------------- | ------------------------ | | --------------------------------- | ------------------------ |
| [AccountManager](#accountmanager) | Obtains an **AccountManager** instance.| | [AccountManager](#accountmanager) | Obtains an **AccountManager** instance.|
...@@ -92,7 +92,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -92,7 +92,7 @@ This is a system API and cannot be called by third-party applications.
| ------- | ------ | ---- | -------------------- | | ------- | ------ | ---- | -------------------- |
| localId | number | Yes | ID of the OS account to activate.| | localId | number | Yes | ID of the OS account to activate.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :---------------------------------- | | :------------------ | :---------------------------------- |
...@@ -141,7 +141,7 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re ...@@ -141,7 +141,7 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------- | :----------------------------------------------------------- | | :--------------------- | :----------------------------------------------------------- |
...@@ -202,7 +202,7 @@ Checks whether an OS account is activated. This API uses a promise to return the ...@@ -202,7 +202,7 @@ Checks whether an OS account is activated. This API uses a promise to return the
| ------- | ------ | ---- | ------------ | | ------- | ------ | ---- | ------------ |
| localId | number | Yes | ID of the target OS account.| | localId | number | Yes | ID of the target OS account.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------- | :----------------------------------------------------------- | | :--------------------- | :----------------------------------------------------------- |
...@@ -266,7 +266,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u ...@@ -266,7 +266,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u
| localId | number | Yes | ID of the target OS account. | | localId | number | Yes | ID of the target OS account. |
| constraint | string | Yes | [Constraint](#constraints) specified.| | constraint | string | Yes | [Constraint](#constraints) specified.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------- | :----------------------------------------------------------- | | :--------------------- | :----------------------------------------------------------- |
...@@ -316,7 +316,7 @@ Checks whether this OS account is a test account. This API uses a promise to ret ...@@ -316,7 +316,7 @@ Checks whether this OS account is a test account. This API uses a promise to ret
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------- | :----------------------------------------------------------- | | :--------------------- | :----------------------------------------------------------- |
...@@ -400,7 +400,7 @@ Checks whether an OS account has been verified. This API uses a promise to retur ...@@ -400,7 +400,7 @@ Checks whether an OS account has been verified. This API uses a promise to retur
| ------- | ------ | ---- | ------------------ | | ------- | ------ | ---- | ------------------ |
| localId | number | No | ID of the target OS account.| | localId | number | No | ID of the target OS account.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------- | :----------------------------------------------------------- | | :--------------------- | :----------------------------------------------------------- |
...@@ -467,7 +467,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -467,7 +467,7 @@ This is a system API and cannot be called by third-party applications.
| ------- | ------ | ---- | -------------------- | | ------- | ------ | ---- | -------------------- |
| localId | number | Yes | ID of the OS account to remove.| | localId | number | Yes | ID of the OS account to remove.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :---------------------------------- | | :------------------ | :---------------------------------- |
...@@ -540,7 +540,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -540,7 +540,7 @@ This is a system API and cannot be called by third-party applications.
| constraints | Array&lt;string&gt; | Yes | List of [constraints](#constraints) to set or remove.| | constraints | Array&lt;string&gt; | Yes | List of [constraints](#constraints) to set or remove.|
| enable | boolean | Yes | Set or remove constraints. The value **true** means to set constraints, and **false** means to remove constraints. | | enable | boolean | Yes | Set or remove constraints. The value **true** means to set constraints, and **false** means to remove constraints. |
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :---------------------------------- | | :------------------ | :---------------------------------- |
...@@ -608,7 +608,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -608,7 +608,7 @@ This is a system API and cannot be called by third-party applications.
| localId | number | Yes | ID of the target OS account.| | localId | number | Yes | ID of the target OS account.|
| localName | string | Yes | Account name to set. | | localName | string | Yes | Account name to set. |
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :---------------------------------- | | :------------------ | :---------------------------------- |
...@@ -663,7 +663,7 @@ Obtains the number of OS accounts created. This API uses a promise to return the ...@@ -663,7 +663,7 @@ Obtains the number of OS accounts created. This API uses a promise to return the
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -712,7 +712,7 @@ Obtains the ID of the OS account to which the current process belongs. This API ...@@ -712,7 +712,7 @@ Obtains the ID of the OS account to which the current process belongs. This API
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -769,7 +769,7 @@ Obtains the OS account ID based on the process UID. This API uses a promise to r ...@@ -769,7 +769,7 @@ Obtains the OS account ID based on the process UID. This API uses a promise to r
| ------ | ------ | ---- | --------- | | ------ | ------ | ---- | --------- |
| uid | number | Yes | Process UID.| | uid | number | Yes | Process UID.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -831,7 +831,7 @@ Obtains the OS account ID based on domain account information. This API uses a p ...@@ -831,7 +831,7 @@ Obtains the OS account ID based on domain account information. This API uses a p
| ---------- | --------------------------------------- | ---- | ------------ | | ---------- | --------------------------------------- | ---- | ------------ |
| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information.| | domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -885,7 +885,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -885,7 +885,7 @@ This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -946,7 +946,7 @@ Obtains all constraints enabled for an OS account. This API uses a promise to re ...@@ -946,7 +946,7 @@ Obtains all constraints enabled for an OS account. This API uses a promise to re
| ------- | ------ | ---- | ------------ | | ------- | ------ | ---- | ------------ |
| localId | number | Yes | ID of the target OS account.| | localId | number | Yes | ID of the target OS account.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------- | :----------------------------------------------------------- | | :--------------------------------- | :----------------------------------------------------------- |
...@@ -1004,7 +1004,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1004,7 +1004,7 @@ This is a system API and cannot be called by third-party applications.
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :---------------------------------------------------------- | :----------------------------------------------------------- | | :---------------------------------------------------------- | :----------------------------------------------------------- |
...@@ -1056,7 +1056,7 @@ Obtains information about all activated OS accounts. This API uses a promise to ...@@ -1056,7 +1056,7 @@ Obtains information about all activated OS accounts. This API uses a promise to
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------- | :----------------------------------------------------------- | | :--------------------------------- | :----------------------------------------------------------- |
...@@ -1122,7 +1122,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1122,7 +1122,7 @@ This is a system API and cannot be called by third-party applications.
| localName | string | Yes | Name of the OS account to create.| | localName | string | Yes | Name of the OS account to create.|
| type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.| | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------------------- | :----------------------------------------------------------- | | :--------------------------------------------- | :----------------------------------------------------------- |
...@@ -1189,7 +1189,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1189,7 +1189,7 @@ This is a system API and cannot be called by third-party applications.
| type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.| | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.|
| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. | | domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. |
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------------------- | :----------------------------------------------------------- | | :--------------------------------------------- | :----------------------------------------------------------- |
...@@ -1243,7 +1243,7 @@ Obtains information about the OS account to which the current process belongs. T ...@@ -1243,7 +1243,7 @@ Obtains information about the OS account to which the current process belongs. T
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------------------- | :----------------------------------------------------------- | | :--------------------------------------------- | :----------------------------------------------------------- |
...@@ -1308,7 +1308,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1308,7 +1308,7 @@ This is a system API and cannot be called by third-party applications.
| ------- | ------ | ---- | -------------------- | | ------- | ------ | ---- | -------------------- |
| localId | number | Yes | ID of the target OS account.| | localId | number | Yes | ID of the target OS account.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------------------- | :----------------------------------------------------------- | | :--------------------------------------------- | :----------------------------------------------------------- |
...@@ -1358,7 +1358,7 @@ Obtains the type of the OS account to which the current process belongs. This AP ...@@ -1358,7 +1358,7 @@ Obtains the type of the OS account to which the current process belongs. This AP
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------------------- | :----------------------------------------------------------- | | :--------------------------------------------- | :----------------------------------------------------------- |
...@@ -1411,7 +1411,7 @@ Obtains the ID of this distributed virtual device. This API uses a promise to re ...@@ -1411,7 +1411,7 @@ Obtains the ID of this distributed virtual device. This API uses a promise to re
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -1476,7 +1476,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1476,7 +1476,7 @@ This is a system API and cannot be called by third-party applications.
| ------- | ------ | ---- | ------------ | | ------- | ------ | ---- | ------------ |
| localId | number | Yes | ID of the target OS account.| | localId | number | Yes | ID of the target OS account.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -1547,7 +1547,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1547,7 +1547,7 @@ This is a system API and cannot be called by third-party applications.
| localId | number | Yes | ID of the target OS account.| | localId | number | Yes | ID of the target OS account.|
| photo | string | Yes | Profile photo information. | | photo | string | Yes | Profile photo information. |
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :---------------------------------- | | :------------------ | :---------------------------------- |
...@@ -1609,7 +1609,7 @@ Obtains the OS account ID based on the SN. This API uses a promise to return the ...@@ -1609,7 +1609,7 @@ Obtains the OS account ID based on the SN. This API uses a promise to return the
| ------------ | ------ | ---- | ---------- | | ------------ | ------ | ---- | ---------- |
| serialNumber | number | Yes | Account SN.| | serialNumber | number | Yes | Account SN.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -1667,7 +1667,7 @@ Obtains the SN of an OS account based on the account ID. This API uses a promise ...@@ -1667,7 +1667,7 @@ Obtains the SN of an OS account based on the account ID. This API uses a promise
| ------- | ------ | ---- | ------------ | | ------- | ------ | ---- | ------------ |
| localId | number | Yes | ID of the target OS account.| | localId | number | Yes | ID of the target OS account.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -1787,7 +1787,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1787,7 +1787,7 @@ This is a system API and cannot be called by third-party applications.
| ------- | ------ | ---- | ------------ | | ------- | ------ | ---- | ------------ |
| uid | number | Yes | Process UID.| | uid | number | Yes | Process UID.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -1836,7 +1836,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1836,7 +1836,7 @@ This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -1898,7 +1898,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1898,7 +1898,7 @@ This is a system API and cannot be called by third-party applications.
| localId | number | Yes | ID of the target OS account.| | localId | number | Yes | ID of the target OS account.|
| constraint | string | Yes | Name of the [constraint](#constraints) to query.| | constraint | string | Yes | Name of the [constraint](#constraints) to query.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
......
...@@ -1141,7 +1141,7 @@ Obtains the string corresponding to the specified resource name. This API return ...@@ -1141,7 +1141,7 @@ Obtains the string corresponding to the specified resource name. This API return
resourceManager.getStringByNameSync("test"); resourceManager.getStringByNameSync("test");
``` ```
### getBoolean<sup>9+</sup> ### getBoolean<sup>9+</sup>
getBoolean(resId: number): boolean getBoolean(resId: number): boolean
...@@ -1187,7 +1187,7 @@ Obtains the Boolean result corresponding to the specified resource name. This AP ...@@ -1187,7 +1187,7 @@ Obtains the Boolean result corresponding to the specified resource name. This AP
resourceManager.getBooleanByName("boolean_test"); resourceManager.getBooleanByName("boolean_test");
``` ```
### getNumber<sup>9+</sup> ### getNumber<sup>9+</sup>
getNumber(resId: number): number getNumber(resId: number): number
......
...@@ -13,12 +13,15 @@ import securityLabel from '@ohos.securityLabel'; ...@@ -13,12 +13,15 @@ import securityLabel from '@ohos.securityLabel';
## Usage ## Usage
Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the application sandbox. For details, see [getOrCreateLocalDir of the Context module](js-apis-Context.md). Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the application sandbox as follows:
```js ```js
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context = featureAbility.getContext();
let path = context.getFilesDir(); let path = '';
context.getFilesDir().then((data) => {
path = data;
})
``` ```
## securityLabel.setSecurityLabel ## securityLabel.setSecurityLabel
......
...@@ -470,7 +470,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -470,7 +470,7 @@ This is a system API and cannot be called by third-party applications.
| Name | Type | Mandatory| Description| | Name | Type | Mandatory| Description|
| ---------- | ------ | ---- | ---- | | ---------- | ------ | ---- | ---- |
| userId | string | No | User ID.<br>Value:<br>-&nbsp; Set this parameter to the ID of the user to be queried.<br>-&nbsp; If no value is specified, information about the current user is queried.| | userId | number | No | User ID.<br>Value:<br>-&nbsp; Set this parameter to the ID of the user to be queried.<br>-&nbsp; If no value is specified, information about the current user is queried.|
**Return value** **Return value**
...@@ -481,7 +481,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -481,7 +481,7 @@ This is a system API and cannot be called by third-party applications.
**Example** **Example**
```js ```js
let userId = ""; let userId = 1;
storageStatistics.getUserStorageStats(userId).then(function(StorageStats){ storageStatistics.getUserStorageStats(userId).then(function(StorageStats){
console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats)); console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats));
}).catch(function(err){ }).catch(function(err){
...@@ -507,13 +507,13 @@ This is a system API and cannot be called by third-party applications. ...@@ -507,13 +507,13 @@ This is a system API and cannot be called by third-party applications.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | ------------------------------------ | ---- | -------------------------- | | ---------- | ------------------------------------ | ---- | -------------------------- |
| userId | string | No | User ID.<br>Value:<br>-&nbsp; Set this parameter to the ID of the user to be queried.<br>-&nbsp; If no value is specified, information about the current user is queried. | | userId | number | No | User ID.<br>Value:<br>-&nbsp; Set this parameter to the ID of the user to be queried.<br>-&nbsp; If no value is specified, information about the current user is queried. |
| callback | callback:AsyncCallback&lt;[StorageStats](#StorageStats)&gt; | Yes | Callback invoked to return the information obtained.| | callback | callback:AsyncCallback&lt;[StorageStats](#StorageStats)&gt; | Yes | Callback invoked to return the information obtained.|
**Example** **Example**
```js ```js
let userId = ""; let userId = 1;
storageStatistics.getUserStorageStats(userId, function(error, StorageStats){ storageStatistics.getUserStorageStats(userId, function(error, StorageStats){
// Do something. // Do something.
console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats)); console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats));
......
...@@ -3,13 +3,6 @@ ...@@ -3,13 +3,6 @@
## setTimeout ## setTimeout
## Modules to Import
```
import Time from '@ohos.Time';
```
setTimeout(handler[,delay[,…args]]): number setTimeout(handler[,delay[,…args]]): number
Sets a timer for the system to call a function after the timer goes off. Sets a timer for the system to call a function after the timer goes off.
......
# Search # Search
The **\<Search>** component provides an input area for users to search.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Search>** component provides an input area for users to search.
## Required Permissions ## Required Permissions
...@@ -24,7 +24,7 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll ...@@ -24,7 +24,7 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| value | string | No| - | Text input in the search text box. | | value | string | No| - | Text input in the search text box. |
| placeholder | string | No | - | Text displayed when there is no input. | | placeholder | string | No | - | Text displayed when there is no input. |
| icon | string | No| - | Path to the search icon. By default, the system search icon is used. The supported icon formats are svg, jpg, and png. | | icon | string | No| - | Path to the search icon. By default, the system search icon is used. The supported icon formats are .svg, .jpg, and .png. |
| controller | SearchController | No| - | Controller. | | controller | SearchController | No| - | Controller. |
...@@ -36,7 +36,6 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll ...@@ -36,7 +36,6 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll
| placeholderColor | [ResourceColor](../../ui/ts-types.md) | - | Placeholder text color. | | placeholderColor | [ResourceColor](../../ui/ts-types.md) | - | Placeholder text color. |
| placeholderFont | [Font](../../ui/ts-types.md) | - | Placeholder text style. | | placeholderFont | [Font](../../ui/ts-types.md) | - | Placeholder text style. |
| textFont | [Font](../../ui/ts-types.md) | - | Text font for the search text box. | | textFont | [Font](../../ui/ts-types.md) | - | Text font for the search text box. |
| copyOption<sup>9+</sup> | boolean\|[CopyOption](ts-basic-components-text.md) | true | Whether copy and paste is allowed. |
## Events ## Events
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册