提交 248e6194 编写于 作者: D duangavin123

Signed-off-by: duangavin123 <duanxichao@huawei.com>

Merge branch 'master' of https://gitee.com/duangavin123_admin/docs
......@@ -7,6 +7,8 @@ The distributed data objects allow data across devices to be processed like loca
## Available APIs
For details about the APIs related to the distributed data object, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md).
### Creating a Distributed Data Object Instance
Call **createDistributedObject()** to create a distributed data object instance. You can specify the attributes of the instance in **source**.
......@@ -15,7 +17,7 @@ Call **createDistributedObject()** to create a distributed data object instance.
**Table 1** API for creating a distributed data object instance
| Package| API| Description|
| -------- | -------- | -------- |
| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>-&nbsp;**source**: attributes of the **distributedObject** set.<br>-&nbsp;**DistributedObject**: returns the distributed object created.|
| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>- **source**: attributes of the **distributedObject** set.<br>- **DistributedObject**: returns the distributed object created.|
### Generating a Session ID
......@@ -33,16 +35,16 @@ Call **setSessionId()** to set a session ID for a distributed data object. The s
**Table 3** API for setting a session ID
| Class| API| Description|
| -------- | -------- | -------- |
| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.<br>&nbsp;**sessionId**: session ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.<br> **sessionId**: session ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
### Observing Data Changes
Call **on()** to subscribe to data changes of a distributed data object. When the data changes, a callback will be invoked to return the data changes. You can use **off()** to unsubscribe from the data changes.
**Table 4** APIs for observing data changes of a distributed data object
| Class| API| Description|
| Class| API| Description|
| -------- | -------- | -------- |
| DistributedDataObject| on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Subscribes to data changes.|
| DistributedDataObject| on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Subscribes to data changes.|
| DistributedDataObject| off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Unsubscribes from data changes. **Callback**: specifies callback used to return changes of the distributed data object. If this parameter is not specified, all callbacks related to data changes will be unregistered.|
### Observing Online or Offline Status
......@@ -67,13 +69,13 @@ The saved data will be released in the following cases:
- The application has been uninstalled.
- Data is successfully restored.
**Table 6** APIs for saving a distributed data object and revoking the saving
**Table 6** APIs for saving a distributed data object and revoking the saving operation
| Class| API| Description|
| -------- | -------- | -------- |
| DistributedDataObject | save(deviceId: string): Promise&lt;SaveSuccessResponse&gt; | Saves a distributed data object. This API uses a promise to return the result.|
| DistributedDataObject| save(deviceId: string, callback: AsyncCallback&lt;SaveSuccessResponse&gt;): void | Saves a distributed data object. This API uses an asynchronous callback to return the result.|
| DistributedDataObject | revokeSave(callback: AsyncCallback&lt;RevokeSaveSuccessResponse&gt;): void | Revokes the data saving operation. This API uses an asynchronous callback to return the result. |
| DistributedDataObject| revokeSave(): Promise&lt;RevokeSaveSuccessResponse&gt; | Revokes the data saving operation. This API uses a promise to return the result. |
| DistributedDataObject | revokeSave(callback: AsyncCallback&lt;RevokeSaveSuccessResponse&gt;): void | Revokes the data saving operation. This API uses an asynchronous callback to return the result.|
| DistributedDataObject| revokeSave(): Promise&lt;RevokeSaveSuccessResponse&gt; | Revokes the data saving operation. This API uses a promise to return the result.|
## How to Develop
......@@ -157,7 +159,7 @@ The following example shows how to implement a distributed data object synchroni
local_object.on("change", this.changeCallback.bind(this));
```
6. Modify object attributes. <br>The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types).
6. Modify object attributes. <br>The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types).
The sample code is as follows:
```js
......@@ -205,41 +207,39 @@ The following example shows how to implement a distributed data object synchroni
10. Save a distributed data object and revoke the data saving operation.
- Callback
```js
// Save a distributed data object.
local_object.save("local", (result, data)=>{
console.log("save callback");
console.info("save sessionId " + data.sessionId);
console.info("save version " + data.version);
console.info("save deviceId " + data.deviceId);
});
// Revoke the data saving operation.
local_object.revokeSave((result, data) =>{
console.log("revokeSave callback");
console.info("revokeSave sessionId " + data.sessionId);
});
```
- Promise
```js
// Save a distributed data object.
g_object.save("local").then((result)=>{
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}, (result)=>{
console.info("save local failed.");
});
// Revoke the data saving operation.
g_object.revokeSave().then((result)=>{
console.info("revokeSave success.");
}, (result)=>{
console.info("revokeSave failed.");
});
```
11. Unsubscribe from the status changes of the distributed data object. <br>You can specify the callback to unregister. If you do not specify the callback, this API unregister all callbacks of this distributed data object.
```js
// Save a distributed data object.
local_object.save("local", (result, data)=>{
console.log("save callback");
console.info("save sessionId " + data.sessionId);
console.info("save version " + data.version);
console.info("save deviceId " + data.deviceId);
});
// Revoke the data saving operation.
local_object.revokeSave((result, data) =>{
console.log("revokeSave callback");
console.info("revokeSave sessionId " + data.sessionId);
});
```
- Promise
```js
// Save a distributed data object.
g_object.save("local").then((result)=>{
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}, (result)=>{
console.info("save local failed.");
});
// Revoke the data saving operation.
g_object.revokeSave().then((result)=>{
console.info("revokeSave success.");
}, (result)=>{
console.info("revokeSave failed.");
});
```
11. Unsubscribe from the status changes of the distributed data object. <br>You can specify the callback to unregister. If you do not specify the callback, this API unregisters all callbacks of this distributed data object.
The sample code is as follows:
```js
......
......@@ -7,19 +7,21 @@ The Distributed Data Service (DDS) implements synchronization of application dat
## Available APIs
For details about the APIs related to distributed data, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md).
The table below describes the APIs provided by the OpenHarmony DDS module.
**Table 1** APIs provided by the DDS
| Category | API | Description |
| -------- | --- | ----------- |
| Creating a distributed database | createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KVManager** object for database management.|
| Obtaining a distributed KV store | getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Obtains the KV store with the specified **Options** and **storeId**. |
| Managing data in a distributed KV store | put(key: string, value: Uint8Array \| string \| number \| boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array \| string \| number \| boolean): Promise&lt;void> | Inserts and updates data. |
| Category | API | Description |
| ------------ | ------------- | ------------- |
| Creating a distributed database| createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KVManager** object for database management.|
| Obtaining a distributed KV store| getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Obtains the KV store with the specified **Options** and **storeId**.|
| Managing data in a distributed KV store| put(key: string, value: Uint8Array \| string \| number \| boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array \| string \| number \| boolean): Promise&lt;void> | Inserts and updates data.|
| Managing data in a distributed KV store| delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. |
| Managing data in a distributed KV store | get(key: string, callback: AsyncCallback&lt;Uint8Array \| string \| boolean \| number&gt;): void<br>get(key: string): Promise&lt;Uint8Array \| string \| boolean \| number> | Queries data. |
| Subscribing to changes in the distributed data | on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;ChangeNotification&gt;): void<br>on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string, number]&gt;&gt;): void | Subscribes to data changes in the KV store. |
| Synchronizing data across devices | sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. |
| Managing data in a distributed KV store| get(key: string, callback: AsyncCallback&lt;Uint8Array \| string \| boolean \| number&gt;): void<br>get(key: string): Promise&lt;Uint8Array \| string \| boolean \| number> | Queries data. |
| Subscribing to changes in the distributed data| on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;ChangeNotification&gt;): void<br>on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string, number]&gt;&gt;): void | Subscribes to data changes in the KV store.|
| Synchronizing data across devices| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. |
......@@ -29,14 +31,13 @@ The table below describes the APIs provided by the OpenHarmony DDS module.
The following uses a single KV store as an example to describe the development procedure.
1. Import the distributed data module.
```js
import distributedData from '@ohos.data.distributedData';
```
2. Create a **KvManager** instance based on the specified **KvManagerConfig** object.
1. Create a **KvManagerConfig** object based on the application context.
2. Create a **KvManager** instance.
(1) Create a **KvManagerConfig** object based on the application context.
(2) Create a **KvManager** instance.
The sample code is as follows:
```js
......@@ -63,8 +64,8 @@ The following uses a single KV store as an example to describe the development p
```
3. Create and obtain a single KV store.
1. Declare the ID of the single KV store to create.
2. Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required.
(1) Declare the ID of the single KV store to create.
(2) Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required.
The sample code is as follows:
```js
......@@ -91,12 +92,11 @@ The following uses a single KV store as an example to describe the development p
}
```
> ![icon-note.gif](../public_sys-resources/icon-note.gif) **NOTE**<br/>
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (**kvStore** in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle.
4. Subscribe to changes in the distributed data.<br/>
4. Subscribe to changes in the distributed data.<br/>
The following is the sample code for subscribing to the data changes of a single KV store:
```js
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
console.log("dataChange callback call data: " + JSON.stringify(data));
......@@ -104,8 +104,8 @@ The following uses a single KV store as an example to describe the development p
```
5. Write data to the single KV store.
1. Construct the key and value to be written into the single KV store.
2. Write key-value pairs into the single KV store.
(1) Construct the key and value to be written into the single KV store.
(2) Write key-value pairs into the single KV store.
The following is the sample code for writing key-value pairs of the string type into the single KV store:
......@@ -126,11 +126,10 @@ The following uses a single KV store as an example to describe the development p
```
6. Query data in the single KV store.
1. Construct the key to be queried from the single KV store.
2. Query data from the single KV store.
(1) Construct the key to be queried from the single KV store.
(2) Query data from the single KV store.
The following is the sample code for querying data of the string type from the single KV store:
```js
const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
......@@ -178,3 +177,7 @@ The following uses a single KV store as an example to describe the development p
}
});
```
## Samples
The following samples are provided to help you better understand the distributed data development:
- [`KvStore`: Distributed Database (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Kvstore)
- [Distributed Database](https://gitee.com/openharmony/codelabs/tree/master/Data/JsDistributedData)
......@@ -34,7 +34,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
| Class| API| Description|
| -------- | -------- | -------- |
| RdbStore | insert(table: string, values: ValuesBucket, callback: AsyncCallback&lt;number&gt;):void | Inserts a row of data into a table. This API uses a callback to return the result.<br>- **table**: name of the target table.<br>- **values**: data to be inserted into the table.<br>- **callback**: callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.|
| RdbStore | insert(table: string, values: ValuesBucket, callback: AsyncCallback&lt;number&gt;):void | Inserts a row of data into a table. This API uses a callback to return the result.<br>- **table**: name of the target table.<br>- **values**: data to be inserted into the table.<br>- **callback**: callback invoked to return the result. If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.|
| RdbStore | insert(table: string, values: ValuesBucket): Promise&lt;number&gt; | Inserts a row of data into a table. This API uses a promise to return the result.<br>- **table**: name of the target table.<br>- **values**: data to be inserted into the table.|
- **Updating data**
......@@ -190,7 +190,7 @@ You can obtain the distributed table name for a remote device based on the local
| -------- | -------- | -------- |
| RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback\<Array\<string>>): void;| Unregisters the observer of the specified type for the RDB store. This API uses a callback to return the result.<br>- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** means to subscribe to remote data changes.<br>- **observer**: observer to unregister.|
### Backing Up and Restore an RDB Store
### Backing Up and Restoring an RDB Store
**Backing Up an RDB Store**
......@@ -198,8 +198,8 @@ You can obtain the distributed table name for a remote device based on the local
| Class| API| Description|
| -------- | -------- | -------- |
| RdbStore |backup(destName:string, callback: AsyncCallback&lt;void&gt;):void| Backs up the RDB store with the specified name. This API uses an asynchronous callback to return the result.<br>- **destName**: name of the RDB backup file.<br>- **callback**: callback invoked to return the result.|
| RdbStore |backup(destName:string): Promise&lt;void&gt;| Backs up the RDB store with the specified name. This API uses a promise to return the result.<br>- **destName**: name of the RDB backup file.|
| RdbStore |backup(destName:string, callback: AsyncCallback&lt;void&gt;):void| Backs up an RDB store. This API uses an asynchronous callback to return the result.<br>- **destName**: name of the RDB backup file.<br>- **callback**: callback invoked to return the result.|
| RdbStore |backup(destName:string): Promise&lt;void&gt;| Backs up an RDB store. This API uses a promise to return the result.<br>- **destName**: name of the RDB backup file.|
**Restoring an RDB Store**
......@@ -207,8 +207,8 @@ You can obtain the distributed table name for a remote device based on the local
| Class| API| Description|
| -------- | -------- | -------- |
| RdbStore |restore(srcName:string, callback: AsyncCallback&lt;void&gt;):void| Restores an RDB store using the specified backup file. This API uses an asynchronous callback to return the result.<br>- **srcName**: name of the RDB backup file.<br>- **callback**: callback invoked to return the result.|
| RdbStore |restore(srcName:string): Promise&lt;void&gt;| Restores an RDB store using the specified backup file. This API uses a promise to return the result.<br>- **srcName**: name of the RDB backup file.|
| RdbStore |restore(srcName:string, callback: AsyncCallback&lt;void&gt;):void| Restores an RDB store using a backup file. This API uses an asynchronous callback to return the result.<br>- **srcName**: name of the RDB backup file.<br>- **callback**: callback invoked to return the result.|
| RdbStore |restore(srcName:string): Promise&lt;void&gt;| Restores an RDB store using a backup file. This API uses a promise to return the result.<br>- **srcName**: name of the RDB backup file.|
## How to Develop
......@@ -270,7 +270,7 @@ You can obtain the distributed table name for a remote device based on the local
const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType"))
resultSet.close()
})
```
```
4. Set the distributed tables to be synchronized.
......
......@@ -3,7 +3,6 @@
## When to Use
With device usage statistics APIs, you can have a better understanding of the application, notification, and system usage. For example, in application usage statistics, you can query the application usage, event log, and bundle group.
The application records (usage history statistics and event records) cached by components are updated to the database for persistent storage within 30 minutes after an event is reported.
## Available APIs
......@@ -23,7 +22,7 @@ import stats from '@ohos.bundleState';
| function queryAppUsagePriorityGroup(callback: AsyncCallback&lt;number&gt;): void | Queries the priority group of this application. This API uses an asynchronous callback to return the result.|
| function queryAppUsagePriorityGroup(): Promise&lt;number&gt;; | Queries the priority group of this application. This API uses a promise to return the result.|
| function isIdleState(bundleName: string, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether the application specified by **bundleName** is in the idle state. |
| function getRecentlyUsedModules(maxNum: number, callback: AsyncCallback&lt;BundleActiveModuleInfo&gt;): void | Obtains the number of FA usage records specified by **maxNum**.|
| function getRecentlyUsedModules(maxNum? : number, callback: AsyncCallback&lt;BundleActiveModuleInfo&gt;): void | Obtains the number of FA usage records specified by **maxNum**. If **maxNum** is not specified, the default value **1000** is used.|
| function queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback&lt;Array&lt;BundleActiveEventState&gt;&gt;): void | Queries the number of notifications from all applications based on the specified start time and end time.|
| function queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback&lt;Array&lt;BundleActiveEventState&gt;&gt;): void | Queries statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time.|
| function queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback&lt;number&gt;): void | Queries the priority group of the application specified by **bundleName**. If **bundleName** is not specified, the priority group of the current application is queried. This API uses an asynchronous callback to return the result.|
......@@ -45,7 +44,7 @@ import stats from '@ohos.bundleState';
...,
"reqPermissions": [
{
"name": "ohos.permission.BUNDLE_ACTIVE_INFO"
"name": "ohos.permission.BUNDLE_ACTIVE_INFO"
}
]
}
......@@ -57,13 +56,13 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState'
// Promise mode
stats.queryBundleActiveStates(0, 20000000000000).then( res => {
stats.queryBundleActiveStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise success.');
for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise result ' + JSON.stringify(res[i]));
}
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise failed, because: ' + err.code);
});
......@@ -87,7 +86,7 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState'
// Promise mode
stats.queryBundleStateInfos(0, 20000000000000).then( res => {
stats.queryBundleStateInfos(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise success.');
let i = 1;
for (let key in res){
......@@ -95,7 +94,7 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise result ' + JSON.stringify(res[key]));
i++;
}
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise failed, because: ' + err.code);
});
......@@ -121,13 +120,13 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState'
// Promise mode
stats.queryCurrentBundleActiveStates(0, 20000000000000).then( res => {
stats.queryCurrentBundleActiveStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.');
for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise result ' + JSON.stringify(res[i]));
}
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise failed, because: ' + err.code);
});
......@@ -151,13 +150,13 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState'
// Promise mode
stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then( res => {
stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.');
for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise result ' + JSON.stringify(res[i]));
}
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise failed, because: ' + err.code);
});
......@@ -179,14 +178,14 @@ import stats from '@ohos.bundleState';
```js
import stats from '@ohos.bundleState'
// Promise mode
stats.queryAppUsagePriorityGroup().then( res => {
stats.queryAppUsagePriorityGroup().then(res => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code);
});
// Callback mode
stats.queryAppUsagePriorityGroup((err, res) => {
if (err) {
......@@ -196,16 +195,16 @@ import stats from '@ohos.bundleState';
}
});
```
7. Check whether the application specified by **bundleName** is in the idle state. This requires no permission to be configured in the **config.json** file. A third-party application can only check the idle status of itself.
```js
import stats from '@ohos.bundleState'
// Promise mode
stats.isIdleState("com.ohos.camera").then( res => {
stats.isIdleState("com.ohos.camera").then(res => {
console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res));
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE isIdleState promise failed, because: ' + err.code);
});
......@@ -225,18 +224,18 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState'
// Promise mode
stats.getRecentlyUsedModules(1000).then( res => {
stats.getRecentlyUsedModules(1000).then(res => {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded');
for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise result ' + JSON.stringify(res[i]));
}
}).catch( err=> {
}).catch(err=> {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise failed, because: ' + err.code);
});
// Promise mode when maxNum is not specified
stats.getRecentlyUsedModules().then( res => {
stats.getRecentlyUsedModules().then(res => {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded');
for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1));
......@@ -247,7 +246,7 @@ import stats from '@ohos.bundleState';
});
// Asynchronous callback mode
stats.getRecentlyUsedModules(1000,(err, res) => {
stats.getRecentlyUsedModules(1000, (err, res) => {
if(err) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code);
} else {
......@@ -261,7 +260,7 @@ import stats from '@ohos.bundleState';
// Asynchronous callback mode when maxNum is not specified
stats.getRecentlyUsedModules((err, res) => {
if(err) {
if (err) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code);
} else {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback succeeded.');
......@@ -279,10 +278,10 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState'
// Promise mode
stats.queryAppNotificationNumber(0, 20000000000000).then( res => {
stats.queryAppNotificationNumber(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise success.');
console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise result ' + JSON.stringify(res));
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise failed, because: ' + err.code);
});
......@@ -301,15 +300,15 @@ import stats from '@ohos.bundleState';
```js
import stats from '@ohos.bundleState'
// Promise mode
stats.queryBundleActiveEventStates(0, 20000000000000).then( res => {
stats.queryBundleActiveEventStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise success.');
console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise result ' + JSON.stringify(res));
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise failed, because: ' + err.code);
});
// Asynchronous callback mode
stats.queryBundleActiveEventStates(0, 20000000000000, (err, res) => {
if (err) {
......@@ -325,14 +324,14 @@ import stats from '@ohos.bundleState';
```js
import stats from '@ohos.bundleState'
// Promise mode without parameters
stats.queryAppUsagePriorityGroup().then( res => {
stats.queryAppUsagePriorityGroup().then(res => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code);
});
// Asynchronous callback mode without parameters
stats.queryAppUsagePriorityGroup((err, res) => {
if (err) {
......@@ -341,17 +340,17 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res));
}
});
// Promise mode with parameters
stats.queryAppUsagePriorityGroup(this.bundleName).then( res => {
stats.queryAppUsagePriorityGroup(this.bundleName).then(res => {
console.log('BUNDLE_ACTIVE QueryPackageGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE QueryPackageGroup promise failed. because: ' + err.code);
});
// Asynchronous callback mode with parameters
stats.queryAppUsagePriorityGroup(this.bundleName, (err, res) => {
if(err) {
if (err) {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code);
} else {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback succeeded. result: ' + JSON.stringify(res));
......@@ -363,16 +362,16 @@ import stats from '@ohos.bundleState';
```javascript
import stats from '@ohos.bundleState'
// Promise mode
stats.setBundleGroup(this.bundleName, this.newGroup).then( () => {
stats.setBundleGroup(this.bundleName, this.newGroup).then(() => {
console.log('BUNDLE_ACTIVE SetBundleGroup promise succeeded.');
}).catch( err => {
console.log('BUNDLE_ACTIVE SetBundleGroup promise failed. because: ' + err.code);
});
// Asynchronous callback mode
stats.setBundleGroup(this.bundleName, this.newGroup, (err) => {
if(err) {
if (err) {
console.log('BUNDLE_ACTIVE SetBundleGroup callback failed. because: ' + err.code);
} else {
console.log('BUNDLE_ACTIVE SetBundleGroup callback succeeded.');
......@@ -384,9 +383,9 @@ import stats from '@ohos.bundleState';
```javascript
import stats from '@ohos.bundleState'
// Promise mode
let onBundleGroupChanged = (err,res) =>{
let onBundleGroupChanged = (err,res) => {
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.');
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result oldGroup is : ' + res.oldGroup);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result newGroup is : ' + res.newGroup);
......@@ -394,13 +393,13 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result userId is : ' + res.userId);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result bundleName is : ' + res.bundleName);
};
stats.registerGroupCallBack(onBundleGroupChanged).then( () => {
stats.registerGroupCallBack(onBundleGroupChanged).then(() => {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise succeeded.');
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise failed. because: ' + err.code);
});
// Asynchronous callback mode
let onBundleGroupChanged = (err,res) =>{
let onBundleGroupChanged = (err,res) => {
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.');
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's oldGroup is : ' + res.oldGroup);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's newGroup is : ' + res.newGroup);
......@@ -408,29 +407,29 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's userId is : ' + res.userId);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's bundleName is : ' + res.bundleName);
};
stats.registerGroupCallBack(onBundleGroupChanged, (err)=>{
if(err) {
stats.registerGroupCallBack(onBundleGroupChanged, (err) => {
if (err) {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback failed, because: ' + err.code);
} else {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback success.');
}
});
```
13. Deregister the callback for application group changes.
```javascript
import stats from '@ohos.bundleState'
//promise
stats.unRegisterGroupCallBack().then( () => {
stats.unRegisterGroupCallBack().then(() => {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise succeeded.');
}).catch( err => {
}).catch(err => {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise failed. because: ' + err.code);
});
//callback
stats.unRegisterGroupCallBack((err)=>{
if(err) {
stats.unRegisterGroupCallBack((err) => {
if (err) {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback failed, because: ' + err.code);
} else {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback success.');
......
......@@ -2273,7 +2273,43 @@ Writes the buffer. This API uses an asynchronous callback to return the result.
```
import audio from '@ohos.multimedia.audio';
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 buf = new ArrayBuffer(bufferSize);
ss.readSync(buf);
......@@ -2305,7 +2341,42 @@ Writes the buffer. This API uses a promise to return the result.
```
import audio from '@ohos.multimedia.audio';
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';
let ss = fileio.createStreamSync(filePath, 'r');
let buf = new ArrayBuffer(bufferSize);
......@@ -2408,12 +2479,39 @@ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a
**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;
await audioRenderer.getBufferSize().then(async function (data) => {
console.info('AudioFrameworkRenderLog: getBufferSize :SUCCESS '+data);
audioRenderer.getBufferSize().then((data) => {
console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data);
bufferSize=data;
}).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
**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.');
});
```
......@@ -2564,7 +2663,8 @@ Sets the audio interruption mode for the application. This API uses a callback t
**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.');
});
```
......@@ -2654,7 +2754,7 @@ Subscribes to mark reached events. When the number of frames rendered reaches th
```
audioRenderer.on('markReach', 1000, (position) => {
if (position == "1000") {
if (position == 1000) {
console.log('ON Triggered successfully');
}
});
......@@ -2701,7 +2801,7 @@ Subscribes to period reached events. When the period of frame rendering reaches
```
audioRenderer.on('periodReach', 1000, (position) => {
if (position == "1000") {
if (position == 1000) {
console.log('ON Triggered successfully');
}
});
......@@ -2935,13 +3035,35 @@ Starts capturing. This API uses a promise to return the result.
**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(() => {
console.info('AudioFrameworkRecLog: ---------START---------');
console.info('AudioFrameworkRecLog: Capturer started :SUCCESS ');
console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state);
console.info('AudioFrameworkRecLog: Capturer started :SUCCESS ');
console.info('AudioFrameworkRecLog: Capturer started: SUCCESS');
console.info('AudioFrameworkRecLog: AudioCapturer: STATE: '+audioCapturer.state);
console.info('AudioFrameworkRecLog: Capturer started: SUCCESS ');
if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) {
stateFlag = true;
console.info('AudioFrameworkRecLog: AudioCapturer is in Running State');
}
}).catch((err) => {
console.info('AudioFrameworkRecLog: Capturer start :ERROR : '+err.message);
......@@ -2994,15 +3116,13 @@ Stops capturing. This API uses a promise to return the result.
```
audioCapturer.stop().then(() => {
console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------');
console.info('AudioFrameworkRecLog: Capturer stopped : SUCCESS');
console.info('AudioFrameworkRecLog: ---------STOP RECORD---------');
console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS');
if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){
stateFlag=true;
console.info('AudioFrameworkRecLog: resultFlag : '+stateFlag);
console.info('AudioFrameworkRecLog: State is Stopped': ');
}
}).catch((err) => {
console.info('AudioFrameworkRecLog: Capturer stop:ERROR : '+err.message);
stateFlag=false;
console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+err.message);
});
```
......@@ -3054,11 +3174,9 @@ audioCapturer.release().then(() => {
console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------');
console.info('AudioFrameworkRecLog: Capturer release : SUCCESS');
console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state);
stateFlag=true;
console.info('AudioFrameworkRecLog: stateFlag : '+stateFlag);
}).catch((err) => {
console.info('AudioFrameworkRecLog: Capturer stop:ERROR : '+err.message);
stateFlag=false
console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+err.message);
});
```
......@@ -3082,6 +3200,13 @@ Reads the buffer. This API uses an asynchronous callback to return the result.
**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) => {
if (!err) {
console.log("Success in reading the buffer data");
......@@ -3114,6 +3239,14 @@ Reads the buffer. This API uses a promise to return the result.
**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) => {
console.info('buffer read successfully');
}).catch((err) => {
......@@ -3217,12 +3350,12 @@ Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a
**Example**
```
await audioCapturer.getBufferSize().then(async function (bufferSize) {
console.info('AudioFrameworkRecordLog: getBufferSize :SUCCESS '+ bufferSize);
var buffer = await audioCapturer.read(bufferSize, true);
console.info('Buffer read is ' + buffer );
}).catch((err) => {
console.info('AudioFrameworkRecordLog: getBufferSize :ERROR : '+err.message);
var bufferSize;
audioCapturer.getBufferSize().then((data) => {
console.info('AudioFrameworkRecLog: getBufferSize :SUCCESS '+ data);
bufferSize = data;
}).catch((err) => {
console.info('AudioFrameworkRecLog: getBufferSize :ERROR : '+ err.message);
});
```
......@@ -3247,7 +3380,7 @@ Subscribes to mark reached events. When the number of frames captured reaches th
```
audioCapturer.on('markReach', 1000, (position) => {
if (position == "1000") {
if (position == 1000) {
console.log('ON Triggered successfully');
}
});
......@@ -3293,7 +3426,7 @@ Subscribes to mark reached events. When the period of frame capturing reaches th
```
audioCapturer.on('periodReach', 1000, (position) => {
if (position == "1000") {
if (position == 1000) {
console.log('ON Triggered successfully');
}
});
......
# 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/>
>
......@@ -23,9 +23,9 @@ Creates a distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | object | Yes| Attribute of the distributed data object to create.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | object | Yes| Attribute of the distributed data object to create.|
**Return value**
| Type| Description|
......@@ -33,12 +33,11 @@ Creates a distributed data object.
| [DistributedObject](#distributedobject) | Distributed data object created.|
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
// 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,
parent:{mother:"jack mom",father:"jack Dad"}});
```
```js
import distributedObject from '@ohos.data.distributedDataObject';
// 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, parent:{mother:"jack mom",father:"jack Dad"}});
```
## distributedObject.genSessionId
......@@ -50,15 +49,15 @@ Creates a random session ID.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Return value**
| Type| Description|
| -------- | -------- |
| string | Session ID created.|
| Type| Description|
| -------- | -------- |
| string | Session ID created.|
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
var sessionId = distributedObject.genSessionId();
```
```js
import distributedObject from '@ohos.data.distributedDataObject';
var sessionId = distributedObject.genSessionId();
```
## SaveSuccessResponse<sup>9+</sup>
......@@ -98,27 +97,26 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
**Parameters**
| 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.|
| 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.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the session ID is set successfully;<br>returns **false** otherwise. |
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the session ID is set successfully;<br>returns **false** otherwise. |
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,
parent:{mother:"jack mom",father:"jack Dad"}});
// Add g_object to the distributed network.
g_object.setSessionId(distributedObject.genSessionId());
// Remove g_object from the distributed network.
g_object.setSessionId("");
```
```js
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});;
// Add g_object to the distributed network.
g_object.setSessionId(distributedObject.genSessionId());
// Remove g_object from the distributed network.
g_object.setSessionId("");
```
### on('change')
......@@ -130,15 +128,15 @@ Subscribes to the changes of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
**Example**
```js
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) => {
console.info("change" + sessionId);
if (changeData != null && changeData != undefined) {
......@@ -159,16 +157,16 @@ Unsubscribes from the changes of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
**Example**
```js
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.
g_object.off("change", globalThis.changeCallback);
// Unregister all data change callbacks.
......@@ -184,10 +182,10 @@ Subscribes to the status change (online or offline) of this distributed data obj
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| 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.|
| 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. |
| 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.|
| 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**
```js
......@@ -195,7 +193,7 @@ import distributedObject from '@ohos.data.distributedDataObject';
globalThis.statusCallback = (sessionId, networkId, status) => {
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);
```
......@@ -209,16 +207,16 @@ Unsubscribes from the status change (online or offline) of this distributed data
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| 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.|
| 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.|
| 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.|
| 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**
```js
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.response += "status changed " + sessionId + " " + status + " " + networkId;
}
......@@ -245,24 +243,24 @@ The saved data will be released in the following cases:
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.|
| callback | AsyncCallback&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
**Example**
```ts
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.save("local", (result)=>{
console.log("save callback");
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
});
```
```js
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.save("local", (status, result)=>{
console.log("save status = " + status);
console.log("save callback");
console.info("save sessionId: " + result.sessionId);
console.info("save version: " + result.version);
console.info("save deviceId: " + result.deviceId);
});
```
### save<sup>9+</sup>
......@@ -281,31 +279,31 @@ The saved data will be released in the following cases:
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| 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. |
| 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. |
**Return value**
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[SaveSuccessResponse](#savesuccessresponse)&gt; | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
**Example**
```ts
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.save("local").then((result)=>{
console.log("save callback");
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}, ()=>{
console.error("save failed");
});
```
```js
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.save("local").then((result)=>{
console.log("save callback");
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}, ()=>{
console.error("save failed");
});
```
### revokeSave<sup>9+</sup>
......@@ -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
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse)&gt; | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
**Example**
```ts
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.revokeSave((result, data) =>{
console.log("revokeSave callback");
});
```
```js
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.revokeSave((result, data) =>{
console.log("revokeSave callback");
});
```
### revokeSave<sup>9+</sup>
......@@ -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
**Return value**
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse)&gt; | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
**Example**
```ts
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.revokeSave("local").then((result)=>{
console.log("revokeSave callback");
console.log("sessionId" + result.sessionId);
}, ()=>{
console.error("revokeSave failed");
});
```
```js
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.revokeSave().then((result)=>{
console.log("revokeSave callback");
console.log("sessionId" + result.sessionId);
}, ()=>{
console.error("revokeSave failed");
});
```
# Display
Provides APIs for managing displays, such as obtaining information about the default display, obtaining information about all displays, and listening for the addition and removal of displays.
The **Display** module provides APIs for managing displays, such as obtaining information about the default display, obtaining information about all displays, and listening for the addition and removal of displays.
> **NOTE**
>
......@@ -14,11 +14,11 @@ import display from '@ohos.display';
## DisplayState
Provides the state of a display.
Enumerates the display states.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
| Name| Default Value| Description|
| Name| Value| Description|
| -------- | -------- | -------- |
| STATE_UNKNOWN | 0 | Unknown.|
| STATE_OFF | 1 | The display is shut down.|
......@@ -56,7 +56,7 @@ Describes the attributes of a display.
getDefaultDisplay(callback: AsyncCallback&lt;Display&gt;): void
Obtains the default display object.
Obtains the default display object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
......@@ -82,7 +82,7 @@ Obtains the default display object.
getDefaultDisplay(): Promise&lt;Display&gt;
Obtains the default display object.
Obtains the default display object. This API uses a promise to return the result.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
......@@ -103,11 +103,31 @@ Obtains the default display object.
});
```
## display.getDefaultDisplaySync<sup>9+</sup>
getDefaultDisplaySync(): Display
Obtains the default display object. This API returns the result synchronously.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
**Return value**
| Type | Description |
| ------------------------------| ----------------------------------------------|
| [Display](#display) | Default display object.|
**Example**
```js
var displayClass = display.getDefaultDisplaySync();
```
## display.getAllDisplay
getAllDisplay(callback: AsyncCallback&lt;Array&lt;Display&gt;&gt;): void
Obtains all the display objects.
Obtains all display objects. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
......@@ -133,7 +153,7 @@ Obtains all the display objects.
getAllDisplay(): Promise&lt;Array&lt;Display&gt;&gt;
Obtains all the display objects.
Obtains all display objects. This API uses a promise to return the result.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
......@@ -158,15 +178,15 @@ Obtains all the display objects.
on(type: 'add'|'remove'|'change', callback: Callback&lt;number&gt;): void
Enables listening.
Subscribes to display changes.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Listening type. The available values are as follows:<br>- **add**: listening for whether a display is added<br>- **remove**: listening for whether a display is removed<br>- **change**: listening for whether a display is changed|
| callback | Callback&lt;number&gt; | Yes| Callback used to return the ID of the display.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type.<br>- **add**, indicating the display addition event.<br>- **remove**, indicating the display removal event.<br>- **change**, indicating the display change event.|
| callback | Callback&lt;number&gt; | Yes| Callback used to return the ID of the display.|
**Example**
```js
......@@ -181,14 +201,14 @@ Enables listening.
off(type: 'add'|'remove'|'change', callback?: Callback&lt;number&gt;): void
Disables listening.
Unsubscribes from display changes.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Listening type. The available values are as follows:<br>- **add**: listening for whether a display is added<br>- **remove**: listening for whether a display is removed<br>- **change**: listening for whether a display is changed|
| type | string | Yes| Event type.<br>- **add**, indicating the display addition event.<br>- **remove**, indicating the display removal event.<br>- **change**, indicating the display change event.|
| callback | Callback&lt;number&gt; | No| Callback used to return the ID of the display.|
**Example**
......
......@@ -2,7 +2,7 @@
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.
......
......@@ -20,7 +20,7 @@ Obtains an **AccountManager** instance.
**System capability**: SystemCapability.Account.OsAccount
**Return Value**
**Return value**
| Type | Description |
| --------------------------------- | ------------------------ |
| [AccountManager](#accountmanager) | Obtains an **AccountManager** instance.|
......@@ -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.|
**Return Value**
**Return value**
| Type | Description |
| :------------------ | :---------------------------------- |
......@@ -141,7 +141,7 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re
**System capability**: SystemCapability.Account.OsAccount
**Return Value**
**Return value**
| Type | Description |
| :--------------------- | :----------------------------------------------------------- |
......@@ -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.|
**Return Value**
**Return value**
| Type | Description |
| :--------------------- | :----------------------------------------------------------- |
......@@ -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. |
| constraint | string | Yes | [Constraint](#constraints) specified.|
**Return Value**
**Return value**
| Type | Description |
| :--------------------- | :----------------------------------------------------------- |
......@@ -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
**Return Value**
**Return value**
| Type | Description |
| :--------------------- | :----------------------------------------------------------- |
......@@ -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.|
**Return Value**
**Return value**
| Type | Description |
| :--------------------- | :----------------------------------------------------------- |
......@@ -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.|
**Return Value**
**Return value**
| Type | Description |
| :------------------ | :---------------------------------- |
......@@ -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.|
| 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 |
| :------------------ | :---------------------------------- |
......@@ -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.|
| localName | string | Yes | Account name to set. |
**Return Value**
**Return value**
| Type | Description |
| :------------------ | :---------------------------------- |
......@@ -663,7 +663,7 @@ Obtains the number of OS accounts created. This API uses a promise to return the
**System capability**: SystemCapability.Account.OsAccount
**Return Value**
**Return value**
| Type | Description |
| :-------------------- | :----------------------------------------------------------- |
......@@ -712,7 +712,7 @@ Obtains the ID of the OS account to which the current process belongs. This API
**System capability**: SystemCapability.Account.OsAccount
**Return Value**
**Return value**
| Type | Description |
| :-------------------- | :----------------------------------------------------------- |
......@@ -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.|
**Return Value**
**Return value**
| Type | Description |
| :-------------------- | :----------------------------------------------------------- |
......@@ -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.|
**Return Value**
**Return value**
| Type | Description |
| :-------------------- | :----------------------------------------------------------- |
......@@ -885,7 +885,7 @@ This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.Account.OsAccount
**Return Value**
**Return value**
| Type | Description |
| :-------------------- | :----------------------------------------------------------- |
......@@ -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.|
**Return Value**
**Return value**
| Type | Description |
| :--------------------------------- | :----------------------------------------------------------- |
......@@ -1004,7 +1004,7 @@ This is a system API and cannot be called by third-party applications.
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
**Return Value**
**Return value**
| Type | Description |
| :---------------------------------------------------------- | :----------------------------------------------------------- |
......@@ -1056,7 +1056,7 @@ Obtains information about all activated OS accounts. This API uses a promise to
**System capability**: SystemCapability.Account.OsAccount
**Return Value**
**Return value**
| Type | Description |
| :--------------------------------- | :----------------------------------------------------------- |
......@@ -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.|
| type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.|
**Return Value**
**Return value**
| Type | Description |
| :--------------------------------------------- | :----------------------------------------------------------- |
......@@ -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.|
| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. |
**Return Value**
**Return value**
| Type | Description |
| :--------------------------------------------- | :----------------------------------------------------------- |
......@@ -1243,7 +1243,7 @@ Obtains information about the OS account to which the current process belongs. T
**System capability**: SystemCapability.Account.OsAccount
**Return Value**
**Return value**
| Type | Description |
| :--------------------------------------------- | :----------------------------------------------------------- |
......@@ -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.|
**Return Value**
**Return value**
| Type | Description |
| :--------------------------------------------- | :----------------------------------------------------------- |
......@@ -1358,7 +1358,7 @@ Obtains the type of the OS account to which the current process belongs. This AP
**System capability**: SystemCapability.Account.OsAccount
**Return Value**
**Return value**
| Type | Description |
| :--------------------------------------------- | :----------------------------------------------------------- |
......@@ -1411,7 +1411,7 @@ Obtains the ID of this distributed virtual device. This API uses a promise to re
**System capability**: SystemCapability.Account.OsAccount
**Return Value**
**Return value**
| Type | Description |
| :-------------------- | :----------------------------------------------------------- |
......@@ -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.|
**Return Value**
**Return value**
| Type | Description |
| :-------------------- | :----------------------------------------------------------- |
......@@ -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.|
| photo | string | Yes | Profile photo information. |
**Return Value**
**Return value**
| Type | Description |
| :------------------ | :---------------------------------- |
......@@ -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.|
**Return Value**
**Return value**
| Type | Description |
| :-------------------- | :----------------------------------------------------------- |
......@@ -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.|
**Return Value**
**Return value**
| Type | Description |
| :-------------------- | :----------------------------------------------------------- |
......@@ -1787,7 +1787,7 @@ This is a system API and cannot be called by third-party applications.
| ------- | ------ | ---- | ------------ |
| uid | number | Yes | Process UID.|
**Return Value**
**Return value**
| Type | Description |
| :-------------------- | :----------------------------------------------------------- |
......@@ -1836,7 +1836,7 @@ This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.Account.OsAccount
**Return Value**
**Return value**
| Type | Description |
| :-------------------- | :----------------------------------------------------------- |
......@@ -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.|
| constraint | string | Yes | Name of the [constraint](#constraints) to query.|
**Return Value**
**Return value**
| Type | Description |
| :-------------------- | :----------------------------------------------------------- |
......
......@@ -3,13 +3,6 @@
## setTimeout
## Modules to Import
```
import Time from '@ohos.Time';
```
setTimeout(handler[,delay[,…args]]): number
Sets a timer for the system to call a function after the timer goes off.
......
# Image
The **\<Image>** component is used to render and display local and online images.
> **NOTE**<br>
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Image&gt;** component is used to render and display images.
## Required Permissions
ohos.permission.INTERNET (using Internet images)
To use online images, you need to add the **ohos.permission.INTERNET** permission to the corresponding abilities in the **config.json** (for the FA model) or **module.json5** file (for the stage model).
```
"abilities": [
{
...
"permissions": ["ohos.permission.INTERNET"],
...
}
]
```
## Child Components
None
Not supported
## APIs
Image(value: {uri: string | PixelMap})
Image(src: string | PixelMap | Resource)
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| uri | string | Yes | - | Image URI. Both local and Internal URIs are supported. |
Obtains an image from the specified source for subsequent rendering and display.
**Parameters**
| Name| Type | Mandatory| Default Value| Description |
| ------ | ------------------------------------------------------------ | ---- | ------ | ------------------------------------------------------------ |
| src | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](../../ui/ts-types.md) | Yes | - | Image source. Both local and online images are supported.<br>When using resources referenced using a relative path, for example, `Image("common/test.jpg")`, the **\<Image>** component cannot be called across bundles or modules. Therefore, you are advised to use `$r` to reference image resources that need to be used globally.<br>\- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.<br>\- Base64 strings are supported. The value format is `data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, where `[base64 data]` is a Base64 string.<br/>\- The value can also be a path starting with `dataability://`, which is used to access the image path provided by a Data ability. |
## Attributes
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| alt | string | - | Placeholder image displayed during loading. Both local and Internal URIs are supported. |
| objectFit | ImageFit | ImageFit.Cover | Image scale type. |
| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat enums) | ImageRepeat.NoRepeat | Whether the image is repeated.<br/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>> - This attribute is not applicable to SVG images. |
| interpolation | ImageInterpolation | ImageInterpolation.None | Interpolation effect of the image. This attribute is valid only when the image is zoomed in.<br/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>> - This attribute is not applicable to SVG images.<br/>> <br/>> - This attribute is not applicable to a **PixelMap** object. |
| renderMode | ImageRenderMode | ImageRenderMode.Original | Rendering mode of the image.<br/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>> - This attribute is not applicable to SVG images. |
| sourceSize | {<br/>width: number,<br/>height: number<br/>} | - | Decoding size of the image. The original image is decoded into an image of the specified size. If the value is of the number type, the unit px is used.<br/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>> This attribute is not applicable to a **PixelMap** object. |
| syncLoad<sup>8+</sup> | boolean | false | Whether to load images synchronously. By default, images are loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed. |
- ImageFit enums
| Name | Description |
| -------- | -------- |
| Cover | The image is scaled with its aspect ratio retained for both sides to be greater than or equal to the display boundaries. |
| Contain | The image is scaled with its aspect ratio retained for the content to be completely displayed within the display boundaries. |
| Fill | The video content is resized to fill the display area while retaining its aspect ratio. |
| None | The original size is retained. Generally, this enum is used together with the **objectRepeat** attribute. |
| ScaleDown | The image content is displayed with its aspect ratio retained. The size is smaller than or equal to the original size. |
- ImageInterpolation enums
| Name | Description |
| -------- | -------- |
| None | Interpolation image data is not used. |
| High | The interpolation image data is used at the high level. The use of the interpolation image data may affect the image rendering speed. |
| Medium | The interpolation image data is used at the medium level. |
| Low | The interpolation image data is used at the low level. |
- ImageRenderMode enums
| Name | Description |
| -------- | -------- |
| Original | The image is rendered based on the original image, including the color. |
| Template | The image is rendered as a template image, and its color is ignored. |
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name | Type | Default Value | Description |
| --------------------- | ---------------------------------------- | ------------------------ | ---------------------------------------- |
| alt | string \| [Resource](../../ui/ts-types.md) | - | Placeholder image displayed during loading. Both local and Internet URIs are supported. |
| objectFit | [ImageFit](#imagefit-enums) | ImageFit.Cover | Image scale type. |
| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | NoRepeat | Whether the image is repeated.<br>**NOTE**<br>This attribute is not applicable to SVG images. |
| interpolation | [ImageInterpolation](#imageinterpolation) | ImageInterpolation.None | Interpolation effect of the image. This attribute is valid only when the image is zoomed in.<br>**NOTE**<br>This attribute is not applicable to SVG images or **PixelMap** objects. |
| renderMode | [ImageRenderMode](#imagerendermode) | ImageRenderMode.Original | Rendering mode of the image.<br>**NOTE**<br>This attribute is not applicable to SVG images. |
| sourceSize | {<br>width: number,<br>height: number<br>} | - | Decoding size of the image. The original image is decoded into an image of the specified size, in px.<br>**NOTE**<br>This attribute is not applicable to **PixelMap** objects. |
| syncLoad<sup>8+</sup> | boolean | false | Whether to load images synchronously. By default, images are loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed. |
### ImageFit
| Name | Description |
| --------- | -------------------------------- |
| Cover | The image is scaled with its aspect ratio retained for both sides to be greater than or equal to the display boundaries. |
| Contain | The image is scaled with its aspect ratio retained for the content to be completely displayed within the display boundaries. |
| Fill | The image is scaled to fill the display area, and its aspect ratio is not retained. |
| None | The image is displayed in its original size. Generally, this enum is used together with the **objectRepeat** attribute.|
| ScaleDown | The image is displayed with its aspect ratio retained, in a size smaller than or equal to the original size. |
### ImageInterpolation
| Name | Description |
| ------ | ------------------------- |
| None | Interpolation image data is not used. |
| High | The interpolation image data is used at the high level, which may affect the image rendering speed.|
| Medium | The interpolation image data is used at the medium level. |
| Low | The interpolation image data is used at the low level. |
### ImageRenderMode
| Name | Description |
| -------- | --------------------- |
| Original | The image is rendered based on the original image, including the color. |
| Template | The image is rendered as a template image, and its color is ignored.|
## Events
| Name | Description |
| -------- | -------- |
| onComplete(callback: (event?: { width: number, height: number, componentWidth: number, componentHeight: number, loadingStatus: number }) =&gt; void) | Triggered when an image is successfully loaded. The loaded image is returned. |
| onError(callback: (event?: { componentWidth: number, componentHeight: number }) =&gt; void) | An exception occurs during image loading. |
| onFinish(callback: () =&gt; void) | If the source file to be loaded is an SVG image, this callback is invoked when the SVG animation playback is complete. If the animation is an infinite loop, this callback is not triggered. |
In addition to the universal events (ts-universal-events-click.md), the following events are supported.
| Name | Description |
| ---------------------------------------- | ---------------------------------------- |
| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,<br> componentHeight: number, loadingStatus: number }) =&gt; void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.<br>- **width**: width of the image, in pixels.<br>- **height**: height of the image, in pixels.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels.<br>- **loadingStatus**: image loading status.<br>|
| onError(callback: (event?: { componentWidth: number, componentHeight: number }) =&gt; void) | Triggered when an exception occurs during image loading.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels.<br>|
| onFinish(callback: () =&gt; void) | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered.|
## Example
### Loading Images
```
// Image1
Load and display different types of images and set the scale type of the images.
```ts
@Entry
@Component
struct ImageExample1 {
......@@ -143,9 +161,9 @@ struct ImageExample1 {
![en-us_image_0000001211898484](figures/en-us_image_0000001211898484.gif)
### Setting Attributes
```
// Image2
```ts
@Entry
@Component
struct ImageExample2 {
......@@ -163,12 +181,12 @@ struct ImageExample2 {
.border({ width: 1 }).borderStyle(BorderStyle.Dashed)
.overlay('Template', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
}
Text('alt').fontSize(12).fontColor(0xcccccc).width('96%').height(30)
Image('')
.alt($r('app.media.Image_none'))
.width(100).height(100).border({ width: 1 }).borderStyle(BorderStyle.Dashed)
Text('sourceSize').fontSize(12).fontColor(0xcccccc).width('96%')
Row({ space: 50 }) {
Image($r('app.media.img_example'))
......@@ -188,7 +206,7 @@ struct ImageExample2 {
.border({ width: 1 }).borderStyle(BorderStyle.Dashed)
.overlay('w:200 h:200', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
}
Text('objectRepeat').fontSize(12).fontColor(0xcccccc).width('96%').height(30)
Row({ space: 5 }) {
Image($r('app.media.ic_health_heart'))
......@@ -211,18 +229,18 @@ struct ImageExample2 {
![en-us_image_0000001212058474](figures/en-us_image_0000001212058474.png)
### Invoking Events
```
// Image3
```ts
@Entry
@Component
struct ImageExample3 {
@State width: number = 0
@State height: number = 0
private on: Resource = $r('app.media.wifi_on')
private off: Resource = $r('app.media.wifi_off')
private on2off: Resource = $r('app.media.wifi_on2off')
private off2on: Resource = $r('app.media.wifi_off2on')
private on: Resource = $r('app.media.image_on')
private off: Resource = $r('app.media.image_off')
private on2off: Resource = $r('app.media.image_on2off')
private off2on: Resource = $r('app.media.image_off2on')
@State src: Resource = this.on
build() {
......@@ -237,6 +255,7 @@ struct ImageExample3 {
})
.objectFit(ImageFit.Cover)
.height(180).width(180)
// Obtain the size of an image after the image loading is complete.
.onComplete((msg: { width: number,height: number }) => {
this.width = msg.width
this.height = msg.height
......@@ -249,7 +268,7 @@ struct ImageExample3 {
offset: { x: 0, y: 20 }
})
}
// Add a click event so that a specific image is loaded upon clicking.
Image(this.src)
.width(120).height(120)
.onClick(() => {
......
# Marquee
> **NOTE**<br>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Marquee>** component is used to display a scrolling piece of text.
The **\<Marquee>** component is used to display a scrolling piece of text. The text is scrolled only when its width exceeds the width of the **\<Marquee>** component.
## Required Permissions
......@@ -15,7 +16,7 @@ None
## Child Components
None
Not supported
## APIs
......@@ -23,28 +24,29 @@ None
Marquee(value: { start: boolean, step?: number, loop?: number, fromStart?: boolean, src: string })
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| start | boolean | Yes | - | Whether to start scrolling. |
| step | number | No | 6 | Scrolling step. |
| loop | number | No | -1 | Number of times the marquee will scroll. If the value is less than or equal to **0**, the marquee will scroll continuously. |
| fromStart | boolean | No | true | Whether the text scrolls from the start. |
| src | string | Yes | - | Text to scroll. |
| start | boolean | Yes| - | Whether to start scrolling.|
| step | number | No| 6 | Scrolling step.|
| loop | number | No| -1 | Number of times the marquee will scroll. If the value is less than or equal to **0**, the marquee will scroll continuously.|
| fromStart | boolean | No| true | Whether the text scrolls from the start.|
| src | string | Yes| - | Text to scroll.|
## Events
| Name | Description |
| Name| Description|
| -------- | -------- |
| onStart(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee starts scrolling. |
| onBounce(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee has reached the end. |
| onFinish(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee has finished scrolling. |
| onStart(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee starts scrolling.|
| onBounce(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee has reached the end.|
| onFinish(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee has finished scrolling.|
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct MarqueeExample {
......@@ -63,6 +65,7 @@ struct MarqueeExample {
fromStart: this.fromStart,
src: this.src
})
.width(400)
.fontColor(Color.White)
.fontSize(50)
.allowScale(false)
......
# Search
The **\<Search>** component provides an input area for users to search.
> **NOTE**
>
> 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
......@@ -24,7 +24,7 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll
| -------- | -------- | -------- | -------- | -------- |
| value | string | No| - | Text input in the search text box. |
| 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. |
......@@ -36,7 +36,6 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll
| placeholderColor | [ResourceColor](../../ui/ts-types.md) | - | Placeholder text color. |
| placeholderFont | [Font](../../ui/ts-types.md) | - | Placeholder text style. |
| 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
......
......@@ -21,13 +21,14 @@ This component contains the child component [\<ListItem>](ts-container-listitem.
## APIs
List(value:{space?: number, initialIndex?: number})
List(value:{space?: number | string, initialIndex?: number, scroller?: Scroller})
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| space | number | No | 0 | Spacing between list items. |
| initialIndex | number | No | 0 | Item displayed at the beginning of the component when the current list is loaded for the first time, that is, the first item to be displayed. If the configured sequence number is greater than the sequence number of the last item, the setting does not take effect. |
| space | number&nbsp;\|&nbsp;string | No | 0 | Spacing between list items. |
| initialIndex | number | No | 0 | Item displayed at the beginning of the viewport when the current list is loaded for the first time, that is, the first item to be displayed. If the value set is greater than the sequence number of the last item, the setting does not take effect. |
| scroller | [Scroller](ts-container-scroll.md#scroller) | No | - | Controller bound to the list to control the scrolling. |
## Attributes
......@@ -36,8 +37,8 @@ List(value:{space?: number, initialIndex?: number})
| -------- | -------- | -------- | -------- |
| listDirection | [Axis](ts-appendix-enums.md#axis-enums) | Vertical | Direction in which the list items are arranged. For details, see **Axis** enums. |
| divider | {<br>strokeWidth: Length,<br>color?:Color,<br>startMargin?: Length,<br>endMargin?: Length<br>} | - | Style of the divider for the list items. By default, there is no divider.<br>**strokeWidth**: stroke width of the divider.<br>**color**: color of the divider.<br>**startMargin**: distance between the divider and the start of the list.<br>**endMargin**: distance between the divider and the end of the list. |
| editMode | boolean | false | Whether the **&lt;List&gt;** component is in editable mode. |
| edgeEffect | EdgeEffect | EdgeEffect.Spring | Sliding effect. For details, see EdgeEffect enums. |
| editMode | boolean | false | Whether the **\<List>** component is in editable mode. |
| edgeEffect | EdgeEffect | EdgeEffect.Spring | Sliding effect. For details, see **EdgeEffect enums**. |
| chainAnimation | boolean | false | Whether to display chained animations on this list when it slides or its top and bottom are dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.<br>- **false**: No chained animations are displayed.<br>- **true**: Chained animations are displayed. |
| multiSelectable<sup>8+</sup> | boolean | false | Whether to enable mouse frame selection.<br>- **false**: The mouse frame selection is disabled.<br>- **true**: The mouse frame selection is enabled. |
| restoreId<sup>8+</sup> | number | - | Migration ID of the component. During application migration, the status of the component is migrated to the component with the same migration ID on the peer end.<br>For a **<\List>** component, the status includes the item serial number displayed at the start position. |
......@@ -48,7 +49,7 @@ List(value:{space?: number, initialIndex?: number})
| Name | Description |
| -------- | -------- |
| Spring | Similar to the physical dynamic effect of a spring. After scrolling to the edge, the user can continue to scroll for a distance based on the initial speed or by touching the knob of the scrollbar. After the user releases their hand, the knob is rebounded. |
| None | No effect after the scrollbar is moved to the edge. |
| None | No effect when the list is scrolled to the edge. |
- ListItemAlign enums
......@@ -64,7 +65,8 @@ List(value:{space?: number, initialIndex?: number})
| Name | Description |
| -------- | -------- |
| onItemDelete(index: number) =&gt; boolean | Triggered when a list item is deleted. |
| onScrollIndex(firstIndex: number, lastIndex: number) =&gt; void | Triggered when the start position and end position of the current list are changed. |
| onScrollBegin<sup>9+</sup>(dx: number, dy: number)&nbsp;=&gt;&nbsp;{ dxRemain: number, dyRemain: number } | Triggered when scrolling starts.<br/>Parameters:<br/>- **dx**: amount by which the list will scroll in the horizontal direction.<br/>- **dy**: amount by which the list will scroll in the vertical direction.<br/>Return value:<br/>- **dxRemain**: remaining amount by which the list can scroll in the horizontal direction.<br/>- **dyRemain**: remaining amount by which the list can scroll in the vertical direction. |
| onScrollIndex(firstIndex:&nbsp;number,&nbsp;lastIndex:&nbsp;number)&nbsp;=&gt;&nbsp;void | Triggered when the start position and end position of the current list are changed. |
> **NOTE**
>
......@@ -106,9 +108,9 @@ struct ListExample {
}.editable(true)
}, item => item)
}
.listDirection(Axis.Vertical) // Arrangement direction
.divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // Divider line
.edgeEffect(EdgeEffect.None) // No effect when sliding to the edge
.listDirection(Axis.Vertical) // Direction in which the list items are arranged.
.divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // Style of the divider for the list items.
.edgeEffect(EdgeEffect.None) // No effect when the list is scrolled to the edge.
.chainAnimation(false) // Chained animations are disabled.
.onScrollIndex((firstIndex: number, lastIndex: number) => {
console.info('first' + firstIndex)
......@@ -166,7 +168,7 @@ struct ListLanesExample {
.lanes({ minLength: 40, maxLength: 60 })
.alignListItem(this.alignListItem)
Button("Change alignListItem: "+ this.alignListItem).onClick(() => {
Button("Change alignListItem:" + this.alignListItem).onClick(() => {
if (this.alignListItem == ListItemAlign.Start) {
this.alignListItem = ListItemAlign.Center
} else if (this.alignListItem == ListItemAlign.Center) {
......@@ -179,3 +181,4 @@ struct ListLanesExample {
}
}
```
# Action Sheet
> **NOTE**<br>
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
......@@ -17,25 +18,25 @@ None
show(options: { paramObject1})
Defines and shows the action sheet.
Defines and shows an action sheet.
- paramObject1 parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| title | string \|[Resource](../../ui/ts-types.md#resource) | No | None | Title of the dialog box. |
| message | string \|[Resource](../../ui/ts-types.md#resource) | | | Content of the dialog box. |
| title | string \|[Resource](../../ui/ts-types.md) | No | None | Title of the dialog box. |
| message | string \|[Resource](../../ui/ts-types.md) | | | Content of the dialog box. |
| autoCancel | boolean | No | true | Whether to close the dialog box when the overlay is clicked. |
| confirm | {<br/>value: string \|[Resource](../../ui/ts-types.md#resource),<br>action: () =&gt; void<br/>} | number | string | Text content of the confirm button and callback upon button clicking.<br/>**value**: button text.<br/>**action**: callback upon button clicking. |
| confirm | {<br/>value: string \| [Resource](../../ui/ts-types.md),<br/>action: () =&gt; void<br/>} | No | - | Text content of the confirm button and callback upon button clicking.<br/>**value**: button text.<br/>**action**: callback upon button clicking. |
| cancel | () =&gt; void | No | - | Callback invoked when the dialog box is closed after the overlay is clicked. |
| alignment | DialogAlignment | No | DialogAlignment.Default | Alignment mode of the dialog box in the vertical direction. |
| offset | {<br/>dx: Length\|[Resource](../../ui/ts-types.md#resource)<br/>dy: Length\|[Resource](../../ui/ts-types.md#resource)<br/>} | No | - | Offset of the dialog box relative to the alignment position. |
| sheets | Array&lt;SheetInfo&gt; | Yes | - | Options in the dialog box. Each option supports the image, text, and callback. |
| alignment | [DialogAlignment](ts-methods-custom-dialog-box.md) | No | DialogAlignment.Default | Alignment mode of the dialog box in the vertical direction. |
| offset | {<br/>dx: Length,<br/>dy: Length<br/>} | No | {<br/>dx: 0,<br/>dy: 0<br/>} | Offset of the dialog box relative to the alignment position. |
| sheets | Array<SheetInfo&gt; | Yes | - | Options in the dialog box. Each option supports the image, text, and callback. |
- SheetInfo parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| title | string | Yes | - | Sheet text. |
| icon | string | No | None | Sheet icon. |
| title | string \| [Resource](../../ui/ts-types.md) | Yes | - | Sheet text. |
| icon | string \| [Resource](../../ui/ts-types.md) | No | None | Sheet icon. |
| action | ()=&gt;void | Yes | - | Callback when the sheet is selected. |
......@@ -43,10 +44,11 @@ Defines and shows the action sheet.
```
```ts
// xxx.ets
@Entry
@Component
struct ActionSheetExapmle {
struct ActionSheetExample {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button('Click to Show ActionSheet')
......
# Alert Dialog Box
> **NOTE**<br>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> **NOTE**
>
> This method is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **<AlertDialog\>** component is used to display an alert dialog box. You can set the text content and response callback for an alert dialog box as needed.
......@@ -10,40 +11,41 @@ The **<AlertDialog\>** component is used to display an alert dialog box. You can
## Attributes
| Name | Type | Default Value | Description |
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| show | options: { paramObject1\| paramObject2} | - | Defines and displays the **<AlertDialog\>** component. |
| show | options: { paramObject1 \| paramObject2} | - | Defines and displays the **<AlertDialog\>** component. |
- paramObject1 parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| title | string \|[Resource](../../ui/ts-types.md#resource) | | | Title of a dialog box. |
| message | string \|[Resource](../../ui/ts-types.md#resource) | | | Content of the dialog box. |
| title | string \| [Resource](../../ui/ts-types.md) | No | - | Title of a dialog box. |
| message | string \| [Resource](../../ui/ts-types.md) | Yes | - | Content of the dialog box. |
| autoCancel | boolean | No | true | Whether to close the dialog box when the overlay is clicked. |
| confirm | {<br/>value: string \|[Resource](../../ui/ts-types.md#resource),<br>fontColor?: Color\|number \|string \|[Resource](../../ui/ts-types.md#resource),<br/>backgroundColor?:Color \|number\|string\|[Resource](../../ui/ts-types.md#resource),<br>action: () =&gt; void<br/>} <br/> | | | Text content, text color, background color, and click callback of the confirm button. |
| confirm | {<br/>value: string \| [Resource](../../ui/ts-types.md),<br>fontColor?: Color\| number \| string \| [Resource](../../ui/ts-types.md),<br/>backgroundColor?:Color \| number \| string \| [Resource](../../ui/ts-types.md),<br>action: () =&gt; void<br/>} <br/> | No | - | Text content, text color, background color, and click callback of the confirm button. |
| cancel | () =&gt; void | No | - | Callback invoked when the dialog box is closed after the overlay is clicked. |
| alignment | DialogAlignment | No | DialogAlignment.Default | Alignment mode of the dialog box in the vertical direction. |
| offset | {<br/>dx: Length \|[Resource](../../ui/ts-types.md#resource),<br/>dy: Length \|[Resource](../../ui/ts-types.md#resource)<br/>} | | | Offset of the dialog box relative to the alignment position. |
| alignment | [DialogAlignment](ts-methods-custom-dialog-box.md) | No | DialogAlignment.Default | Alignment mode of the dialog box in the vertical direction. |
| offset | {<br/>dx: Length \| [Resource](../../ui/ts-types.md),<br/>dy: Length \| [Resource](../../ui/ts-types.md)<br/>} | No | - | Offset of the dialog box relative to the alignment position. |
| gridCount | number | No | - | Number of grid columns occupied by the width of the dialog box. |
- paramObject2 parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| title | string \|[Resource](../../ui/ts-types.md#resource) | No | - | Title of a dialog box. |
| message | string \|[Resource](../../ui/ts-types.md#resource) | Yes | - | Content of the dialog box. |
| title | string \| [Resource](../../ui/ts-types.md) | No | - | Title of a dialog box. |
| message | string \| [Resource](../../ui/ts-types.md) | Yes | - | Content of the dialog box. |
| autoCancel | boolean | No | true | Whether to close the dialog box when the overlay is clicked. |
| primaryButton | {<br/>value: string \|[Resource](../../ui/ts-types.md#resource),<br>fontColor?: Color\|number \|string \|[Resource](../../ui/ts-types.md#resource),<br/>backgroundColor?:Color \|number\|string\|[Resource](../../ui/ts-types.md#resource),<br>action: () =&gt; void<br/>} <br/> | | | Text content, text color, background color, and click callback of the primary button. |
| secondaryButton | {<br/>value: string \|[Resource](../../ui/ts-types.md#resource),<br>fontColor?: Color\|number \|string \|[Resource](../../ui/ts-types.md#resource),<br/>backgroundColor?:Color \|number\|string\|[Resource](../../ui/ts-types.md#resource),<br>action: () =&gt; void<br/>} <br/> | | | Text content, text color, background color, and click callback of the secondary button. |
| primaryButton | {<br/>value: string \| [Resource](../../ui/ts-types.md),<br>fontColor?: Color \| number \| string \| [Resource](../../ui/ts-types.md),<br/>backgroundColor?:Color \| number\| string\| [Resource](../../ui/ts-types.md),<br>action: () =&gt; void<br/>} <br/> | No | - | Text content, text color, background color, and click callback of the primary button. |
| secondaryButton | {<br/>value: string \|[Resource](../../ui/ts-types.md),<br>fontColor?: Color \| number \| string \| [Resource](../../ui/ts-types.md),<br/>backgroundColor?:Color \| number\| string\| [Resource](../../ui/ts-types.md),<br>action: () =&gt; void<br/>} <br/> | No | - | Text content, text color, background color, and click callback of the secondary button. |
| cancel | () =&gt; void | No | - | Callback invoked when the dialog box is closed after the overlay is clicked. |
| alignment | DialogAlignment | No | DialogAlignment.Default | Alignment mode of the dialog box in the vertical direction. |
| offset | {<br/>dx: Length \|[Resource](../../ui/ts-types.md#resource),<br/>dy: Length \|[Resource](../../ui/ts-types.md#resource)<br/>} | | | Offset of the dialog box relative to the alignment position. |
| alignment | [DialogAlignment](ts-methods-custom-dialog-box.md) | No | DialogAlignment.Default | Alignment mode of the dialog box in the vertical direction. |
| offset | {<br/>dx: Length \| [Resource](../../ui/ts-types.md),<br/>dy: Length \| [Resource](../../ui/ts-types.md)<br/>} | No | - | Offset of the dialog box relative to the alignment position. |
| gridCount | number | No | - | Number of grid columns occupied by the width of the dialog box. |
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct AlertDialogExample {
......
# Transition of Shared Elements
Shared element transition can be used for transition between pages, for example, transition from an image on the current page to the next page.
> **NOTE**
>
> This animationis supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
Transition of shared elements can be used for transition between pages, for example, transition from an image on the current page to the next page.
## Type
## Attributes
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| sharedTransition | id: string,<br/>options?: Object | - | If the same ID is configured for a component on the two pages, this shared component is transited. If this parameter is set to an empty string, no shared elements are transited. |
- options parameters
| Name | Type | Default Value | Mandatory | Description |
| Name | Type | Default Value | Mandatory | Description |
| -------- | -------- | -------- | -------- | -------- |
| duration | number | 1000 | No | Animation duration, in ms. The default duration is 1000 ms. |
| curve | Curve \| Curves | Linear | No | The default curve is linear. For details about the valid values, see **Curve enums**. |
......
# Border
You can set border styles for components.
> **NOTE**
>
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>
> The border of a component is displayed above the content of its child components since API version 9.
You can set border styles for components.
## Required Permissions
None
## Attributes
......@@ -27,11 +31,25 @@ None
| -------- | -------- | -------- | -------- | -------- |
| width | [Length](../../ui/ts-types.md) | 0 | No| Border width.|
| color | [ResourceColor](../../ui/ts-types.md) | 'Black' | No| Border color.|
| radius | [Length](../../ui/ts-types.md) | 0 | No| Border radius.|
| radius | [Length](../../ui/ts-types.md)\| EdgeRadiuses<sup>9+</sup> | 0 | No| Border radius.|
| style | BorderStyle | BorderStyle.Solid | No| Border style.|
- EdgeRadiuses<sup>9+</sup>
To reference this object, at least one parameter must be passed.
| Name | Type| Mandatory| Default Value| Description |
| ----------- | -------- | ---- | ------ | ---------------- |
| topLeft | length | No | 0 | Radius of the upper-left rounded corner.|
| topRight | length | No | 0 | Radius of the upper-right rounded corner.|
| bottomLeft | length | No | 0 | Radius of the lower-left rounded corner.|
| bottomRight | length | No | 0 | Radius of the lower-right rounded corner.|
- BorderStyle enums
| Name| Description|
| -------- | -------- |
| Dotted | Dotted border. The radius of a dot is half of **borderWidth**.|
......@@ -52,6 +70,10 @@ struct BorderExample {
Text('dashed')
.borderStyle(BorderStyle.Dashed).borderWidth(5).borderColor(0xAFEEEE).borderRadius(10)
.width(120).height(120).textAlign(TextAlign.Center).fontSize(16)
Text('dashed')
.borderStyle(BorderStyle.Dashed).borderWidth(5).borderColor(0xAFEEEE)
.borderRadius({ topLeft: 10, topRight: 20, bottomLeft: 30, bottomRight: 60 })
.width(120).height(120).textAlign(TextAlign.Center).fontSize(16)
// Dotted border
Text('dotted')
.border({ width: 5, color: 0x317AF7, radius: 10, style: BorderStyle.Dotted })
......
# Menu Control
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
This module provides APIs for binding a menu – a vertical list of items – to a component. This menu is displayed by long-pressing, clicking, or right-clicking the component.
> **NOTE**
>
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
......@@ -12,29 +15,30 @@ None
## Attributes
| Name | Type | Default Value | Description |
| ---------------------------- | ---------------------------------------- | ------------- | ---------------------------------------- |
| bindMenu | Array<MenuItem&gt; \| [CustomBuilder](../../ui/ts-types.md)<sup>8+</sup> | - | Menu bound to the component, which is displayed when you click the component. Textual and custom menu items are supported. |
| bindContextMenu<sup>8+</sup> | content: [CustomBuilder](../../ui/ts-types.md)<br>responseType: ResponseType | - | Context menu bound to the component, which is displayed when you long-press or right-click the component. Only custom menu items are supported. |
| Name | Type | Default Value | Description |
| ---------------------------- | ---------------------------------------- | ---- | ---------------------------------- |
| bindMenu | Array<MenuItem&gt;&nbsp;\|&nbsp;[CustomBuilder](../../ui/ts-types.md)<sup>8+</sup> | - | Menu bound to the component, which is displayed when you click the component. Textual and custom menu items are supported.|
| bindContextMenu<sup>8+</sup> | content:&nbsp;[CustomBuilder](../../ui/ts-types.md),<br>responseType:&nbsp;ResponseType | - | Context menu bound to the component, which is displayed when you long-press or right-click the component. Only custom menu items are supported. |
- MenuItem
| Name | Type | Description |
| ------ | ------------- | ---------------------------------------- |
| value | string | Menu item text. |
| action | () =&gt; void | Action triggered when a menu item is clicked. |
| Name | Type | Description |
| ------ | ----------------------- | ----------- |
| value | string | Menu item text. |
| action | ()&nbsp;=&gt;&nbsp;void | Action triggered when a menu item is clicked.|
- ResponseType<sup>8+</sup>
| Value | Description |
| ---------- | ---------------------------------------- |
| LongPress | The menu is displayed when the component is long-pressed. |
| RightClick | The menu is displayed when the component is right-clicked. |
| Value | Description |
| ---------- | ------------- |
| LongPress | The menu is displayed when the component is long-pressed. |
| RightClick | The menu is displayed when the component is right-clicked.|
## Example
#### Menu with Textual Menu Items
```
```ts
// xxx.ets
@Entry
@Component
struct MenuExample {
......@@ -66,7 +70,8 @@ struct MenuExample {
#### Menu with Custom Menu Items
```
```ts
// xxx.ets
import router from '@system.router';
@Entry
......@@ -116,7 +121,8 @@ struct MenuExample {
#### Context Menu (Displayed Upon Right-Clicking)
```
```ts
// xxx.ets
@Entry
@Component
struct ContextMenuExample {
......
# Shape Clipping
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
......@@ -13,16 +14,17 @@ None
## Attributes
| Name | Type | Default Value | Description |
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| clip | Shape \| boolean | false | Specifies a clip mode. The value **Shape** indicates that the current component is cropped based on the specified shape. The value **boolean** specifies whether to clip the component based on the edge outline. |
| mask | Shape | - | Adds a mask of the specified shape to the current component. |
| clip | Shape \| boolean | false | Clip mode. The value **Shape** indicates that the current component is cropped based on the specified shape. The value **boolean** specifies whether to clip the component based on the edge outline. |
| mask | Shape | - | Mask of the specified shape for the current component. |
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct ClipAndMaskExample {
......@@ -30,24 +32,24 @@ struct ClipAndMaskExample {
Column({ space: 5 }) {
Text('clip').fontSize(9).width('90%').fontColor(0xCCCCCC)
// Clip the image by using a circle with a diameter of 280px.
Image('/comment/bg.jpg')
Image($r('app.media.example'))
.clip(new Circle({ width: 80, height: 80 }))
.width('500px').height('280px')
Row() {
Image('/comment/bg.jpg').width('500px').height('280px')
Image($r('app.media.example')).width('500px').height('280px')
}
.clip(true)
.borderRadius(20)
Text('mask').fontSize(9).width('90%').fontColor(0xCCCCCC)
// Add a 500 px x 280 px mask to the image.
Image('/comment/bg.jpg')
Image($r('app.media.example'))
.mask(new Rect({ width: '500px', height: '280px' }).fill(Color.Gray))
.width('500px').height('280px')
// Add a 280 px x 280 px circle mask to the image.
Image('/comment/bg.jpg')
Image($r('app.media.example'))
.mask(new Circle({ width: '280px', height: '280px' }).fill(Color.Gray))
.width('500px').height('281px')
}
......
# Click Event
A click event is triggered when a component is clicked.
> **NOTE**<br>
> **NOTE**
>
> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
......@@ -12,12 +13,12 @@ None
## Events
| Name | Bubble Supported | Description |
| Name | Bubbling Supported | Description |
| -------- | -------- | -------- |
| onClick(callback: (event?: ClickEvent) =&gt; void) | No | Called when a click event occurs. For details about the event parameters, see [ClickEvent](#clickevent). |
### ClickEvent
## ClickEvent
| Name | Type | Description |
| -------- | -------- | -------- |
......@@ -25,30 +26,30 @@ None
| screenY | number | Y coordinate of the click relative to the upper edge of the screen. |
| x | number | X coordinate of the click relative to the left edge of the component being clicked. |
| y | number | Y coordinate of the click relative to the upper edge of the component being clicked. |
| target<sup>8+</sup> | EventTarget | Target element that is clicked. |
| target<sup>8+</sup> | [EventTarget](#eventtarget8) | Target element that is clicked. |
| timestamp | number | Timestamp of the event. |
- EventTarget<sup>8+</sup> attributes
## EventTarget<sup>8+</sup>
| Name | Type | Description |
| -------- | -------- | -------- |
| area | Area | Area information of the target element.|
| Name | Type | Description |
| -------- | -------- | -------- |
| area | [Area](#area8) | Area information of the target element.|
- Area<sup>8+</sup> attributes
## Area<sup>8+</sup>
| Name | Type | Description |
| -------- | -------- | -------- |
| width | number | Width of the target element, in vp. |
| height | number | Height of the target element, in vp. |
| position | Position | Position of the upper left corner of the target element relative to that of the parent element. |
| globalPosition | Position | Position of the upper left corner of the target element relative to that of the page. |
| Name | Type | Description |
| -------- | -------- | -------- |
| width | number | Width of the target element, in vp. |
| height | number | Height of the target element, in vp. |
| position | [Position](#position8) | Position of the upper left corner of the target element relative to that of the parent element. |
| globalPosition | [Position](#position8) | Position of the upper left corner of the target element relative to that of the page. |
- Position<sup>8+</sup> attributes
## Position<sup>8+</sup>
| Name | Type | Description |
| -------- | -------- | -------- |
| x | number | X-coordinate, in vp. |
| y | number | Y-coordinate, in vp. |
| Name | Type | Description |
| -------- | -------- | -------- |
| x | number | X-coordinate, in vp. |
| y | number | Y-coordinate, in vp. |
## Example
......
# Drag/Drop Event
# Drag Event
A drag event is triggered when a component is dragged.
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Events
| Name | Bubble Supported | Description |
| Name | Bubbling Supported | Description |
| -------- | -------- | -------- |
| onDragStart(callback: (event: DragEvent, extraParams?: string) =&gt;\|[Custom Builder](../../ui/ts-types.md)) | No | Triggered when the component bound to the event is dragged for the first time.<br/>-**event**: information about the drag event, including the coordinates of the item that is being dragged.<br/>-**extraParams**: additional information about the drag event. For details, see extraParam.<br/>Return value: object being dragged, which is used for prompts displayed when the object is dragged.<br/>**NOTE**<br/>> - A drag event can be triggered by a 150 ms long press.<br/>> - If the duration of a long-press gesture is set to less than or equal to 150 ms, the callback for the long-press gesture takes precedence. Otherwise, the callback for the drag event takes precedence. |
| onDragEnter(callback: (event: DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item enters a valid drop target.<br/>-**event**: information about the drag event, including the coordinates of the item that is being dragged.<br/>-**extraParams**: additional information about the drag event. For details, see extraParam.<br/>**NOTE**<br/>This event is valid only when the **onDrop** event is listened to. |
| onDragMove(callback: (event: DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item moves in a valid drop target.<br/>-**event**: information about the drag event, including the coordinates of the item that is being dragged.<br/>-**extraParams**: additional information about the drag event. For details, see extraParam.<br/>**NOTE**<br/>This event is valid only when the **onDrop** event is listened to. |
| onDragLeave(callback: (event: DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item leaves a valid drop target.<br/>-**event**: information about the drag event, including the coordinates of the item that is being dragged.<br/>-**extraParams**: additional information about the drag event. For details, see extraParam.<br/>**NOTE**<br/>This event is valid only when the **onDrop** event is listened to. |
| onDrop(callback: (event:DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item is dropped on a valid drop target.<br/>-**event**: information about the drag event, including the coordinates of the item that is being dragged.<br/>-**extraParams**: additional information about the drag event. For details, see extraParam. |
| onDragStart(callback: (event: DragEvent, extraParams?: string) =&gt;\|[Custom Builder](../../ui/ts-types.md)) | No | Triggered when the component bound to the event is dragged for the first time.<br/>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br/>- **extraParams**: additional information about the drag event. For details, see **extraParam**.<br/>Return value: object being dragged, which is used for prompts displayed when the object is dragged.<br/>A drag event can be triggered by a 150 ms long press.<br/>If the duration of a long-press gesture is set to less than or equal to 150 ms, the callback for the long-press gesture takes precedence. Otherwise, the callback for the drag event takes precedence. |
| onDragEnter(callback: (event: DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item enters a valid drop target.<br/>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br/>- **extraParams**: additional information about the drag event. For details, see **extraParam**.<br/>This event is valid only when the **onDrop** event is listened to. |
| onDragMove(callback: (event: DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item moves in a valid drop target.<br/>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br/>- **extraParams**: additional information about the drag event. For details, see **extraParam**.<br/>This event is valid only when the **onDrop** event is listened to. |
| onDragLeave(callback: (event: DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item leaves a valid drop target.<br/>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br/>- **extraParams**: additional information about the drag event. For details, see **extraParam**.<br/>This event is valid only when the **onDrop** event is listened to. |
| onDrop(callback: (event:DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item is dropped on a valid drop target.<br/>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br/>- **extraParams**: additional information about the drag event. For details, see **extraParam**. |
- extraParam
Returns additional information required for dragging an item.
**extraParam** is a string converted from a JSON object. You can obtain the following attributes using the JSON object converted from **Json.parse**.
| Name | Type | Description |
| -------- | -------- | -------- |
| selectedIndex | number | Index of the dragged item in the parent container. The value of **selectedindex** starts from **0**.<br/>**NOTE**<br/>This attribute is valid only in the **ListItem** component. |
| insertIndex | number | Index of the element into which the dragged item is dropped in the **List** component. The value of **insertIndex** starts from **0**.<br/>**NOTE**<br/>This attribute is valid only in the drag event of the **List** component. |
| selectedIndex | number | Index of the dragged item in the parent container. The value of **selectedIndex** starts from **0**.<br/>This attribute is valid only in the **\<ListItem>** component. |
| insertIndex | number | Index of the element into which the dragged item is dropped in the **List** component. The value of **insertIndex** starts from **0**.<br/>This attribute is valid only in the drag event of the **\<List>** component. |
### DragEvent
......
# Key Event
A key event is triggered when a component interacts with a keyboard, remote control, or any other input device with keys.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> This method is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> **NOTE**
>
> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
......@@ -12,58 +14,61 @@ None
## Events
| Name | Bubble Supported | Description |
| Name | Bubbling Supported | Description |
| -------- | -------- | -------- |
| onKeyEvent(event: (event?: KeyEvent) =&gt; void) | Yes | Called when a key event occurs. For details about the event parameters, see [KeyEvent Object](#KeyEvent Object). |
| onKeyEvent(event: (event?: KeyEvent) =&gt; void) | Yes | Called when a key event occurs. For details about **event**, see [KeyEvent](#keyevent). |
### KeyEvent Object
## KeyEvent
- Attributes
| Name | Type | Description |
| Name | Type | Description |
| -------- | -------- | -------- |
| type | KeyType | Type of a key. |
| keyCode | number | Key code. |
| keyText | string | Key value. |
| keySource | KeySource | Type of the input device that triggers the key event. |
| deviceId | number | ID of the input device that triggers the key event. |
| metaKey | number | State of the metakey when the key is pressed. The value **1** means the pressed state, and **0** means the unpressed state. |
| timestamp | number | Timestamp when the key is pressed. |
| type | [KeyType](#keytype-enums) | Type of a key. |
| keyCode | number | Key code. |
| keyText | string | Key value. |
| keySource | [KeySource](#keysource-enums) | Type of the input device that triggers the key event. |
| deviceId | number | ID of the input device that triggers the key event. |
| metaKey | number | State of the metakey when the key is pressed. The value **1** means the pressed state, and **0** means the unpressed state. |
| timestamp | number | Timestamp when the key is pressed. |
- APIs
| Name | Description |
| Name | Description |
| -------- | -------- |
| stopPropagation(): void | Stops the event from bubbling upwards or downwards. |
| stopPropagation(): void | Stops the event from bubbling upwards or downwards. |
- KeyType enums
| Name | Description |
| -------- | -------- |
| Down | The key is pressed. |
| Up | The key is released. |
## KeyType Enums
| Name | Description |
| -------- | -------- |
| Down | The key is pressed. |
| Up | The key is released. |
- KeySource enums
| Name | Description |
| -------- | -------- |
| Unknown | Unknown input device. |
| Keyboard | The input device is a keyboard. |
- Common KeyCode description
| Value | Behavior | Physical Button |
| -------- | -------- | -------- |
| 19 | Upward | Up button. |
| 20 | Downward | Down button. |
| 21 | Leftward | Left button. |
| 22 | Rightward | Right button. |
| 23 | OK | **OK** key on a remote control. |
| 66 | OK | **Enter** key on a keyboard. |
| 160 | OK | **Enter** button on the numeric keypad. |
## KeySource Enums
| Name | Description |
| -------- | -------- |
| Unknown | Unknown input device. |
| [KeyCode](#common-keycode-enums) | The input device is a keyboard. |
## Common KeyCode Enums
| Value | Behavior | Physical Button |
| -------- | -------- | -------- |
| 19 | Upward | Up button. |
| 20 | Downward | Down button. |
| 21 | Leftward | Left button. |
| 22 | Rightward | Right button. |
| 23 | OK | **OK** key on a remote control. |
| 66 | OK | **Enter** key on a keyboard. |
| 160 | OK | **Enter** button on the numeric keypad. |
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct KeyEventExample {
......
# Touch Event
A touch event is triggered when a finger is pressed, slides, or is lifted from a component.
> **NOTE**<br>
> **NOTE**
>
> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
......@@ -12,51 +14,51 @@ None
## Events
| Name | Pop-up | Description |
| -------- | -------- | -------- |
| onTouch(callback: (event?: TouchEvent) =&gt; void) | Yes | Invoked when a touch action is triggered. For details about the event parameters, see [TouchEvent](#touchevent). |
| Name | Bubbling Supported| Description |
| ---------------------------------------- | ---- | ---------------------------------------- |
| onTouch(callback:&nbsp;(event?:&nbsp;TouchEvent)&nbsp;=&gt;&nbsp;void) | Yes | Invoked when a touch action is triggered. For details about **event**, see [TouchEvent](#touchevent).|
### TouchEvent
## TouchEvent
- Attributes
| Name | Type | Description |
| -------- | -------- | -------- |
| type | TouchType | Type of a touch event. |
| touches | Array&lt;TouchObject&gt; | All finger information. |
| changedTouches | Array&lt;TouchObject&gt; | Finger information changed. |
| timestamp | number | Timestamp of the event. |
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md) | Target of the event. |
| Name | Type | Description |
| ------------------- | ---------------------------------------- | ------------ |
| type | TouchType | Type of the touch event. |
| touches | Array&lt;[TouchObject](#touchobject)&gt; | All finger information. |
| changedTouches | Array&lt;[TouchObject](#touchobject)&gt; | Finger information changed.|
| timestamp | number | Timestamp of the event. |
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md#eventtarget8) | Target of the event. |
- APIs
| Name | Description |
| -------- | -------- |
| stopPropagation(): void | Pop-up of the stop event. |
| Name | Description |
| ---------------------- | ------- |
| stopPropagation(): void| Stops the event from bubbling upwards or downwards.|
- TouchObject
| Name | Type | Description |
| -------- | -------- | -------- |
| type | TouchType | Type of a touch event. |
| id | number | Unique identifier of a finger. |
| screenX | number | X coordinate of the touch point relative to the left edge of the screen. |
| screenY | number | Y coordinate of the touch point relative to the upper edge of the device screen. |
| x | number | X coordinate of the touch point relative to the left edge of the element to touch. |
| y | number | Y coordinate of the touch point relative to the upper edge of the element to touch. |
## TouchObject
| Name | Type | Description |
| ------- | --------------------------- | ------------------- |
| type | [TouchType](#touchtype-enums) | Type of the touch event. |
| id | number | Unique identifier of a finger. |
| screenX | number | X-coordinate of the touch point relative to the left edge of the screen. |
| screenY | number | Y-coordinate of the touch point relative to the upper edge of the device screen. |
| x | number | X-coordinate of the touch point relative to the left edge of the element being touched. |
| y | number | Y-coordinate of the touch point relative to the upper edge of the element being touched. |
- TouchType
| Name | Description |
| -------- | -------- |
| Down | Trigger a touch event when a finger is pressed. |
| Up | Trigger a touch event when a finger is lifted. |
| Move | Trigger a touch event when a finger moves on the screen in pressed state. |
| Cancel | Trigger an event when a touch event is canceled. |
## TouchType Enums
| Name | Description |
| ------ | --------------- |
| Down | A finger is pressed. |
| Up | A finger is lifted. |
| Move | A finger moves on the screen in pressed state.|
| Cancel | A touch event is canceled. |
## Example
```ts
// xxx.ets
@Entry
......
# Mouse Event
If an action triggers multiple events, the order of these events is fixed. By default, mouse events are transmitted transparently.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
......@@ -12,48 +14,47 @@ None
## Events
| Name | Bubble Supported | Description |
| Name | Bubbling Supported | Description |
| -------- | -------- | -------- |
| onHover(callback: (isHover: boolean) =&gt; void) | No | Triggered when the mouse cursor enters or leaves the component.<br/>**isHover**: whether the mouse cursor hovers over the component. The value **true** means that the mouse cursor enters the component, and the value **false** means that the mouse cursor leaves the component. |
| onMouse(callback: (event?: MouseEvent) =&gt; void) | Yes | Triggered when the component is clicked by a mouse button or the mouse cursor moves on the component. The **event** parameter indicates the timestamp, mouse button, action, coordinates of the clicked point on the entire screen, and coordinates of the clicked point relative to the component when the event is triggered. |
### MouseEvent
- Attributes
| Name | Type | Description |
| -------- | -------- | -------- |
| timestamp | number | Timestamp when the event is triggered. |
| screenX | number | X-coordinate of the clicked point relative to the upper left corner of the screen. |
| screenY | number | Y-coordinate of the clicked point relative to the upper left corner of the screen. |
| x | number | X-coordinate of the clicked point relative to the upper left corner of the component. |
| y | number | Y-coordinate of the clicked point relative to the upper left corner of the component. |
| button | MouseButton | Mouse button. |
| action | MouseAction | Event action. |
- MouseButton attributes
| Name | Type | Description |
| -------- | -------- | -------- |
| Left | number | Left mouse button. |
| Right | number | Right mouse button. |
| Middle | number | Middle mouse button. |
| Back | number | Back button on the left of the mouse. |
| Forward | number | Forward button on the left of the mouse. |
| None | number | No button. |
- MouseAction attributes
| Name | Type | Description |
| -------- | -------- | -------- |
| Press | number | The mouse button is pressed. |
| Release | number | The mouse button is released. |
| Move | number | The mouse cursor moves. |
| onHover(callback: (isHover: boolean) =&gt; void) | No | Triggered when the mouse cursor enters or leaves the component.<br/>**isHover**: whether the mouse cursor hovers over the component. The value **true** means that the mouse cursor enters the component, and the value **false** means that the mouse cursor leaves the component. |
| onMouse(callback: (event?: MouseEvent) =&gt; void) | Yes | Triggered when the component is clicked by a mouse button or the mouse cursor moves on the component. The **event** parameter indicates the timestamp, mouse button, action, coordinates of the clicked point on the entire screen, and coordinates of the clicked point relative to the component when the event is triggered. |
## MouseEvent
| Name | Type | Description |
| -------- | -------- | -------- |
| timestamp | number | Timestamp when the event is triggered. |
| screenX | number | X-coordinate of the clicked point relative to the upper left corner of the screen. |
| screenY | number | Y-coordinate of the clicked point relative to the upper left corner of the screen. |
| x | number | X-coordinate of the clicked point relative to the upper left corner of the component. |
| y | number | Y-coordinate of the clicked point relative to the upper left corner of the component. |
| button | [MouseButton](#mousebutton) | Mouse button. |
| action | [MouseAction](#mouseaction) | Event action. |
## MouseButton
| Name | Type | Description |
| -------- | -------- | -------- |
| Left | number | Left mouse button. |
| Right | number | Right mouse button. |
| Middle | number | Middle mouse button. |
| Back | number | Back button on the left of the mouse. |
| Forward | number | Forward button on the left of the mouse. |
| None | number | No button. |
## MouseAction
| Name | Type | Description |
| -------- | -------- | -------- |
| Press | number | The mouse button is pressed. |
| Release | number | The mouse button is released. |
| Move | number | The mouse cursor moves. |
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct MouseEventExample {
......
# Permission List
On the basis of the [principles for app permission management](accesstoken-overview.md#basic-principles), apply for permissions for an app by following the procedure illustrated in the figure below.
Before applying for required permissions, read and understand the [permission workflow](accesstoken-overview.md#permission-workflow). Then, determine whether the app can apply for the target permissions based on the table below.
![](figures/permission-application-process.png)
1. For details about the mapping between the app's ability privilege level (APL) and permission level, see [Permission Levels](accesstoken-overview.md#permission-levels).
2. Permissions can be authorized by the user (user_grant) or the system (system_grant). For details, see [Permission Authorization Modes](accesstoken-overview.md#permission-authorization-modes).
3. In principle, an app with a lower APL cannot apply for higher permissions by default. The Access Control List (ACL) makes low-level apps have high-level permissions. For details, see [ACL](accesstoken-overview.md#acl).
The following lists the permissions defined by the system. For details about permission usage examples, see [Access Control Development](accesstoken-guidelines.md).
For details about permission usage examples, see [Access Control Development](accesstoken-guidelines.md).
| Permission | APL | Authorization Mode | Enable ACL| Description |
| -------------------------------------------------------- | ------------ | ------------ | ------- | ------------------------------------------------------------ |
......@@ -26,10 +20,7 @@ The following lists the permissions defined by the system. For details about per
| ohos.permission.REMOVE_CACHE_FILES | system_basic | system_grant | TRUE | Allows the cache of the specified app to be cleared. |
| ohos.permission.REBOOT | system_basic | system_grant | TRUE | Allows an app to restart the device. |
| ohos.permission.RUNNING_LOCK | normal | system_grant | TRUE | Allows an app to obtain a running lock. |
| ohos.permission.ENROLL_BIOMETRIC | system_core | system_grant | FALSE | Allows an app to add or remove biometric data. |
| ohos.permission.ACCESS_BIOMETRIC | normal | system_grant | FALSE | Allows an app to use biometric recognition for identity authentication. |
| ohos.permission.ACCESS_BIOMETRIC_INTERNAL | system_core | system_grant | FALSE | Allows an app to apply for or release biometric recognition resources. |
| ohos.permission.RESET_BIOMETRIC_LOCKOUT | system_core | system_grant | FALSE | Allows an app to reset the maximum number of failures allowed before biometric authentication is locked. |
| ohos.permission.SET_TIME | system_basic | system_grant | TRUE | Allows an app to set the system time. |
| ohos.permission.SET_TIME_ZONE | system_basic | system_grant | TRUE | Allows an app to set the system time zone. |
| ohos.permission.DOWNLOAD_SESSION_MANAGER | system_core | system_grant | TRUE | Allows an app to manage the download sessions. |
......@@ -136,3 +127,5 @@ The following lists the permissions defined by the system. For details about per
| ohos.permission.SET_DEFAULT_APPLICATION | system_core | system_grant | TRUE | Allows an app to set and reset default apps. |
| ohos.permission.MANAGE_DISPOSED_APP_STATUS | system_core | system_grant | TRUE | Allows an app to set and query the app handling state. |
| ohos.permission.ACCESS_IDS | system_core | system_grant | TRUE | Allows an app to query the unique identifier of a device. |
| ohos.permission.DUMP | system_core | system_grant | TRUE | Allows the basic system information and SA service information to be exported. |
| ohos.permission.DISTRIBUTED_SOFTBUS_CENTER | system_basic | system_grant | FALSE | Allows networking between different devices. |
......@@ -62,7 +62,7 @@ struct ComponentA {
@StorageProp('languageCode') lang: string = 'en'
private label: string = 'count'
private aboutToAppear() {
aboutToAppear() {
this.label = (this.lang === 'en') ? 'Number' : 'Count'
}
......
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册