“3e44d2a5662b188f3f1b5ae5d70795030b768531”上不存在“en/application-dev/database/database-storage-overview.md”
提交 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 ...@@ -7,6 +7,8 @@ The distributed data objects allow data across devices to be processed like loca
## Available APIs ## Available APIs
For details about the APIs related to the distributed data object, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md).
### Creating a Distributed Data Object Instance ### Creating a Distributed Data Object Instance
Call **createDistributedObject()** to create a distributed data object instance. You can specify the attributes of the instance in **source**. Call **createDistributedObject()** to create a distributed data object instance. You can specify the attributes of the instance in **source**.
...@@ -15,7 +17,7 @@ Call **createDistributedObject()** to create a distributed data object instance. ...@@ -15,7 +17,7 @@ Call **createDistributedObject()** to create a distributed data object instance.
**Table 1** API for creating a distributed data object instance **Table 1** API for creating a distributed data object instance
| Package| API| Description| | Package| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>-&nbsp;**source**: attributes of the **distributedObject** set.<br>-&nbsp;**DistributedObject**: returns the distributed object created.| | ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>- **source**: attributes of the **distributedObject** set.<br>- **DistributedObject**: returns the distributed object created.|
### Generating a Session ID ### Generating a Session ID
...@@ -33,7 +35,7 @@ Call **setSessionId()** to set a session ID for a distributed data object. The s ...@@ -33,7 +35,7 @@ Call **setSessionId()** to set a session ID for a distributed data object. The s
**Table 3** API for setting a session ID **Table 3** API for setting a session ID
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.<br>&nbsp;**sessionId**: session ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| | DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.<br> **sessionId**: session ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
### Observing Data Changes ### Observing Data Changes
...@@ -67,13 +69,13 @@ The saved data will be released in the following cases: ...@@ -67,13 +69,13 @@ The saved data will be released in the following cases:
- The application has been uninstalled. - The application has been uninstalled.
- Data is successfully restored. - Data is successfully restored.
**Table 6** APIs for saving a distributed data object and revoking the saving **Table 6** APIs for saving a distributed data object and revoking the saving operation
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| DistributedDataObject | save(deviceId: string): Promise&lt;SaveSuccessResponse&gt; | Saves a distributed data object. This API uses a promise to return the result.| | DistributedDataObject | save(deviceId: string): Promise&lt;SaveSuccessResponse&gt; | Saves a distributed data object. This API uses a promise to return the result.|
| DistributedDataObject| save(deviceId: string, callback: AsyncCallback&lt;SaveSuccessResponse&gt;): void | Saves a distributed data object. This API uses an asynchronous callback to return the result.| | DistributedDataObject| save(deviceId: string, callback: AsyncCallback&lt;SaveSuccessResponse&gt;): void | Saves a distributed data object. This API uses an asynchronous callback to return the result.|
| DistributedDataObject | revokeSave(callback: AsyncCallback&lt;RevokeSaveSuccessResponse&gt;): void | Revokes the data saving operation. This API uses an asynchronous callback to return the result. | | DistributedDataObject | revokeSave(callback: AsyncCallback&lt;RevokeSaveSuccessResponse&gt;): void | Revokes the data saving operation. This API uses an asynchronous callback to return the result.|
| DistributedDataObject| revokeSave(): Promise&lt;RevokeSaveSuccessResponse&gt; | Revokes the data saving operation. This API uses a promise to return the result. | | DistributedDataObject| revokeSave(): Promise&lt;RevokeSaveSuccessResponse&gt; | Revokes the data saving operation. This API uses a promise to return the result.|
## How to Develop ## How to Develop
...@@ -206,7 +208,6 @@ The following example shows how to implement a distributed data object synchroni ...@@ -206,7 +208,6 @@ The following example shows how to implement a distributed data object synchroni
- Callback - Callback
```js ```js
// Save a distributed data object. // Save a distributed data object.
local_object.save("local", (result, data)=>{ local_object.save("local", (result, data)=>{
...@@ -222,7 +223,6 @@ The following example shows how to implement a distributed data object synchroni ...@@ -222,7 +223,6 @@ The following example shows how to implement a distributed data object synchroni
}); });
``` ```
- Promise - Promise
```js ```js
// Save a distributed data object. // Save a distributed data object.
g_object.save("local").then((result)=>{ g_object.save("local").then((result)=>{
...@@ -239,7 +239,7 @@ The following example shows how to implement a distributed data object synchroni ...@@ -239,7 +239,7 @@ The following example shows how to implement a distributed data object synchroni
console.info("revokeSave failed."); 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. 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: The sample code is as follows:
```js ```js
......
...@@ -7,19 +7,21 @@ The Distributed Data Service (DDS) implements synchronization of application dat ...@@ -7,19 +7,21 @@ The Distributed Data Service (DDS) implements synchronization of application dat
## Available APIs ## Available APIs
For details about the APIs related to distributed data, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md).
The table below describes the APIs provided by the OpenHarmony DDS module. The table below describes the APIs provided by the OpenHarmony DDS module.
**Table 1** APIs provided by the DDS **Table 1** APIs provided by the DDS
| Category | API | Description | | Category | API | Description |
| -------- | --- | ----------- | | ------------ | ------------- | ------------- |
| Creating a distributed database | createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KVManager** object for database management.| | Creating a distributed database| createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KVManager** object for database management.|
| Obtaining a distributed KV store | getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Obtains the KV store with the specified **Options** and **storeId**. | | Obtaining a distributed KV store| getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Obtains the KV store with the specified **Options** and **storeId**.|
| Managing data in a distributed KV store | put(key: string, value: Uint8Array \| string \| number \| boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array \| string \| number \| boolean): Promise&lt;void> | Inserts and updates data. | | Managing data in a distributed KV store| put(key: string, value: Uint8Array \| string \| number \| boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array \| string \| number \| boolean): Promise&lt;void> | Inserts and updates data.|
| Managing data in a distributed KV store| delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. | | Managing data in a distributed KV store| delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. |
| Managing data in a distributed KV store | get(key: string, callback: AsyncCallback&lt;Uint8Array \| string \| boolean \| number&gt;): void<br>get(key: string): Promise&lt;Uint8Array \| string \| boolean \| number> | Queries data. | | Managing data in a distributed KV store| get(key: string, callback: AsyncCallback&lt;Uint8Array \| string \| boolean \| number&gt;): void<br>get(key: string): Promise&lt;Uint8Array \| string \| boolean \| number> | Queries data. |
| Subscribing to changes in the distributed data | on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;ChangeNotification&gt;): void<br>on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string, number]&gt;&gt;): void | Subscribes to data changes in the KV store. | | Subscribing to changes in the distributed data| on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;ChangeNotification&gt;): void<br>on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string, number]&gt;&gt;): void | Subscribes to data changes in the KV store.|
| Synchronizing data across devices | sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. | | Synchronizing data across devices| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. |
...@@ -29,14 +31,13 @@ The table below describes the APIs provided by the OpenHarmony DDS module. ...@@ -29,14 +31,13 @@ The table below describes the APIs provided by the OpenHarmony DDS module.
The following uses a single KV store as an example to describe the development procedure. The following uses a single KV store as an example to describe the development procedure.
1. Import the distributed data module. 1. Import the distributed data module.
```js ```js
import distributedData from '@ohos.data.distributedData'; import distributedData from '@ohos.data.distributedData';
``` ```
2. Create a **KvManager** instance based on the specified **KvManagerConfig** object. 2. Create a **KvManager** instance based on the specified **KvManagerConfig** object.
1. Create a **KvManagerConfig** object based on the application context. (1) Create a **KvManagerConfig** object based on the application context.
2. Create a **KvManager** instance. (2) Create a **KvManager** instance.
The sample code is as follows: The sample code is as follows:
```js ```js
...@@ -63,8 +64,8 @@ The following uses a single KV store as an example to describe the development p ...@@ -63,8 +64,8 @@ The following uses a single KV store as an example to describe the development p
``` ```
3. Create and obtain a single KV store. 3. Create and obtain a single KV store.
1. Declare the ID of the single KV store to create. (1) Declare the ID of the single KV store to create.
2. Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required. (2) Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required.
The sample code is as follows: The sample code is as follows:
```js ```js
...@@ -91,12 +92,11 @@ The following uses a single KV store as an example to describe the development p ...@@ -91,12 +92,11 @@ The following uses a single KV store as an example to describe the development p
} }
``` ```
> ![icon-note.gif](../public_sys-resources/icon-note.gif) **NOTE**<br/> > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (**kvStore** in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle. > For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (**kvStore** in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle.
4. Subscribe to changes in the distributed data.<br/> 4. Subscribe to changes in the distributed data.<br/>
The following is the sample code for subscribing to the data changes of a single KV store: The following is the sample code for subscribing to the data changes of a single KV store:
```js ```js
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
console.log("dataChange callback call data: " + JSON.stringify(data)); console.log("dataChange callback call data: " + JSON.stringify(data));
...@@ -104,8 +104,8 @@ The following uses a single KV store as an example to describe the development p ...@@ -104,8 +104,8 @@ The following uses a single KV store as an example to describe the development p
``` ```
5. Write data to the single KV store. 5. Write data to the single KV store.
1. Construct the key and value to be written into the single KV store. (1) Construct the key and value to be written into the single KV store.
2. Write key-value pairs into the single KV store. (2) Write key-value pairs into the single KV store.
The following is the sample code for writing key-value pairs of the string type into the single KV store: The following is the sample code for writing key-value pairs of the string type into the single KV store:
...@@ -126,11 +126,10 @@ The following uses a single KV store as an example to describe the development p ...@@ -126,11 +126,10 @@ The following uses a single KV store as an example to describe the development p
``` ```
6. Query data in the single KV store. 6. Query data in the single KV store.
1. Construct the key to be queried from the single KV store. (1) Construct the key to be queried from the single KV store.
2. Query data from the single KV store. (2) Query data from the single KV store.
The following is the sample code for querying data of the string type from the single KV store: The following is the sample code for querying data of the string type from the single KV store:
```js ```js
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
...@@ -178,3 +177,7 @@ The following uses a single KV store as an example to describe the development p ...@@ -178,3 +177,7 @@ The following uses a single KV store as an example to describe the development p
} }
}); });
``` ```
## Samples
The following samples are provided to help you better understand the distributed data development:
- [`KvStore`: Distributed Database (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Kvstore)
- [Distributed Database](https://gitee.com/openharmony/codelabs/tree/master/Data/JsDistributedData)
...@@ -34,7 +34,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -34,7 +34,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore | insert(table: string, values: ValuesBucket, callback: AsyncCallback&lt;number&gt;):void | Inserts a row of data into a table. This API uses a callback to return the result.<br>- **table**: name of the target table.<br>- **values**: data to be inserted into the table.<br>- **callback**: callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| | RdbStore | insert(table: string, values: ValuesBucket, callback: AsyncCallback&lt;number&gt;):void | Inserts a row of data into a table. This API uses a callback to return the result.<br>- **table**: name of the target table.<br>- **values**: data to be inserted into the table.<br>- **callback**: callback invoked to return the result. If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.|
| RdbStore | insert(table: string, values: ValuesBucket): Promise&lt;number&gt; | Inserts a row of data into a table. This API uses a promise to return the result.<br>- **table**: name of the target table.<br>- **values**: data to be inserted into the table.| | RdbStore | insert(table: string, values: ValuesBucket): Promise&lt;number&gt; | Inserts a row of data into a table. This API uses a promise to return the result.<br>- **table**: name of the target table.<br>- **values**: data to be inserted into the table.|
- **Updating data** - **Updating data**
...@@ -190,7 +190,7 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -190,7 +190,7 @@ You can obtain the distributed table name for a remote device based on the local
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback\<Array\<string>>): void;| Unregisters the observer of the specified type for the RDB store. This API uses a callback to return the result.<br>- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** means to subscribe to remote data changes.<br>- **observer**: observer to unregister.| | RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback\<Array\<string>>): void;| Unregisters the observer of the specified type for the RDB store. This API uses a callback to return the result.<br>- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** means to subscribe to remote data changes.<br>- **observer**: observer to unregister.|
### Backing Up and Restore an RDB Store ### Backing Up and Restoring an RDB Store
**Backing Up an RDB Store** **Backing Up an RDB Store**
...@@ -198,8 +198,8 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -198,8 +198,8 @@ You can obtain the distributed table name for a remote device based on the local
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore |backup(destName:string, callback: AsyncCallback&lt;void&gt;):void| Backs up the RDB store with the specified name. This API uses an asynchronous callback to return the result.<br>- **destName**: name of the RDB backup file.<br>- **callback**: callback invoked to return the result.| | RdbStore |backup(destName:string, callback: AsyncCallback&lt;void&gt;):void| Backs up an RDB store. This API uses an asynchronous callback to return the result.<br>- **destName**: name of the RDB backup file.<br>- **callback**: callback invoked to return the result.|
| RdbStore |backup(destName:string): Promise&lt;void&gt;| Backs up the RDB store with the specified name. This API uses a promise to return the result.<br>- **destName**: name of the RDB backup file.| | RdbStore |backup(destName:string): Promise&lt;void&gt;| Backs up an RDB store. This API uses a promise to return the result.<br>- **destName**: name of the RDB backup file.|
**Restoring an RDB Store** **Restoring an RDB Store**
...@@ -207,8 +207,8 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -207,8 +207,8 @@ You can obtain the distributed table name for a remote device based on the local
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore |restore(srcName:string, callback: AsyncCallback&lt;void&gt;):void| Restores an RDB store using the specified backup file. This API uses an asynchronous callback to return the result.<br>- **srcName**: name of the RDB backup file.<br>- **callback**: callback invoked to return the result.| | RdbStore |restore(srcName:string, callback: AsyncCallback&lt;void&gt;):void| Restores an RDB store using a backup file. This API uses an asynchronous callback to return the result.<br>- **srcName**: name of the RDB backup file.<br>- **callback**: callback invoked to return the result.|
| RdbStore |restore(srcName:string): Promise&lt;void&gt;| Restores an RDB store using the specified backup file. This API uses a promise to return the result.<br>- **srcName**: name of the RDB backup file.| | RdbStore |restore(srcName:string): Promise&lt;void&gt;| Restores an RDB store using a backup file. This API uses a promise to return the result.<br>- **srcName**: name of the RDB backup file.|
## How to Develop ## How to Develop
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
## When to Use ## When to Use
With device usage statistics APIs, you can have a better understanding of the application, notification, and system usage. For example, in application usage statistics, you can query the application usage, event log, and bundle group. With device usage statistics APIs, you can have a better understanding of the application, notification, and system usage. For example, in application usage statistics, you can query the application usage, event log, and bundle group.
The application records (usage history statistics and event records) cached by components are updated to the database for persistent storage within 30 minutes after an event is reported. The application records (usage history statistics and event records) cached by components are updated to the database for persistent storage within 30 minutes after an event is reported.
## Available APIs ## Available APIs
...@@ -23,7 +22,7 @@ import stats from '@ohos.bundleState'; ...@@ -23,7 +22,7 @@ import stats from '@ohos.bundleState';
| function queryAppUsagePriorityGroup(callback: AsyncCallback&lt;number&gt;): void | Queries the priority group of this application. This API uses an asynchronous callback to return the result.| | function queryAppUsagePriorityGroup(callback: AsyncCallback&lt;number&gt;): void | Queries the priority group of this application. This API uses an asynchronous callback to return the result.|
| function queryAppUsagePriorityGroup(): Promise&lt;number&gt;; | Queries the priority group of this application. This API uses a promise to return the result.| | function queryAppUsagePriorityGroup(): Promise&lt;number&gt;; | Queries the priority group of this application. This API uses a promise to return the result.|
| function isIdleState(bundleName: string, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether the application specified by **bundleName** is in the idle state. | | function isIdleState(bundleName: string, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether the application specified by **bundleName** is in the idle state. |
| function getRecentlyUsedModules(maxNum: number, callback: AsyncCallback&lt;BundleActiveModuleInfo&gt;): void | Obtains the number of FA usage records specified by **maxNum**.| | function getRecentlyUsedModules(maxNum? : number, callback: AsyncCallback&lt;BundleActiveModuleInfo&gt;): void | Obtains the number of FA usage records specified by **maxNum**. If **maxNum** is not specified, the default value **1000** is used.|
| function queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback&lt;Array&lt;BundleActiveEventState&gt;&gt;): void | Queries the number of notifications from all applications based on the specified start time and end time.| | function queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback&lt;Array&lt;BundleActiveEventState&gt;&gt;): void | Queries the number of notifications from all applications based on the specified start time and end time.|
| function queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback&lt;Array&lt;BundleActiveEventState&gt;&gt;): void | Queries statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time.| | function queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback&lt;Array&lt;BundleActiveEventState&gt;&gt;): void | Queries statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time.|
| function queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback&lt;number&gt;): void | Queries the priority group of the application specified by **bundleName**. If **bundleName** is not specified, the priority group of the current application is queried. This API uses an asynchronous callback to return the result.| | function queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback&lt;number&gt;): void | Queries the priority group of the application specified by **bundleName**. If **bundleName** is not specified, the priority group of the current application is queried. This API uses an asynchronous callback to return the result.|
...@@ -57,13 +56,13 @@ import stats from '@ohos.bundleState'; ...@@ -57,13 +56,13 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryBundleActiveStates(0, 20000000000000).then( res => { stats.queryBundleActiveStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise success.'); console.log('BUNDLE_ACTIVE queryBundleActiveStates promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleActiveStates promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryBundleActiveStates promise result ' + JSON.stringify(res[i]));
} }
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryBundleActiveStates promise failed, because: ' + err.code);
}); });
...@@ -87,7 +86,7 @@ import stats from '@ohos.bundleState'; ...@@ -87,7 +86,7 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryBundleStateInfos(0, 20000000000000).then( res => { stats.queryBundleStateInfos(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise success.'); console.log('BUNDLE_ACTIVE queryBundleStateInfos promise success.');
let i = 1; let i = 1;
for (let key in res){ for (let key in res){
...@@ -95,7 +94,7 @@ import stats from '@ohos.bundleState'; ...@@ -95,7 +94,7 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise result ' + JSON.stringify(res[key])); console.log('BUNDLE_ACTIVE queryBundleStateInfos promise result ' + JSON.stringify(res[key]));
i++; i++;
} }
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryBundleStateInfos promise failed, because: ' + err.code);
}); });
...@@ -121,13 +120,13 @@ import stats from '@ohos.bundleState'; ...@@ -121,13 +120,13 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryCurrentBundleActiveStates(0, 20000000000000).then( res => { stats.queryCurrentBundleActiveStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.'); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise result ' + JSON.stringify(res[i]));
} }
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise failed, because: ' + err.code);
}); });
...@@ -151,13 +150,13 @@ import stats from '@ohos.bundleState'; ...@@ -151,13 +150,13 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then( res => { stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.'); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise result ' + JSON.stringify(res[i]));
} }
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise failed, because: ' + err.code);
}); });
...@@ -181,9 +180,9 @@ import stats from '@ohos.bundleState'; ...@@ -181,9 +180,9 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryAppUsagePriorityGroup().then( res => { stats.queryAppUsagePriorityGroup().then(res => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code);
}); });
...@@ -203,9 +202,9 @@ import stats from '@ohos.bundleState'; ...@@ -203,9 +202,9 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.isIdleState("com.ohos.camera").then( res => { stats.isIdleState("com.ohos.camera").then(res => {
console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE isIdleState promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE isIdleState promise failed, because: ' + err.code);
}); });
...@@ -225,18 +224,18 @@ import stats from '@ohos.bundleState'; ...@@ -225,18 +224,18 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.getRecentlyUsedModules(1000).then( res => { stats.getRecentlyUsedModules(1000).then(res => {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded'); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise result ' + JSON.stringify(res[i]));
} }
}).catch( err=> { }).catch(err=> {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise failed, because: ' + err.code);
}); });
// Promise mode when maxNum is not specified // Promise mode when maxNum is not specified
stats.getRecentlyUsedModules().then( res => { stats.getRecentlyUsedModules().then(res => {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded'); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1));
...@@ -247,7 +246,7 @@ import stats from '@ohos.bundleState'; ...@@ -247,7 +246,7 @@ import stats from '@ohos.bundleState';
}); });
// Asynchronous callback mode // Asynchronous callback mode
stats.getRecentlyUsedModules(1000,(err, res) => { stats.getRecentlyUsedModules(1000, (err, res) => {
if(err) { if(err) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code); console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code);
} else { } else {
...@@ -261,7 +260,7 @@ import stats from '@ohos.bundleState'; ...@@ -261,7 +260,7 @@ import stats from '@ohos.bundleState';
// Asynchronous callback mode when maxNum is not specified // Asynchronous callback mode when maxNum is not specified
stats.getRecentlyUsedModules((err, res) => { stats.getRecentlyUsedModules((err, res) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code); console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback succeeded.'); console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback succeeded.');
...@@ -279,10 +278,10 @@ import stats from '@ohos.bundleState'; ...@@ -279,10 +278,10 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryAppNotificationNumber(0, 20000000000000).then( res => { stats.queryAppNotificationNumber(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise success.'); console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise success.');
console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise result ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise result ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise failed, because: ' + err.code);
}); });
...@@ -303,10 +302,10 @@ import stats from '@ohos.bundleState'; ...@@ -303,10 +302,10 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryBundleActiveEventStates(0, 20000000000000).then( res => { stats.queryBundleActiveEventStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise success.'); console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise success.');
console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise result ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise result ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise failed, because: ' + err.code);
}); });
...@@ -327,9 +326,9 @@ import stats from '@ohos.bundleState'; ...@@ -327,9 +326,9 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode without parameters // Promise mode without parameters
stats.queryAppUsagePriorityGroup().then( res => { stats.queryAppUsagePriorityGroup().then(res => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code);
}); });
...@@ -343,15 +342,15 @@ import stats from '@ohos.bundleState'; ...@@ -343,15 +342,15 @@ import stats from '@ohos.bundleState';
}); });
// Promise mode with parameters // Promise mode with parameters
stats.queryAppUsagePriorityGroup(this.bundleName).then( res => { stats.queryAppUsagePriorityGroup(this.bundleName).then(res => {
console.log('BUNDLE_ACTIVE QueryPackageGroup promise succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE QueryPackageGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE QueryPackageGroup promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE QueryPackageGroup promise failed. because: ' + err.code);
}); });
// Asynchronous callback mode with parameters // Asynchronous callback mode with parameters
stats.queryAppUsagePriorityGroup(this.bundleName, (err, res) => { stats.queryAppUsagePriorityGroup(this.bundleName, (err, res) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code); console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE QueryPackageGroup callback succeeded. result: ' + JSON.stringify(res));
...@@ -365,14 +364,14 @@ import stats from '@ohos.bundleState'; ...@@ -365,14 +364,14 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.setBundleGroup(this.bundleName, this.newGroup).then( () => { stats.setBundleGroup(this.bundleName, this.newGroup).then(() => {
console.log('BUNDLE_ACTIVE SetBundleGroup promise succeeded.'); console.log('BUNDLE_ACTIVE SetBundleGroup promise succeeded.');
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE SetBundleGroup promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE SetBundleGroup promise failed. because: ' + err.code);
}); });
// Asynchronous callback mode // Asynchronous callback mode
stats.setBundleGroup(this.bundleName, this.newGroup, (err) => { stats.setBundleGroup(this.bundleName, this.newGroup, (err) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE SetBundleGroup callback failed. because: ' + err.code); console.log('BUNDLE_ACTIVE SetBundleGroup callback failed. because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE SetBundleGroup callback succeeded.'); console.log('BUNDLE_ACTIVE SetBundleGroup callback succeeded.');
...@@ -386,7 +385,7 @@ import stats from '@ohos.bundleState'; ...@@ -386,7 +385,7 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
let onBundleGroupChanged = (err,res) =>{ let onBundleGroupChanged = (err,res) => {
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.');
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result oldGroup is : ' + res.oldGroup); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result oldGroup is : ' + res.oldGroup);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result newGroup is : ' + res.newGroup); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result newGroup is : ' + res.newGroup);
...@@ -394,13 +393,13 @@ import stats from '@ohos.bundleState'; ...@@ -394,13 +393,13 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result userId is : ' + res.userId); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result userId is : ' + res.userId);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result bundleName is : ' + res.bundleName); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result bundleName is : ' + res.bundleName);
}; };
stats.registerGroupCallBack(onBundleGroupChanged).then( () => { stats.registerGroupCallBack(onBundleGroupChanged).then(() => {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise succeeded.'); console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise succeeded.');
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise failed. because: ' + err.code);
}); });
// Asynchronous callback mode // Asynchronous callback mode
let onBundleGroupChanged = (err,res) =>{ let onBundleGroupChanged = (err,res) => {
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.');
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's oldGroup is : ' + res.oldGroup); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's oldGroup is : ' + res.oldGroup);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's newGroup is : ' + res.newGroup); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's newGroup is : ' + res.newGroup);
...@@ -408,8 +407,8 @@ import stats from '@ohos.bundleState'; ...@@ -408,8 +407,8 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's userId is : ' + res.userId); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's userId is : ' + res.userId);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's bundleName is : ' + res.bundleName); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's bundleName is : ' + res.bundleName);
}; };
stats.registerGroupCallBack(onBundleGroupChanged, (err)=>{ stats.registerGroupCallBack(onBundleGroupChanged, (err) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback failed, because: ' + err.code); console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback failed, because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback success.');
...@@ -423,14 +422,14 @@ import stats from '@ohos.bundleState'; ...@@ -423,14 +422,14 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
//promise //promise
stats.unRegisterGroupCallBack().then( () => { stats.unRegisterGroupCallBack().then(() => {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise succeeded.'); console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise succeeded.');
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise failed. because: ' + err.code);
}); });
//callback //callback
stats.unRegisterGroupCallBack((err)=>{ stats.unRegisterGroupCallBack((err) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback failed, because: ' + err.code); console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback failed, because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback success.');
......
...@@ -2273,7 +2273,43 @@ Writes the buffer. This API uses an asynchronous callback to return the result. ...@@ -2273,7 +2273,43 @@ Writes the buffer. This API uses an asynchronous callback to return the result.
``` ```
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility'
var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000,
channels: audio.AudioChannel.CHANNEL_2,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}
var audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_SPEECH,
usage: audio.streamUsage.STREAM_USAGE_VOICE_COMMUNICATION
rendererFlags: 1
}
var audioRendererOptions = {
streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo
}
var audioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data)=> {
audioRenderer = data;
console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS');
}).catch((err) => {
console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message);
});
var bufferSize;
audioRenderer.getBufferSize().then((data)=> {
console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data);
bufferSize = data;
}).catch((err) => {
console.info.('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message);
});
console.info('Buffer size:'+bufferSize);
var context = featureAbility.getContext();
var path = await context.getCacheDir();
var filePath = path+"/StarWars10s-2C-48000-4SW.wav"
let ss = fileio.createStreamSync(filePath, 'r'); let ss = fileio.createStreamSync(filePath, 'r');
let buf = new ArrayBuffer(bufferSize); let buf = new ArrayBuffer(bufferSize);
ss.readSync(buf); ss.readSync(buf);
...@@ -2305,7 +2341,42 @@ Writes the buffer. This API uses a promise to return the result. ...@@ -2305,7 +2341,42 @@ Writes the buffer. This API uses a promise to return the result.
``` ```
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility'
var audioStreamInfo = {
samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000,
channels:audio.AudioChannel.CHANNEL_2,
sampleFormat.audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE,
encodingType.audio.AudioEncodingType.ENCODING_TYPE_RAW
}
var audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_SPEECH,
usage: audio.streamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
rendererFlags: 1
}
var audioRendererOptions = {
streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo
}
var audioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data) => {
audioRenderer = data;
console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS');
}).catch((err) => {
console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message);
});
var bufferSize;
audioRenderer.getBufferSize().then((data) => {
console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data);
bufferSize = data;
}).catch((err) => {
console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message);
});
console.info('BufferSize: ' + bufferSize);
var context = featureAbility.getContext();
var path = await context.getCacheDir();
var filePath = 'data/StarWars10s-2C-48000-4SW.wav'; var filePath = 'data/StarWars10s-2C-48000-4SW.wav';
let ss = fileio.createStreamSync(filePath, 'r'); let ss = fileio.createStreamSync(filePath, 'r');
let buf = new ArrayBuffer(bufferSize); let buf = new ArrayBuffer(bufferSize);
...@@ -2408,12 +2479,39 @@ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a ...@@ -2408,12 +2479,39 @@ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a
**Example** **Example**
``` ```
import audio from '@ohos.multimedia.audio';
import fileio from '@ohos.fileio';
var audioStreamInfo = {
samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000,
channels:audio.AudioChannel.CHANNEL_2,
sampleFormat.audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE,
encodingType.audio.AudioEncodingType.ENCODING_TYPE_RAW
}
var audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_SPEECH,
usage: audio.streamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
rendererFlags: 1
}
var audioRendererOptions = {
streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo
}
var audioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data) => {
audioRenderer = data;
console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS');
}).catch((err) => {
console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message);
});
var bufferSize; var bufferSize;
await audioRenderer.getBufferSize().then(async function (data) => { audioRenderer.getBufferSize().then((data) => {
console.info('AudioFrameworkRenderLog: getBufferSize :SUCCESS '+data); console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data);
bufferSize=data; bufferSize=data;
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRenderLog: getBufferSize :ERROR : '+err.message); console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message);
}); });
``` ```
...@@ -2542,7 +2640,8 @@ Sets the audio interruption mode for the application. This API uses a promise to ...@@ -2542,7 +2640,8 @@ Sets the audio interruption mode for the application. This API uses a promise to
**Example** **Example**
``` ```
audioManager.setInterruptMode(audio.InterruptType.SHARE_MODE).then(() => { const audioManager = audio.getAudioManager();
audioManager.setInterruptMode(audio.InterruptMode.SHARE_MODE).then(() => {
console.log('Promise returned to indicate a successful volume setting.'); console.log('Promise returned to indicate a successful volume setting.');
}); });
``` ```
...@@ -2564,7 +2663,8 @@ Sets the audio interruption mode for the application. This API uses a callback t ...@@ -2564,7 +2663,8 @@ Sets the audio interruption mode for the application. This API uses a callback t
**Example** **Example**
``` ```
audioManager.setInterruptMode(audio.InterruptType.SHARE_MODE,()=>{ const audioManager = audio.getAudioManager();
audioManager.setInterruptMode(audio.InterruptMode.SHARE_MODE,()=>{
console.log('Callback returned to indicate a successful volume setting.'); console.log('Callback returned to indicate a successful volume setting.');
}); });
``` ```
...@@ -2654,7 +2754,7 @@ Subscribes to mark reached events. When the number of frames rendered reaches th ...@@ -2654,7 +2754,7 @@ Subscribes to mark reached events. When the number of frames rendered reaches th
``` ```
audioRenderer.on('markReach', 1000, (position) => { audioRenderer.on('markReach', 1000, (position) => {
if (position == "1000") { if (position == 1000) {
console.log('ON Triggered successfully'); console.log('ON Triggered successfully');
} }
}); });
...@@ -2701,7 +2801,7 @@ Subscribes to period reached events. When the period of frame rendering reaches ...@@ -2701,7 +2801,7 @@ Subscribes to period reached events. When the period of frame rendering reaches
``` ```
audioRenderer.on('periodReach', 1000, (position) => { audioRenderer.on('periodReach', 1000, (position) => {
if (position == "1000") { if (position == 1000) {
console.log('ON Triggered successfully'); console.log('ON Triggered successfully');
} }
}); });
...@@ -2935,13 +3035,35 @@ Starts capturing. This API uses a promise to return the result. ...@@ -2935,13 +3035,35 @@ Starts capturing. This API uses a promise to return the result.
**Example** **Example**
``` ```
import audio from '@ohos.multimedia.audio';
import fileio from '@ohos.fileio';
var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_2,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}
var audioCapturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags = 1
}
var audioCapturer;
audio.createAudioCapturer(audioCapturerOptions).then((data) => {
audioCapturer = data;
console.info('AudioFrameworkRecLog: AudioCapturer Created: SUCCESS');
}).catch((err) => {
console.info('AudioFrameworkRecLog: AudioCapturer Created: ERROR: '+err.message);
});
audioCapturer.start().then(() => { audioCapturer.start().then(() => {
console.info('AudioFrameworkRecLog: ---------START---------'); console.info('AudioFrameworkRecLog: ---------START---------');
console.info('AudioFrameworkRecLog: Capturer started :SUCCESS '); console.info('AudioFrameworkRecLog: Capturer started: SUCCESS');
console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state); console.info('AudioFrameworkRecLog: AudioCapturer: STATE: '+audioCapturer.state);
console.info('AudioFrameworkRecLog: Capturer started :SUCCESS '); console.info('AudioFrameworkRecLog: Capturer started: SUCCESS ');
if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) {
stateFlag = true; console.info('AudioFrameworkRecLog: AudioCapturer is in Running State');
} }
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecLog: Capturer start :ERROR : '+err.message); console.info('AudioFrameworkRecLog: Capturer start :ERROR : '+err.message);
...@@ -2994,15 +3116,13 @@ Stops capturing. This API uses a promise to return the result. ...@@ -2994,15 +3116,13 @@ Stops capturing. This API uses a promise to return the result.
``` ```
audioCapturer.stop().then(() => { audioCapturer.stop().then(() => {
console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); console.info('AudioFrameworkRecLog: ---------STOP RECORD---------');
console.info('AudioFrameworkRecLog: Capturer stopped : SUCCESS'); console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS');
if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){
stateFlag=true; console.info('AudioFrameworkRecLog: State is Stopped': ');
console.info('AudioFrameworkRecLog: resultFlag : '+stateFlag);
} }
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecLog: Capturer stop:ERROR : '+err.message); console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+err.message);
stateFlag=false;
}); });
``` ```
...@@ -3054,11 +3174,9 @@ audioCapturer.release().then(() => { ...@@ -3054,11 +3174,9 @@ audioCapturer.release().then(() => {
console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------');
console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); console.info('AudioFrameworkRecLog: Capturer release : SUCCESS');
console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state); console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state);
stateFlag=true;
console.info('AudioFrameworkRecLog: stateFlag : '+stateFlag); console.info('AudioFrameworkRecLog: stateFlag : '+stateFlag);
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecLog: Capturer stop:ERROR : '+err.message); console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+err.message);
stateFlag=false
}); });
``` ```
...@@ -3082,6 +3200,13 @@ Reads the buffer. This API uses an asynchronous callback to return the result. ...@@ -3082,6 +3200,13 @@ Reads the buffer. This API uses an asynchronous callback to return the result.
**Example** **Example**
``` ```
var bufferSize;
audioCapturer.getBufferSize().then((data) => {
console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS '+data);
bufferSize = data;
}).catch((err) => {
console.info('AudioFrameworkRecLog: getBufferSize: EROOR: '+err.message);
});
audioCapturer.read(bufferSize, true, async(err, buffer) => { audioCapturer.read(bufferSize, true, async(err, buffer) => {
if (!err) { if (!err) {
console.log("Success in reading the buffer data"); console.log("Success in reading the buffer data");
...@@ -3114,6 +3239,14 @@ Reads the buffer. This API uses a promise to return the result. ...@@ -3114,6 +3239,14 @@ Reads the buffer. This API uses a promise to return the result.
**Example** **Example**
``` ```
var bufferSize;
audioCapturer.getBufferSize().then((data) => {
console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS '+data);
bufferSize = data;
}).catch((err) => {
console.info('AudioFrameworkRecLog: getBufferSize: ERROR '+err.message);
});
console.info('Buffer size: ' + bufferSize);
audioCapturer.read(bufferSize, true).then((buffer) => { audioCapturer.read(bufferSize, true).then((buffer) => {
console.info('buffer read successfully'); console.info('buffer read successfully');
}).catch((err) => { }).catch((err) => {
...@@ -3217,12 +3350,12 @@ Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a ...@@ -3217,12 +3350,12 @@ Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a
**Example** **Example**
``` ```
await audioCapturer.getBufferSize().then(async function (bufferSize) { var bufferSize;
console.info('AudioFrameworkRecordLog: getBufferSize :SUCCESS '+ bufferSize); audioCapturer.getBufferSize().then((data) => {
var buffer = await audioCapturer.read(bufferSize, true); console.info('AudioFrameworkRecLog: getBufferSize :SUCCESS '+ data);
console.info('Buffer read is ' + buffer ); bufferSize = data;
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecordLog: getBufferSize :ERROR : '+err.message); console.info('AudioFrameworkRecLog: getBufferSize :ERROR : '+ err.message);
}); });
``` ```
...@@ -3247,7 +3380,7 @@ Subscribes to mark reached events. When the number of frames captured reaches th ...@@ -3247,7 +3380,7 @@ Subscribes to mark reached events. When the number of frames captured reaches th
``` ```
audioCapturer.on('markReach', 1000, (position) => { audioCapturer.on('markReach', 1000, (position) => {
if (position == "1000") { if (position == 1000) {
console.log('ON Triggered successfully'); console.log('ON Triggered successfully');
} }
}); });
...@@ -3293,7 +3426,7 @@ Subscribes to mark reached events. When the period of frame capturing reaches th ...@@ -3293,7 +3426,7 @@ Subscribes to mark reached events. When the period of frame capturing reaches th
``` ```
audioCapturer.on('periodReach', 1000, (position) => { audioCapturer.on('periodReach', 1000, (position) => {
if (position == "1000") { if (position == 1000) {
console.log('ON Triggered successfully'); console.log('ON Triggered successfully');
} }
}); });
......
# Distributed Data Object # Distributed Data Object
Provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices. The distributedDataObject module provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices.
> **NOTE**<br/> > **NOTE**<br/>
> >
...@@ -23,9 +23,9 @@ Creates a distributed data object. ...@@ -23,9 +23,9 @@ Creates a distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| source | object | Yes| Attribute of the distributed data object to create.| | source | object | Yes| Attribute of the distributed data object to create.|
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -33,12 +33,11 @@ Creates a distributed data object. ...@@ -33,12 +33,11 @@ Creates a distributed data object.
| [DistributedObject](#distributedobject) | Distributed data object created.| | [DistributedObject](#distributedobject) | Distributed data object created.|
**Example** **Example**
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
// Create a distributed data object, which contains attributes of four types, namely, string, number, boolean, and object. // Create a distributed data object, which contains attributes of four types, namely, string, number, boolean, and object.
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
parent:{mother:"jack mom",father:"jack Dad"}}); ```
```
## distributedObject.genSessionId ## distributedObject.genSessionId
...@@ -50,15 +49,15 @@ Creates a random session ID. ...@@ -50,15 +49,15 @@ Creates a random session ID.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| string | Session ID created.| | string | Session ID created.|
**Example** **Example**
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var sessionId = distributedObject.genSessionId(); var sessionId = distributedObject.genSessionId();
``` ```
## SaveSuccessResponse<sup>9+</sup> ## SaveSuccessResponse<sup>9+</sup>
...@@ -98,27 +97,26 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo ...@@ -98,27 +97,26 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| | sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the session ID is set successfully;<br>returns **false** otherwise. | | boolean | Returns **true** if the session ID is set successfully;<br>returns **false** otherwise. |
**Example** **Example**
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});;
parent:{mother:"jack mom",father:"jack Dad"}}); // Add g_object to the distributed network.
// Add g_object to the distributed network. g_object.setSessionId(distributedObject.genSessionId());
g_object.setSessionId(distributedObject.genSessionId()); // Remove g_object from the distributed network.
// Remove g_object from the distributed network. g_object.setSessionId("");
g_object.setSessionId(""); ```
```
### on('change') ### on('change')
...@@ -130,15 +128,15 @@ Subscribes to the changes of this distributed data object. ...@@ -130,15 +128,15 @@ Subscribes to the changes of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback used to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.| | callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback used to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example** **Example**
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
globalThis.changeCallback = (sessionId, changeData) => { globalThis.changeCallback = (sessionId, changeData) => {
console.info("change" + sessionId); console.info("change" + sessionId);
if (changeData != null && changeData != undefined) { if (changeData != null && changeData != undefined) {
...@@ -159,16 +157,16 @@ Unsubscribes from the changes of this distributed data object. ...@@ -159,16 +157,16 @@ Unsubscribes from the changes of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.| | type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.| | callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example** **Example**
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
// Unregister the specified data change callback. // Unregister the specified data change callback.
g_object.off("change", globalThis.changeCallback); g_object.off("change", globalThis.changeCallback);
// Unregister all data change callbacks. // Unregister all data change callbacks.
...@@ -184,10 +182,10 @@ Subscribes to the status change (online or offline) of this distributed data obj ...@@ -184,10 +182,10 @@ Subscribes to the status change (online or offline) of this distributed data obj
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| | type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.<br>**sessionId**: session ID of the distributed data object.<br>**networkId**: object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline. | | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.<br>**sessionId**: session ID of the distributed data object.<br>**networkId**: object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline.|
**Example** **Example**
```js ```js
...@@ -195,7 +193,7 @@ import distributedObject from '@ohos.data.distributedDataObject'; ...@@ -195,7 +193,7 @@ import distributedObject from '@ohos.data.distributedDataObject';
globalThis.statusCallback = (sessionId, networkId, status) => { globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
} }
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
g_object.on("status", globalThis.statusCallback); g_object.on("status", globalThis.statusCallback);
``` ```
...@@ -209,16 +207,16 @@ Unsubscribes from the status change (online or offline) of this distributed data ...@@ -209,16 +207,16 @@ Unsubscribes from the status change (online or offline) of this distributed data
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| | type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.<br>**sessionId**: session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the status, which can be online or offline.| | callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.<br>**sessionId**: session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the status, which can be online or offline.|
**Example** **Example**
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
globalThis.statusCallback = (sessionId, networkId, status) => { globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
} }
...@@ -245,24 +243,24 @@ The saved data will be released in the following cases: ...@@ -245,24 +243,24 @@ The saved data will be released in the following cases:
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.| | deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.|
| callback | AsyncCallback&lt;[SaveSuccessResponse](#savesuccessresponse)&gt; | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| | callback | AsyncCallback&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
**Example** **Example**
```js
```ts import distributedObject from '@ohos.data.distributedDataObject';
import distributedObject from '@ohos.data.distributedDataObject'; var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); g_object.setSessionId("123456");
g_object.setSessionId("123456"); g_object.save("local", (status, result)=>{
g_object.save("local", (result)=>{ console.log("save status = " + status);
console.log("save callback"); console.log("save callback");
console.info("save sessionId " + result.sessionId); console.info("save sessionId: " + result.sessionId);
console.info("save version " + result.version); console.info("save version: " + result.version);
console.info("save deviceId " + result.deviceId); console.info("save deviceId: " + result.deviceId);
}); });
``` ```
### save<sup>9+</sup> ### save<sup>9+</sup>
...@@ -281,31 +279,31 @@ The saved data will be released in the following cases: ...@@ -281,31 +279,31 @@ The saved data will be released in the following cases:
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. | | deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. |
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[SaveSuccessResponse](#savesuccessresponse)&gt; | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| | Promise&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
**Example** **Example**
```ts ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456"); g_object.setSessionId("123456");
g_object.save("local").then((result)=>{ g_object.save("local").then((result)=>{
console.log("save callback"); console.log("save callback");
console.info("save sessionId " + result.sessionId); console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version); console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId); console.info("save deviceId " + result.deviceId);
}, ()=>{ }, ()=>{
console.error("save failed"); console.error("save failed");
}); });
``` ```
### revokeSave<sup>9+</sup> ### revokeSave<sup>9+</sup>
...@@ -319,20 +317,20 @@ If the object is stored on another device, the data on the local device will be ...@@ -319,20 +317,20 @@ If the object is stored on another device, the data on the local device will be
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse)&gt; | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.| | callback | AsyncCallback&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
**Example** **Example**
```ts ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456"); g_object.setSessionId("123456");
g_object.revokeSave((result, data) =>{ g_object.revokeSave((result, data) =>{
console.log("revokeSave callback"); console.log("revokeSave callback");
}); });
``` ```
### revokeSave<sup>9+</sup> ### revokeSave<sup>9+</sup>
...@@ -345,22 +343,22 @@ If the object is stored on another device, the data on the local device will be ...@@ -345,22 +343,22 @@ If the object is stored on another device, the data on the local device will be
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse)&gt; | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.| | Promise&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
**Example** **Example**
```ts ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456"); g_object.setSessionId("123456");
g_object.revokeSave("local").then((result)=>{ g_object.revokeSave().then((result)=>{
console.log("revokeSave callback"); console.log("revokeSave callback");
console.log("sessionId" + result.sessionId); console.log("sessionId" + result.sessionId);
}, ()=>{ }, ()=>{
console.error("revokeSave failed"); console.error("revokeSave failed");
}); });
``` ```
# Display # 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** > **NOTE**
> >
...@@ -14,11 +14,11 @@ import display from '@ohos.display'; ...@@ -14,11 +14,11 @@ import display from '@ohos.display';
## DisplayState ## DisplayState
Provides the state of a display. Enumerates the display states.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
| Name| Default Value| Description| | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| STATE_UNKNOWN | 0 | Unknown.| | STATE_UNKNOWN | 0 | Unknown.|
| STATE_OFF | 1 | The display is shut down.| | STATE_OFF | 1 | The display is shut down.|
...@@ -56,7 +56,7 @@ Describes the attributes of a display. ...@@ -56,7 +56,7 @@ Describes the attributes of a display.
getDefaultDisplay(callback: AsyncCallback&lt;Display&gt;): void 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 **System capability**: SystemCapability.WindowManager.WindowManager.Core
...@@ -82,7 +82,7 @@ Obtains the default display object. ...@@ -82,7 +82,7 @@ Obtains the default display object.
getDefaultDisplay(): Promise&lt;Display&gt; 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 **System capability**: SystemCapability.WindowManager.WindowManager.Core
...@@ -103,11 +103,31 @@ Obtains the default display object. ...@@ -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 ## display.getAllDisplay
getAllDisplay(callback: AsyncCallback&lt;Array&lt;Display&gt;&gt;): void 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 **System capability**: SystemCapability.WindowManager.WindowManager.Core
...@@ -133,7 +153,7 @@ Obtains all the display objects. ...@@ -133,7 +153,7 @@ Obtains all the display objects.
getAllDisplay(): Promise&lt;Array&lt;Display&gt;&gt; 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 **System capability**: SystemCapability.WindowManager.WindowManager.Core
...@@ -158,15 +178,15 @@ Obtains all the display objects. ...@@ -158,15 +178,15 @@ Obtains all the display objects.
on(type: 'add'|'remove'|'change', callback: Callback&lt;number&gt;): void on(type: 'add'|'remove'|'change', callback: Callback&lt;number&gt;): void
Enables listening. Subscribes to display changes.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | 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; | Yes| Callback used to return the ID of the display.| | callback | Callback&lt;number&gt; | Yes| Callback used to return the ID of the display.|
**Example** **Example**
```js ```js
...@@ -181,14 +201,14 @@ Enables listening. ...@@ -181,14 +201,14 @@ Enables listening.
off(type: 'add'|'remove'|'change', callback?: Callback&lt;number&gt;): void off(type: 'add'|'remove'|'change', callback?: Callback&lt;number&gt;): void
Disables listening. Unsubscribes from display changes.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | 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.| | callback | Callback&lt;number&gt; | No| Callback used to return the ID of the display.|
**Example** **Example**
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
The distributedAccount module provides basic functions for managing distributed accounts, including querying and updating account login status. The distributedAccount module provides basic functions for managing distributed accounts, including querying and updating account login status.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br> > **NOTE**<br>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
......
...@@ -20,7 +20,7 @@ Obtains an **AccountManager** instance. ...@@ -20,7 +20,7 @@ Obtains an **AccountManager** instance.
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| --------------------------------- | ------------------------ | | --------------------------------- | ------------------------ |
| [AccountManager](#accountmanager) | Obtains an **AccountManager** instance.| | [AccountManager](#accountmanager) | Obtains an **AccountManager** instance.|
...@@ -92,7 +92,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -92,7 +92,7 @@ This is a system API and cannot be called by third-party applications.
| ------- | ------ | ---- | -------------------- | | ------- | ------ | ---- | -------------------- |
| localId | number | Yes | ID of the OS account to activate.| | localId | number | Yes | ID of the OS account to activate.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :---------------------------------- | | :------------------ | :---------------------------------- |
...@@ -141,7 +141,7 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re ...@@ -141,7 +141,7 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------- | :----------------------------------------------------------- | | :--------------------- | :----------------------------------------------------------- |
...@@ -202,7 +202,7 @@ Checks whether an OS account is activated. This API uses a promise to return the ...@@ -202,7 +202,7 @@ Checks whether an OS account is activated. This API uses a promise to return the
| ------- | ------ | ---- | ------------ | | ------- | ------ | ---- | ------------ |
| localId | number | Yes | ID of the target OS account.| | localId | number | Yes | ID of the target OS account.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------- | :----------------------------------------------------------- | | :--------------------- | :----------------------------------------------------------- |
...@@ -266,7 +266,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u ...@@ -266,7 +266,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u
| localId | number | Yes | ID of the target OS account. | | localId | number | Yes | ID of the target OS account. |
| constraint | string | Yes | [Constraint](#constraints) specified.| | constraint | string | Yes | [Constraint](#constraints) specified.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------- | :----------------------------------------------------------- | | :--------------------- | :----------------------------------------------------------- |
...@@ -316,7 +316,7 @@ Checks whether this OS account is a test account. This API uses a promise to ret ...@@ -316,7 +316,7 @@ Checks whether this OS account is a test account. This API uses a promise to ret
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------- | :----------------------------------------------------------- | | :--------------------- | :----------------------------------------------------------- |
...@@ -400,7 +400,7 @@ Checks whether an OS account has been verified. This API uses a promise to retur ...@@ -400,7 +400,7 @@ Checks whether an OS account has been verified. This API uses a promise to retur
| ------- | ------ | ---- | ------------------ | | ------- | ------ | ---- | ------------------ |
| localId | number | No | ID of the target OS account.| | localId | number | No | ID of the target OS account.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------- | :----------------------------------------------------------- | | :--------------------- | :----------------------------------------------------------- |
...@@ -467,7 +467,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -467,7 +467,7 @@ This is a system API and cannot be called by third-party applications.
| ------- | ------ | ---- | -------------------- | | ------- | ------ | ---- | -------------------- |
| localId | number | Yes | ID of the OS account to remove.| | localId | number | Yes | ID of the OS account to remove.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :---------------------------------- | | :------------------ | :---------------------------------- |
...@@ -540,7 +540,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -540,7 +540,7 @@ This is a system API and cannot be called by third-party applications.
| constraints | Array&lt;string&gt; | Yes | List of [constraints](#constraints) to set or remove.| | constraints | Array&lt;string&gt; | Yes | List of [constraints](#constraints) to set or remove.|
| enable | boolean | Yes | Set or remove constraints. The value **true** means to set constraints, and **false** means to remove constraints. | | enable | boolean | Yes | Set or remove constraints. The value **true** means to set constraints, and **false** means to remove constraints. |
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :---------------------------------- | | :------------------ | :---------------------------------- |
...@@ -608,7 +608,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -608,7 +608,7 @@ This is a system API and cannot be called by third-party applications.
| localId | number | Yes | ID of the target OS account.| | localId | number | Yes | ID of the target OS account.|
| localName | string | Yes | Account name to set. | | localName | string | Yes | Account name to set. |
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :---------------------------------- | | :------------------ | :---------------------------------- |
...@@ -663,7 +663,7 @@ Obtains the number of OS accounts created. This API uses a promise to return the ...@@ -663,7 +663,7 @@ Obtains the number of OS accounts created. This API uses a promise to return the
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -712,7 +712,7 @@ Obtains the ID of the OS account to which the current process belongs. This API ...@@ -712,7 +712,7 @@ Obtains the ID of the OS account to which the current process belongs. This API
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -769,7 +769,7 @@ Obtains the OS account ID based on the process UID. This API uses a promise to r ...@@ -769,7 +769,7 @@ Obtains the OS account ID based on the process UID. This API uses a promise to r
| ------ | ------ | ---- | --------- | | ------ | ------ | ---- | --------- |
| uid | number | Yes | Process UID.| | uid | number | Yes | Process UID.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -831,7 +831,7 @@ Obtains the OS account ID based on domain account information. This API uses a p ...@@ -831,7 +831,7 @@ Obtains the OS account ID based on domain account information. This API uses a p
| ---------- | --------------------------------------- | ---- | ------------ | | ---------- | --------------------------------------- | ---- | ------------ |
| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information.| | domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -885,7 +885,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -885,7 +885,7 @@ This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -946,7 +946,7 @@ Obtains all constraints enabled for an OS account. This API uses a promise to re ...@@ -946,7 +946,7 @@ Obtains all constraints enabled for an OS account. This API uses a promise to re
| ------- | ------ | ---- | ------------ | | ------- | ------ | ---- | ------------ |
| localId | number | Yes | ID of the target OS account.| | localId | number | Yes | ID of the target OS account.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------- | :----------------------------------------------------------- | | :--------------------------------- | :----------------------------------------------------------- |
...@@ -1004,7 +1004,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1004,7 +1004,7 @@ This is a system API and cannot be called by third-party applications.
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :---------------------------------------------------------- | :----------------------------------------------------------- | | :---------------------------------------------------------- | :----------------------------------------------------------- |
...@@ -1056,7 +1056,7 @@ Obtains information about all activated OS accounts. This API uses a promise to ...@@ -1056,7 +1056,7 @@ Obtains information about all activated OS accounts. This API uses a promise to
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------- | :----------------------------------------------------------- | | :--------------------------------- | :----------------------------------------------------------- |
...@@ -1122,7 +1122,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1122,7 +1122,7 @@ This is a system API and cannot be called by third-party applications.
| localName | string | Yes | Name of the OS account to create.| | localName | string | Yes | Name of the OS account to create.|
| type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.| | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------------------- | :----------------------------------------------------------- | | :--------------------------------------------- | :----------------------------------------------------------- |
...@@ -1189,7 +1189,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1189,7 +1189,7 @@ This is a system API and cannot be called by third-party applications.
| type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.| | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.|
| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. | | domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. |
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------------------- | :----------------------------------------------------------- | | :--------------------------------------------- | :----------------------------------------------------------- |
...@@ -1243,7 +1243,7 @@ Obtains information about the OS account to which the current process belongs. T ...@@ -1243,7 +1243,7 @@ Obtains information about the OS account to which the current process belongs. T
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------------------- | :----------------------------------------------------------- | | :--------------------------------------------- | :----------------------------------------------------------- |
...@@ -1308,7 +1308,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1308,7 +1308,7 @@ This is a system API and cannot be called by third-party applications.
| ------- | ------ | ---- | -------------------- | | ------- | ------ | ---- | -------------------- |
| localId | number | Yes | ID of the target OS account.| | localId | number | Yes | ID of the target OS account.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------------------- | :----------------------------------------------------------- | | :--------------------------------------------- | :----------------------------------------------------------- |
...@@ -1358,7 +1358,7 @@ Obtains the type of the OS account to which the current process belongs. This AP ...@@ -1358,7 +1358,7 @@ Obtains the type of the OS account to which the current process belongs. This AP
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------------------- | :----------------------------------------------------------- | | :--------------------------------------------- | :----------------------------------------------------------- |
...@@ -1411,7 +1411,7 @@ Obtains the ID of this distributed virtual device. This API uses a promise to re ...@@ -1411,7 +1411,7 @@ Obtains the ID of this distributed virtual device. This API uses a promise to re
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -1476,7 +1476,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1476,7 +1476,7 @@ This is a system API and cannot be called by third-party applications.
| ------- | ------ | ---- | ------------ | | ------- | ------ | ---- | ------------ |
| localId | number | Yes | ID of the target OS account.| | localId | number | Yes | ID of the target OS account.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -1547,7 +1547,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1547,7 +1547,7 @@ This is a system API and cannot be called by third-party applications.
| localId | number | Yes | ID of the target OS account.| | localId | number | Yes | ID of the target OS account.|
| photo | string | Yes | Profile photo information. | | photo | string | Yes | Profile photo information. |
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :---------------------------------- | | :------------------ | :---------------------------------- |
...@@ -1609,7 +1609,7 @@ Obtains the OS account ID based on the SN. This API uses a promise to return the ...@@ -1609,7 +1609,7 @@ Obtains the OS account ID based on the SN. This API uses a promise to return the
| ------------ | ------ | ---- | ---------- | | ------------ | ------ | ---- | ---------- |
| serialNumber | number | Yes | Account SN.| | serialNumber | number | Yes | Account SN.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -1667,7 +1667,7 @@ Obtains the SN of an OS account based on the account ID. This API uses a promise ...@@ -1667,7 +1667,7 @@ Obtains the SN of an OS account based on the account ID. This API uses a promise
| ------- | ------ | ---- | ------------ | | ------- | ------ | ---- | ------------ |
| localId | number | Yes | ID of the target OS account.| | localId | number | Yes | ID of the target OS account.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -1787,7 +1787,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1787,7 +1787,7 @@ This is a system API and cannot be called by third-party applications.
| ------- | ------ | ---- | ------------ | | ------- | ------ | ---- | ------------ |
| uid | number | Yes | Process UID.| | uid | number | Yes | Process UID.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -1836,7 +1836,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1836,7 +1836,7 @@ This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
...@@ -1898,7 +1898,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1898,7 +1898,7 @@ This is a system API and cannot be called by third-party applications.
| localId | number | Yes | ID of the target OS account.| | localId | number | Yes | ID of the target OS account.|
| constraint | string | Yes | Name of the [constraint](#constraints) to query.| | constraint | string | Yes | Name of the [constraint](#constraints) to query.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :----------------------------------------------------------- | | :-------------------- | :----------------------------------------------------------- |
......
...@@ -3,13 +3,6 @@ ...@@ -3,13 +3,6 @@
## setTimeout ## setTimeout
## Modules to Import
```
import Time from '@ohos.Time';
```
setTimeout(handler[,delay[,…args]]): number setTimeout(handler[,delay[,…args]]): number
Sets a timer for the system to call a function after the timer goes off. Sets a timer for the system to call a function after the timer goes off.
......
# Image # 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. > 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 ## 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 ## Child Components
None Not supported
## APIs ## APIs
Image(value: {uri: string | PixelMap}) Image(src: string | PixelMap | Resource)
- Parameters Obtains an image from the specified source for subsequent rendering and display.
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| uri | string | Yes | - | Image URI. Both local and Internal URIs are supported. |
**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 ## Attributes
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | --------------------- | ---------------------------------------- | ------------------------ | ---------------------------------------- |
| alt | string | - | Placeholder image displayed during loading. Both local and Internal URIs are supported. | | alt | string \| [Resource](../../ui/ts-types.md) | - | Placeholder image displayed during loading. Both local and Internet URIs are supported. |
| objectFit | ImageFit | ImageFit.Cover | Image scale type. | | objectFit | [ImageFit](#imagefit-enums) | 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. | | 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.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. | | 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.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. | | 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. 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. | | 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. | | 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 ### 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 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. |
| 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. |
## Events ### 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 | | 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. | | Original | The image is rendered based on the original image, including the color. |
| onError(callback: (event?: { componentWidth: number, componentHeight: number }) =&gt; void) | An exception occurs during image loading. | | Template | The image is rendered as a template image, and its color is ignored.|
| 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. |
## Events
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 ## Example
### Loading Images
``` Load and display different types of images and set the scale type of the images.
// Image1
```ts
@Entry @Entry
@Component @Component
struct ImageExample1 { struct ImageExample1 {
...@@ -143,9 +161,9 @@ struct ImageExample1 { ...@@ -143,9 +161,9 @@ struct ImageExample1 {
![en-us_image_0000001211898484](figures/en-us_image_0000001211898484.gif) ![en-us_image_0000001211898484](figures/en-us_image_0000001211898484.gif)
### Setting Attributes
``` ```ts
// Image2
@Entry @Entry
@Component @Component
struct ImageExample2 { struct ImageExample2 {
...@@ -211,18 +229,18 @@ struct ImageExample2 { ...@@ -211,18 +229,18 @@ struct ImageExample2 {
![en-us_image_0000001212058474](figures/en-us_image_0000001212058474.png) ![en-us_image_0000001212058474](figures/en-us_image_0000001212058474.png)
### Invoking Events
``` ```ts
// Image3
@Entry @Entry
@Component @Component
struct ImageExample3 { struct ImageExample3 {
@State width: number = 0 @State width: number = 0
@State height: number = 0 @State height: number = 0
private on: Resource = $r('app.media.wifi_on') private on: Resource = $r('app.media.image_on')
private off: Resource = $r('app.media.wifi_off') private off: Resource = $r('app.media.image_off')
private on2off: Resource = $r('app.media.wifi_on2off') private on2off: Resource = $r('app.media.image_on2off')
private off2on: Resource = $r('app.media.wifi_off2on') private off2on: Resource = $r('app.media.image_off2on')
@State src: Resource = this.on @State src: Resource = this.on
build() { build() {
...@@ -237,6 +255,7 @@ struct ImageExample3 { ...@@ -237,6 +255,7 @@ struct ImageExample3 {
}) })
.objectFit(ImageFit.Cover) .objectFit(ImageFit.Cover)
.height(180).width(180) .height(180).width(180)
// Obtain the size of an image after the image loading is complete.
.onComplete((msg: { width: number,height: number }) => { .onComplete((msg: { width: number,height: number }) => {
this.width = msg.width this.width = msg.width
this.height = msg.height this.height = msg.height
...@@ -249,7 +268,7 @@ struct ImageExample3 { ...@@ -249,7 +268,7 @@ struct ImageExample3 {
offset: { x: 0, y: 20 } offset: { x: 0, y: 20 }
}) })
} }
// Add a click event so that a specific image is loaded upon clicking.
Image(this.src) Image(this.src)
.width(120).height(120) .width(120).height(120)
.onClick(() => { .onClick(() => {
......
# Marquee # Marquee
> **NOTE**<br> > **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<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 ## Required Permissions
...@@ -15,7 +16,7 @@ None ...@@ -15,7 +16,7 @@ None
## Child Components ## Child Components
None Not supported
## APIs ## APIs
...@@ -23,28 +24,29 @@ None ...@@ -23,28 +24,29 @@ None
Marquee(value: { start: boolean, step?: number, loop?: number, fromStart?: boolean, src: string }) Marquee(value: { start: boolean, step?: number, loop?: number, fromStart?: boolean, src: string })
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| start | boolean | Yes | - | Whether to start scrolling. | | start | boolean | Yes| - | Whether to start scrolling.|
| step | number | No | 6 | Scrolling step. | | 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. | | 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. | | fromStart | boolean | No| true | Whether the text scrolls from the start.|
| src | string | Yes | - | Text to scroll. | | src | string | Yes| - | Text to scroll.|
## Events ## Events
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| onStart(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee starts 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. | | 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. | | onFinish(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee has finished scrolling.|
## Example ## Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct MarqueeExample { struct MarqueeExample {
...@@ -63,6 +65,7 @@ struct MarqueeExample { ...@@ -63,6 +65,7 @@ struct MarqueeExample {
fromStart: this.fromStart, fromStart: this.fromStart,
src: this.src src: this.src
}) })
.width(400)
.fontColor(Color.White) .fontColor(Color.White)
.fontSize(50) .fontSize(50)
.allowScale(false) .allowScale(false)
......
# Search # Search
The **\<Search>** component provides an input area for users to search.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Search>** component provides an input area for users to search.
## Required Permissions ## Required Permissions
...@@ -24,7 +24,7 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll ...@@ -24,7 +24,7 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| value | string | No| - | Text input in the search text box. | | value | string | No| - | Text input in the search text box. |
| placeholder | string | No | - | Text displayed when there is no input. | | placeholder | string | No | - | Text displayed when there is no input. |
| icon | string | No| - | Path to the search icon. By default, the system search icon is used. The supported icon formats are svg, jpg, and png. | | icon | string | No| - | Path to the search icon. By default, the system search icon is used. The supported icon formats are .svg, .jpg, and .png. |
| controller | SearchController | No| - | Controller. | | controller | SearchController | No| - | Controller. |
...@@ -36,7 +36,6 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll ...@@ -36,7 +36,6 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll
| placeholderColor | [ResourceColor](../../ui/ts-types.md) | - | Placeholder text color. | | placeholderColor | [ResourceColor](../../ui/ts-types.md) | - | Placeholder text color. |
| placeholderFont | [Font](../../ui/ts-types.md) | - | Placeholder text style. | | placeholderFont | [Font](../../ui/ts-types.md) | - | Placeholder text style. |
| textFont | [Font](../../ui/ts-types.md) | - | Text font for the search text box. | | textFont | [Font](../../ui/ts-types.md) | - | Text font for the search text box. |
| copyOption<sup>9+</sup> | boolean\|[CopyOption](ts-basic-components-text.md) | true | Whether copy and paste is allowed. |
## Events ## Events
......
...@@ -21,13 +21,14 @@ This component contains the child component [\<ListItem>](ts-container-listitem. ...@@ -21,13 +21,14 @@ This component contains the child component [\<ListItem>](ts-container-listitem.
## APIs ## APIs
List(value:{space?: number, initialIndex?: number}) List(value:{space?: number | string, initialIndex?: number, scroller?: Scroller})
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| space | number | No | 0 | Spacing between list items. | | space | number&nbsp;\|&nbsp;string | 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. | | 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 ## Attributes
...@@ -36,8 +37,8 @@ List(value:{space?: number, initialIndex?: number}) ...@@ -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. | | 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. | | 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. | | editMode | boolean | false | Whether the **\<List>** component is in editable mode. |
| edgeEffect | EdgeEffect | EdgeEffect.Spring | Sliding effect. For details, see EdgeEffect enums. | | 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. | | 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. | | 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. | | 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}) ...@@ -48,7 +49,7 @@ List(value:{space?: number, initialIndex?: number})
| Name | Description | | 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. | | 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 - ListItemAlign enums
...@@ -64,7 +65,8 @@ List(value:{space?: number, initialIndex?: number}) ...@@ -64,7 +65,8 @@ List(value:{space?: number, initialIndex?: number})
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| onItemDelete(index: number) =&gt; boolean | Triggered when a list item is deleted. | | 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** > **NOTE**
> >
...@@ -106,9 +108,9 @@ struct ListExample { ...@@ -106,9 +108,9 @@ struct ListExample {
}.editable(true) }.editable(true)
}, item => item) }, item => item)
} }
.listDirection(Axis.Vertical) // Arrangement direction .listDirection(Axis.Vertical) // Direction in which the list items are arranged.
.divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // Divider line .divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // Style of the divider for the list items.
.edgeEffect(EdgeEffect.None) // No effect when sliding to the edge .edgeEffect(EdgeEffect.None) // No effect when the list is scrolled to the edge.
.chainAnimation(false) // Chained animations are disabled. .chainAnimation(false) // Chained animations are disabled.
.onScrollIndex((firstIndex: number, lastIndex: number) => { .onScrollIndex((firstIndex: number, lastIndex: number) => {
console.info('first' + firstIndex) console.info('first' + firstIndex)
...@@ -166,7 +168,7 @@ struct ListLanesExample { ...@@ -166,7 +168,7 @@ struct ListLanesExample {
.lanes({ minLength: 40, maxLength: 60 }) .lanes({ minLength: 40, maxLength: 60 })
.alignListItem(this.alignListItem) .alignListItem(this.alignListItem)
Button("Change alignListItem: "+ this.alignListItem).onClick(() => { Button("Change alignListItem:" + this.alignListItem).onClick(() => {
if (this.alignListItem == ListItemAlign.Start) { if (this.alignListItem == ListItemAlign.Start) {
this.alignListItem = ListItemAlign.Center this.alignListItem = ListItemAlign.Center
} else if (this.alignListItem == ListItemAlign.Center) { } else if (this.alignListItem == ListItemAlign.Center) {
...@@ -179,3 +181,4 @@ struct ListLanesExample { ...@@ -179,3 +181,4 @@ struct ListLanesExample {
} }
} }
``` ```
# Action Sheet # 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. > 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 ...@@ -17,25 +18,25 @@ None
show(options: { paramObject1}) show(options: { paramObject1})
Defines and shows the action sheet. Defines and shows an action sheet.
- paramObject1 parameters - paramObject1 parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| title | string \|[Resource](../../ui/ts-types.md#resource) | No | None | Title 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#resource) | | | Content 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. | | 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. | | 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. | | 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#resource)<br/>dy: Length\|[Resource](../../ui/ts-types.md#resource)<br/>} | No | - | Offset of the dialog box relative to the alignment position. | | 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&lt;SheetInfo&gt; | Yes | - | Options in the dialog box. Each option supports the image, text, and callback. | | sheets | Array<SheetInfo&gt; | Yes | - | Options in the dialog box. Each option supports the image, text, and callback. |
- SheetInfo parameters - SheetInfo parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| title | string | Yes | - | Sheet text. | | title | string \| [Resource](../../ui/ts-types.md) | Yes | - | Sheet text. |
| icon | string | No | None | Sheet icon. | | icon | string \| [Resource](../../ui/ts-types.md) | No | None | Sheet icon. |
| action | ()=&gt;void | Yes | - | Callback when the sheet is selected. | | action | ()=&gt;void | Yes | - | Callback when the sheet is selected. |
...@@ -43,10 +44,11 @@ Defines and shows the action sheet. ...@@ -43,10 +44,11 @@ Defines and shows the action sheet.
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ActionSheetExapmle { struct ActionSheetExample {
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button('Click to Show ActionSheet') Button('Click to Show ActionSheet')
......
# Alert Dialog Box # Alert Dialog Box
> **NOTE**<br> > **NOTE**
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. >
> 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. 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.
...@@ -12,38 +13,39 @@ The **<AlertDialog\>** component is used to display an alert dialog box. You can ...@@ -12,38 +13,39 @@ The **<AlertDialog\>** component is used to display an alert dialog box. You can
| 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 - paramObject1 parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| title | string \|[Resource](../../ui/ts-types.md#resource) | | | Title of a dialog box. | | title | string \| [Resource](../../ui/ts-types.md) | No | - | Title of a dialog box. |
| message | string \|[Resource](../../ui/ts-types.md#resource) | | | Content of the 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. | | 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. | | 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. | | 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#resource),<br/>dy: Length \|[Resource](../../ui/ts-types.md#resource)<br/>} | | | Offset of the dialog box relative to the alignment position. | | 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. | | gridCount | number | No | - | Number of grid columns occupied by the width of the dialog box. |
- paramObject2 parameters - paramObject2 parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| title | string \|[Resource](../../ui/ts-types.md#resource) | No | - | Title of a dialog box. | | title | string \| [Resource](../../ui/ts-types.md) | No | - | Title of a dialog box. |
| message | string \|[Resource](../../ui/ts-types.md#resource) | Yes | - | Content of the 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. | | 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. | | 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#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. | | 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. | | 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. | | 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#resource),<br/>dy: Length \|[Resource](../../ui/ts-types.md#resource)<br/>} | | | Offset of the dialog box relative to the alignment position. | | 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. | | gridCount | number | No | - | Number of grid columns occupied by the width of the dialog box. |
## Example ## Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct AlertDialogExample { struct AlertDialogExample {
......
# Transition of Shared Elements # 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** > **NOTE**
>
> This animationis supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > 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. ## Attributes
## Type
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
......
# Border # Border
You can set border styles for components.
> **NOTE** > **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 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. > 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 ## Required Permissions
None None
## Attributes ## Attributes
...@@ -27,11 +31,25 @@ None ...@@ -27,11 +31,25 @@ None
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | [Length](../../ui/ts-types.md) | 0 | No| Border width.| | width | [Length](../../ui/ts-types.md) | 0 | No| Border width.|
| color | [ResourceColor](../../ui/ts-types.md) | 'Black' | No| Border color.| | 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.| | 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 - BorderStyle enums
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| Dotted | Dotted border. The radius of a dot is half of **borderWidth**.| | Dotted | Dotted border. The radius of a dot is half of **borderWidth**.|
...@@ -52,6 +70,10 @@ struct BorderExample { ...@@ -52,6 +70,10 @@ struct BorderExample {
Text('dashed') Text('dashed')
.borderStyle(BorderStyle.Dashed).borderWidth(5).borderColor(0xAFEEEE).borderRadius(10) .borderStyle(BorderStyle.Dashed).borderWidth(5).borderColor(0xAFEEEE).borderRadius(10)
.width(120).height(120).textAlign(TextAlign.Center).fontSize(16) .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 // Dotted border
Text('dotted') Text('dotted')
.border({ width: 5, color: 0x317AF7, radius: 10, style: BorderStyle.Dotted }) .border({ width: 5, color: 0x317AF7, radius: 10, style: BorderStyle.Dotted })
......
# Menu Control # Menu Control
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** 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. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -13,28 +16,29 @@ None ...@@ -13,28 +16,29 @@ None
| Name | Type | Default Value | Description | | 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. | | 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: [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. | | 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 - MenuItem
| Name | Type | Description | | Name | Type | Description |
| ------ | ------------- | ---------------------------------------- | | ------ | ----------------------- | ----------- |
| value | string | Menu item text. | | value | string | Menu item text. |
| action | () =&gt; void | Action triggered when a menu item is clicked. | | action | ()&nbsp;=&gt;&nbsp;void | Action triggered when a menu item is clicked.|
- ResponseType<sup>8+</sup> - ResponseType<sup>8+</sup>
| Value | Description | | Value | Description |
| ---------- | ---------------------------------------- | | ---------- | ------------- |
| LongPress | The menu is displayed when the component is long-pressed. | | LongPress | The menu is displayed when the component is long-pressed. |
| RightClick | The menu is displayed when the component is right-clicked. | | RightClick | The menu is displayed when the component is right-clicked.|
## Example ## Example
#### Menu with Textual Menu Items #### Menu with Textual Menu Items
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct MenuExample { struct MenuExample {
...@@ -66,7 +70,8 @@ struct MenuExample { ...@@ -66,7 +70,8 @@ struct MenuExample {
#### Menu with Custom Menu Items #### Menu with Custom Menu Items
``` ```ts
// xxx.ets
import router from '@system.router'; import router from '@system.router';
@Entry @Entry
...@@ -116,7 +121,8 @@ struct MenuExample { ...@@ -116,7 +121,8 @@ struct MenuExample {
#### Context Menu (Displayed Upon Right-Clicking) #### Context Menu (Displayed Upon Right-Clicking)
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ContextMenuExample { struct ContextMenuExample {
......
# Shape Clipping # 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. > 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 ...@@ -13,16 +14,17 @@ None
## Attributes ## 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. | | 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 | - | Adds a mask of the specified shape to the current component. | | mask | Shape | - | Mask of the specified shape for the current component. |
## Example ## Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ClipAndMaskExample { struct ClipAndMaskExample {
...@@ -30,24 +32,24 @@ struct ClipAndMaskExample { ...@@ -30,24 +32,24 @@ struct ClipAndMaskExample {
Column({ space: 5 }) { Column({ space: 5 }) {
Text('clip').fontSize(9).width('90%').fontColor(0xCCCCCC) Text('clip').fontSize(9).width('90%').fontColor(0xCCCCCC)
// Clip the image by using a circle with a diameter of 280px. // 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 })) .clip(new Circle({ width: 80, height: 80 }))
.width('500px').height('280px') .width('500px').height('280px')
Row() { Row() {
Image('/comment/bg.jpg').width('500px').height('280px') Image($r('app.media.example')).width('500px').height('280px')
} }
.clip(true) .clip(true)
.borderRadius(20) .borderRadius(20)
Text('mask').fontSize(9).width('90%').fontColor(0xCCCCCC) Text('mask').fontSize(9).width('90%').fontColor(0xCCCCCC)
// Add a 500 px x 280 px mask to the image. // 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)) .mask(new Rect({ width: '500px', height: '280px' }).fill(Color.Gray))
.width('500px').height('280px') .width('500px').height('280px')
// Add a 280 px x 280 px circle mask to the image. // 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)) .mask(new Circle({ width: '280px', height: '280px' }).fill(Color.Gray))
.width('500px').height('281px') .width('500px').height('281px')
} }
......
# Click Event # 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. > This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## Required Permissions
None None
...@@ -12,12 +13,12 @@ None ...@@ -12,12 +13,12 @@ None
## Events ## 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). | | 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 | | Name | Type | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -25,30 +26,30 @@ None ...@@ -25,30 +26,30 @@ None
| screenY | number | Y coordinate of the click relative to the upper edge of the screen. | | 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. | | 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. | | 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. | | timestamp | number | Timestamp of the event. |
- EventTarget<sup>8+</sup> attributes ## EventTarget<sup>8+</sup>
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| area | Area | Area information of the target element.| | area | [Area](#area8) | Area information of the target element.|
- Area<sup>8+</sup> attributes ## Area<sup>8+</sup>
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| width | number | Width of the target element, in vp. | | width | number | Width of the target element, in vp. |
| height | number | Height 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. | | position | [Position](#position8) | 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. | | 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 | | Name | Type | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| x | number | X-coordinate, in vp. | | x | number | X-coordinate, in vp. |
| y | number | Y-coordinate, in vp. | | y | number | Y-coordinate, in vp. |
## Example ## Example
......
# Drag/Drop Event # Drag Event
A drag event is triggered when a component is dragged.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## 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. | | 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/>**NOTE**<br/>This event is valid only when the **onDrop** event is listened to. | | 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/>**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/>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. | | 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. | | 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 - extraParam
Returns additional information required for dragging an item. 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**. **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 | | 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. | | 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/>**NOTE**<br/>This attribute is valid only in the drag event of the **List** 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 ### DragEvent
......
# Key Event # 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** > **NOTE**
> This method is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. >
> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## Required Permissions
...@@ -12,20 +14,20 @@ None ...@@ -12,20 +14,20 @@ None
## Events ## 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 - Attributes
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| type | KeyType | Type of a key. | | type | [KeyType](#keytype-enums) | Type of a key. |
| keyCode | number | Key code. | | keyCode | number | Key code. |
| keyText | string | Key value. | | keyText | string | Key value. |
| keySource | KeySource | Type of the input device that triggers the key event. | | 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. | | 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. | | 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. | | timestamp | number | Timestamp when the key is pressed. |
...@@ -35,35 +37,38 @@ None ...@@ -35,35 +37,38 @@ None
| -------- | -------- | | -------- | -------- |
| stopPropagation(): void | Stops the event from bubbling upwards or downwards. | | stopPropagation(): void | Stops the event from bubbling upwards or downwards. |
- KeyType enums ## KeyType Enums
| Name | Description |
| -------- | -------- |
| Down | The key is pressed. |
| Up | The key is released. |
| 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 ## KeySource Enums
| Value | Behavior | Physical Button | | Name | Description |
| -------- | -------- | -------- | | -------- | -------- |
| 19 | Upward | Up button. | | Unknown | Unknown input device. |
| 20 | Downward | Down button. | | [KeyCode](#common-keycode-enums) | The input device is a keyboard. |
| 21 | Leftward | Left button. |
| 22 | Rightward | Right button. | ## Common KeyCode Enums
| 23 | OK | **OK** key on a remote control. |
| 66 | OK | **Enter** key on a keyboard. | | Value | Behavior | Physical Button |
| 160 | OK | **Enter** button on the numeric keypad. | | -------- | -------- | -------- |
| 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 ## Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct KeyEventExample { struct KeyEventExample {
......
# Touch Event # 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. > 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 ...@@ -12,51 +14,51 @@ None
## Events ## Events
| Name | Pop-up | Description | | Name | Bubbling Supported| Description |
| -------- | -------- | -------- | | ---------------------------------------- | ---- | ---------------------------------------- |
| onTouch(callback: (event?: TouchEvent) =&gt; void) | Yes | Invoked when a touch action is triggered. For details about the event parameters, see [TouchEvent](#touchevent). | | 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 - Attributes
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | ------------------- | ---------------------------------------- | ------------ |
| type | TouchType | Type of a touch event. | | type | TouchType | Type of the touch event. |
| touches | Array&lt;TouchObject&gt; | All finger information. | | touches | Array&lt;[TouchObject](#touchobject)&gt; | All finger information. |
| changedTouches | Array&lt;TouchObject&gt; | Finger information changed. | | changedTouches | Array&lt;[TouchObject](#touchobject)&gt; | Finger information changed.|
| timestamp | number | Timestamp of the event. | | timestamp | number | Timestamp of the event. |
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md) | Target of the event. | | target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md#eventtarget8) | Target of the event. |
- APIs - APIs
| Name | Description | | Name | Description |
| -------- | -------- | | ---------------------- | ------- |
| stopPropagation(): void | Pop-up of the stop event. | | stopPropagation(): void| Stops the event from bubbling upwards or downwards.|
- TouchObject ## TouchObject
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | ------- | --------------------------- | ------------------- |
| type | TouchType | Type of a touch event. | | type | [TouchType](#touchtype-enums) | Type of the touch event. |
| id | number | Unique identifier of a finger. | | id | number | Unique identifier of a finger. |
| screenX | number | X coordinate of the touch point relative to the left edge of the screen. | | 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. | | 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. | | 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 to touch. | | y | number | Y-coordinate of the touch point relative to the upper edge of the element being touched. |
- TouchType ## TouchType Enums
| Name | Description | | Name | Description |
| -------- | -------- | | ------ | --------------- |
| Down | Trigger a touch event when a finger is pressed. | | Down | A finger is pressed. |
| Up | Trigger a touch event when a finger is lifted. | | Up | A finger is lifted. |
| Move | Trigger a touch event when a finger moves on the screen in pressed state. | | Move | A finger moves on the screen in pressed state.|
| Cancel | Trigger an event when a touch event is canceled. | | Cancel | A touch event is canceled. |
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
......
# Mouse Event # 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. > 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 ...@@ -12,48 +14,47 @@ None
## Events ## 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. | | 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. | | 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 ## MouseEvent
- Attributes | Name | Type | Description |
| Name | Type | Description | | -------- | -------- | -------- |
| -------- | -------- | -------- | | timestamp | number | Timestamp when the event is triggered. |
| 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. |
| 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. |
| 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. |
| 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. |
| y | number | Y-coordinate of the clicked point relative to the upper left corner of the component. | | button | [MouseButton](#mousebutton) | Mouse button. |
| button | MouseButton | Mouse button. | | action | [MouseAction](#mouseaction) | Event action. |
| action | MouseAction | Event action. |
## MouseButton
| Name | Type | Description |
- MouseButton attributes | -------- | -------- | -------- |
| Name | Type | Description | | Left | number | Left mouse button. |
| -------- | -------- | -------- | | Right | number | Right mouse button. |
| Left | number | Left mouse button. | | Middle | number | Middle mouse button. |
| Right | number | Right mouse button. | | Back | number | Back button on the left of the mouse. |
| Middle | number | Middle mouse button. | | Forward | number | Forward button on the left of the mouse. |
| Back | number | Back button on the left of the mouse. | | None | number | No button. |
| Forward | number | Forward button on the left of the mouse. |
| None | number | No button. | ## MouseAction
| Name | Type | Description |
- MouseAction attributes | -------- | -------- | -------- |
| Name | Type | Description | | Press | number | The mouse button is pressed. |
| -------- | -------- | -------- | | Release | number | The mouse button is released. |
| Press | number | The mouse button is pressed. | | Move | number | The mouse cursor moves. |
| Release | number | The mouse button is released. |
| Move | number | The mouse cursor moves. |
## Example ## Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct MouseEventExample { struct MouseEventExample {
......
...@@ -24,9 +24,13 @@ The table below lists only the API used in this guide. For more information, see ...@@ -24,9 +24,13 @@ The table below lists only the API used in this guide. For more information, see
## Declaring Permissions ## Declaring Permissions
### config.json Declare the permissions required by the app one by one in the project configuration file. The app cannot obtain the permissions that are not declared in the configuration file. The ability framework provides two models: Feature Ability (FA) model and Stage model. For more information, see [Ability Framework Overview](../ability/ability-brief.md).
Declare the permissions required by the app one by one in the **config.json** file. The app can obtain permissions that have been declared in the **config.json** file. Note that the app bundle structure and configuration file vary with the ability framework model.
### FA Model
For the apps based on the FA model, declare the permissions in the **config.json** file.
**Description of config.json** **Description of config.json**
...@@ -40,6 +44,41 @@ Declare the permissions required by the app one by one in the **config.json** fi ...@@ -40,6 +44,41 @@ Declare the permissions required by the app one by one in the **config.json** fi
**Example** **Example**
```json
{
"module" : {
"reqPermissions":[
{
"name" : "ohos.permission.PERMISSION1",
"reason": "$string:reason",
"usedScene": {
"abilities": [
"FormAbility"
],
"when":"inuse"
}
},
{
"name" : "ohos.permission.PERMISSION2",
"reason": "$string:reason",
"usedScene": {
"abilities": [
"FormAbility"
],
"when":"always"
}
}
],
}
}
```
### Stage Model
For the apps based on the stage model, declare the permissions in the **module.json5** file.
**Example**
```json ```json
{ {
"module" : { "module" : {
...@@ -68,11 +107,12 @@ Declare the permissions required by the app one by one in the **config.json** fi ...@@ -68,11 +107,12 @@ Declare the permissions required by the app one by one in the **config.json** fi
} }
} }
``` ```
## Declaring the ACL ## Declaring the ACL
The permission level of **ohos.permission.PERMISSION2** is **system_basic**, which is higher than the app's APL. In this case, use the ACL. The permission level of **ohos.permission.PERMISSION2** is **system_basic**, which is higher than the app's APL. In this case, use the ACL.
In addition to declaring all the permissions in the **config.json** file, you must declare the permissions whose levels are higher than the app's APL in the app's [profile](../quick-start/app-provision-structure.md). In this example, declare the permission under the **acls** field: In addition to declaring all the permissions in the configuration file, you must declare the permissions whose levels are higher than the app's APL in the app's [profile](../quick-start/app-provision-structure.md). In this example, declare the permission under the **acls** field:
```json ```json
{ {
"version-name": "1.0.0", "version-name": "1.0.0",
......
# Access Control Overview # Access Control Overview
## Introduction
AccessTokenManager (ATM) implements unified app permission management based on access tokens on OpenHarmony. AccessTokenManager (ATM) implements unified app permission management based on access tokens on OpenHarmony.
By default, apps can access limited system resources. However, in some cases, an app needs to access excess data (including personal data) and functions of the system or another app to implement extended functions. The system or apps must also share their data or functions through interfaces in an explicit manner. OpenHarmony uses app permissions to perform access control and prevent improper or malicious use of these data or functions. By default, apps can access limited system resources. However, in some cases, an app needs to access excess data (including personal data) and functions of the system or another app to implement extended functions. The system or apps must also share their data or functions through interfaces in an explicit manner. OpenHarmony uses app permissions to perform access control and prevent improper or malicious use of these data or functions.
...@@ -12,9 +11,9 @@ App permissions are used to protect the following objects: ...@@ -12,9 +11,9 @@ App permissions are used to protect the following objects:
Without the required permissions, an app cannot access or perform operations on the target object. Permissions must be clearly defined for apps. With well-defined app permissions, the system can standardize the behavior of apps and protect user privacy. Before an app accesses the target object, the target object verifies the app's permissions and denies the access if the app does not have required permissions. Without the required permissions, an app cannot access or perform operations on the target object. Permissions must be clearly defined for apps. With well-defined app permissions, the system can standardize the behavior of apps and protect user privacy. Before an app accesses the target object, the target object verifies the app's permissions and denies the access if the app does not have required permissions.
Currently, ATM performs app permission verification based on the token identity (Token ID). A token ID identifies an app. The ATM manages app permissions based on the app's token ID. Currently, ATM verifies app permissions based on the token identity (Token ID). A token ID identifies an app. The ATM manages app permissions based on the app's token ID.
## How to Develop ## Permission Workflow
Determine the permissions required for an app to access data or perform an operation. Declare the required permissions in the app installation package. Determine the permissions required for an app to access data or perform an operation. Declare the required permissions in the app installation package.
...@@ -22,12 +21,34 @@ Determine whether the required permissions need to be authorized by users. If ye ...@@ -22,12 +21,34 @@ Determine whether the required permissions need to be authorized by users. If ye
After the user grants permissions to the app, the app can access the data or perform the operation. After the user grants permissions to the app, the app can access the data or perform the operation.
The figure below shows the process. The figure below shows the permission workflow.
![](figures/permission-workflow.png) ![](figures/permission-workflow.png)
1. Refer to the figure below for the process of applying for app permissions.
![](figures/permission-application-process.png)
1. For details about the mapping between the application Ability Privilege Level (APL) and permission level, see [Permission Levels](#permission-levels).
2. The permission authorization modes include user_grant (permission granted by the user) and system_grant (permission granted by the system). For details, see [Permission Authorization Modes](#permission-authorization-mode).
3. A low-level app can have a high-level permission by using the Access Control List (ACL). For details, see [ACL](#acl).
## When to Use ## When to Use
### Basic Principles
Observe the following principles for permission management:
- Provide clear description about the app functions and scenarios for each permission required by the app so that users can clearly know why and when these permissions are required. Do not induce or mislead users' authorization. The permissions on an app must comply with the description provided in the app.
- Use the principle of least authority for user permissions. Allow only necessary permissions for service functions.
- When an app is started for the first time, avoid frequently displaying dialog boxes to request permissions. Allow the app to apply for permissions only when it needs to use the corresponding service functions.
- If a user rejects to authorize a permission, the user can still use functions irrelevant to this permission and can register and access the app.
- Provide no more message if a user rejects the authorization required by a function. Provide onscreen instructions to direct the user to grant the permission in **Settings** if the user triggers this function again or needs to use this function.
- All the permissions granted to apps must come from the [Permission List](permission-list.md). Custom permissions are not allowed for apps currently.
### Scenarios ### Scenarios
The following describes two common scenarios. The following describes two common scenarios.
...@@ -46,25 +67,13 @@ The following describes two common scenarios. ...@@ -46,25 +67,13 @@ The following describes two common scenarios.
ohos.permission.CAMERA (allowing the apps to use the camera to take photos and record videos) ohos.permission.CAMERA (allowing the apps to use the camera to take photos and record videos)
### Basic Principles
Observe the following principles for permission management:
- Provide clear description about the app functions and scenarios for each permission required by the app so that users can clearly know why and when these permissions are required. Do not induce or mislead users' authorization. The permissions on an app must comply with the description provided in the app.
- Use the principle of least authority for user permissions. Allow only necessary permissions for service functions.
- When an app is started for the first time, avoid frequently displaying dialog boxes to request permissions. Allow the app to apply for permissions only when it needs to use the corresponding service functions.
- If a user rejects to authorize a permission, the user can still use functions irrelevant to this permission and can register and access the app.
- Provide no more message if a user rejects the authorization required by a function. Provide onscreen instructions to direct the user to grant the permission in **Settings** if the user triggers this function again or needs to use this function.
- All the permissions granted to apps must come from the Permission List. Custom permissions are not allowed for apps currently.
## Permission Levels ## Permission Levels
To protect user privacy, ATM defines different permission levels based on the sensitivity of the data involved or the security threat of the ability. To protect user privacy, ATM defines different permission levels based on the sensitivity of the data involved or the security threat of the ability.
### App APL ### App APLs
The ability privilege level (APL) defines the priority of the app permission requested. Apps of different APLs can apply for permissions of different levels. The APL defines the priority of the app permission requested. Apps of different APLs can apply for permissions of different levels.
The table below describes the APLs. The table below describes the APLs.
...@@ -78,7 +87,7 @@ By default, apps are of the normal APL. ...@@ -78,7 +87,7 @@ By default, apps are of the normal APL.
For the app of the system_basic or system_core APL, declare the app APL level in the **apl** field in the app's profile, and use the profile signing tool to generate a certificate when developing the app installation package. For details about the signing process, see [Hapsigner Guide](hapsigntool-guidelines.md). For the app of the system_basic or system_core APL, declare the app APL level in the **apl** field in the app's profile, and use the profile signing tool to generate a certificate when developing the app installation package. For details about the signing process, see [Hapsigner Guide](hapsigntool-guidelines.md).
### Permission Levels ### Levels of Permissions
The permissions open to apps vary with the permission level. The permission levels include the following in ascending order of seniority. The permissions open to apps vary with the permission level. The permission levels include the following in ascending order of seniority.
...@@ -100,33 +109,6 @@ The permissions open to apps vary with the permission level. The permission leve ...@@ -100,33 +109,6 @@ The permissions open to apps vary with the permission level. The permission leve
The permissions of this type are not open to any app currently. The permissions of this type are not open to any app currently.
### ACL
As described above, permission levels and app APLs are in one-to-one correspondence. 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.
**Example**
The APL of app A is normal. App A needs to have permission B (system_basic level) and permission C (normal level).
In this case, you can use the ACL to grant permission B to app A.
For details, see [Using the ACL](#using-the-acl).
For details about whether the ACL is enabled for a permission, see [Permission List](permission-list.md).
### Using the ACL
If the permission required by an app has higher level than the app's APL, you can use the ACL to grant the permissions required.
In addition to the preceding [authorization processes](#authorization-processes), you must declare the ACL.
In other words, in addition to declaring the required permissions in the **config.json** file, you must declare the high-level permissions in the app's [profile](accesstoken-guidelines.md#declaring-the-acl). The subsequent steps of authorization are the same.
**NOTE**
Declare the target ACL in the **acl** field of the app's profile in the app installation package, and generate a certificate using the profile signing tool. For details about the signing process, see [Hapsigner Guide](hapsigntool-guidelines.md).
## Permission Authorization Modes ## Permission Authorization Modes
Permissions can be classified into the following types based on the authorization mode: Permissions can be classified into the following types based on the authorization mode:
...@@ -151,15 +133,15 @@ Permissions can be classified into the following types based on the authorizatio ...@@ -151,15 +133,15 @@ Permissions can be classified into the following types based on the authorizatio
The process for an app obtaining the required permissions varies depending on the permission authorization mode. The process for an app obtaining the required permissions varies depending on the permission authorization mode.
- For a system_grant permission, you need to [declare the permission](accesstoken-guidelines.md) in the **config.json** file. The permission will be pre-granted when the app is installed. - For a system_grant permission, you need to [declare the permission](accesstoken-guidelines.md#declaring-permissions) in the configuration file. The permission will be pre-granted when the app is installed.
- For a user_grant permission, you need to [declare the permission](accesstoken-guidelines.md) in the **config.json** file, and a dialog box needs to be displayed to request user authorization during the running of the app. - For a user_grant permission, you need to [declare the permission](accesstoken-guidelines.md#declaring-permissions) in the configuration file and trigger user authorization through a dialog box during the running of the app.
### Permission Authorization Process (user_grant) ### Permission Authorization Process (user_grant)
The procedure is as follows: The procedure is as follows:
1. In the **config.json** file, declare the permissions required by the app. For details, see [Access Control Development](accesstoken-guidelines.md). 1. In the configuration file, declare the permissions required by the app. For details, see [Access Control Development](accesstoken-guidelines.md).
2. Associate the object that requires the permissions in the app with the target permissions. In this way, the user knows the operations to be granted with the specified permissions. 2. Associate the object that requires the permissions in the app with the target permissions. In this way, the user knows the operations to be granted with the specified permissions.
...@@ -170,7 +152,33 @@ The procedure is as follows: ...@@ -170,7 +152,33 @@ The procedure is as follows:
**Precautions** **Precautions**
- Check the app's permission each time before the operation requiring the permission is performed. - Check the app's permission each time before the operation requiring the permission is performed.
- To check whether a user has granted specific permissions to your app, use the [verifyAccessToken](../reference/apis/js-apis-abilityAccessCtrl.md) method. This method returns [PERMISSION_GRANTED](../reference/apis/js-apis-abilityAccessCtrl.md) or [PERMISSION_DENIED](../reference/apis/js-apis-abilityAccessCtrl.md). For details about the sample code, see [Access Control Development](accesstoken-guidelines.md). - To check whether a user has granted specific permissions to your app, use the [verifyAccessToken](../reference/apis/js-apis-abilityAccessCtrl.md) method. This method returns [PERMISSION_GRANTED](../reference/apis/js-apis-abilityAccessCtrl.md) or [PERMISSION_DENIED](../reference/apis/js-apis-abilityAccessCtrl.md). For details about the sample code, see [Access Control Development](accesstoken-guidelines.md).
- Users must be able to understand and control the authorization of user_grant permissions. During the running process, the app requiring user authorization must proactively call the API to dynamically request the authorization. Then, the system displays a dialog box asking the user to grant the requested permission. The user will determine whether to grant the permission based on the running context of the app. - Users must be able to understand and control the authorization of user_grant permissions. During the running process, the app requiring user authorization must proactively call the API to dynamically request the authorization. Then, the system displays a dialog box asking the user to grant the requested permission. The user will determine whether to grant the permission based on the running context of the app.
- The permission authorized is not permanent, because the user may revoke the authorization at any time. Therefore, even if the user has granted the requested permission to the app, the app must check for the permission before calling the API controlled by this permission. - The permission authorized is not permanent, because the user may revoke the authorization at any time. Therefore, even if the user has granted the requested permission to the app, the app must check for the permission before calling the API controlled by this permission.
## ACL
As described above, permission levels and app APLs are in one-to-one correspondence. In principle, **an app with a lower APL cannot apply for higher permissions by default**.
The ACL makes low-level apps have high-level permissions.
**Example**
The APL of app A is normal. App A needs to have permission B (system_basic level) and permission C (normal level).
In this case, you can use the ACL to grant permission B to app A.
For details, see [Using the ACL](#using-the-acl).
For details about whether a permission can be enabled through the ACL, see the [Permission List](permission-list.md).
### Using the ACL
If the permission required by an app has higher level than the app's APL, you can use the ACL to grant the permissions required.
In addition to the preceding [authorization processes](#authorization-processes), you must declare the ACL.
In other words, in addition to declaring the required permissions in the **config.json** file, you must declare the high-level permissions in the app's [profile](accesstoken-guidelines.md#declaring-the-acl). The subsequent steps of authorization are the same.
**NOTE**
Declare the target ACL in the **acl** field of the app's profile in the app installation package, and generate a certificate using the profile signing tool. For details about the signing process, see [Hapsigner Guide](hapsigntool-guidelines.md).
# Permission List # 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) For details about permission usage examples, see [Access Control Development](accesstoken-guidelines.md).
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).
| Permission | APL | Authorization Mode | Enable ACL| Description | | Permission | APL | Authorization Mode | Enable ACL| Description |
| -------------------------------------------------------- | ------------ | ------------ | ------- | ------------------------------------------------------------ | | -------------------------------------------------------- | ------------ | ------------ | ------- | ------------------------------------------------------------ |
...@@ -26,10 +20,7 @@ The following lists the permissions defined by the system. For details about per ...@@ -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.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.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.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 | 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 | 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.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. | | 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 ...@@ -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.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.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.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 { ...@@ -62,7 +62,7 @@ struct ComponentA {
@StorageProp('languageCode') lang: string = 'en' @StorageProp('languageCode') lang: string = 'en'
private label: string = 'count' private label: string = 'count'
private aboutToAppear() { aboutToAppear() {
this.label = (this.lang === 'en') ? 'Number' : 'Count' this.label = (this.lang === 'en') ? 'Number' : 'Count'
} }
......
# A Method for Rapidly Porting the OpenHarmony Linux Kernel<a name="EN-US_TOPIC_0000001162545194"></a> # A Method for Rapidly Porting the OpenHarmony Linux Kernel
## Overview<a name="section28051350151118"></a> ## Overview
This document describes how to quickly port OpenHarmony to a third-party chip platform by using the existing capabilities of the Linux kernel of the third-party chip platform. This document describes how to quickly port OpenHarmony to a third-party chip platform by using the existing capabilities of the Linux kernel of the third-party chip platform.
## Overall Porting Approach<a name="section994883124"></a> ## Overall Porting Approach
### Kernel Mode Layer and User Mode Layer<a name="section953481431217"></a> ### Kernel Mode Layer and User Mode Layer
For easy description, we divide the OpenHarmony architecture into two parts: For easy description, we divide the OpenHarmony architecture into two parts:
...@@ -20,7 +20,7 @@ The user mode layer includes other parts except the OpenHarmony kernel layer. It ...@@ -20,7 +20,7 @@ The user mode layer includes other parts except the OpenHarmony kernel layer. It
The user mode layer of OpenHarmony is loosely coupled with the third-party chip platform and is easy to port. The kernel and HDF at the kernel mode layer are closely coupled with the third-party chip platform and are difficult to port. This document focus on the porting of the kernel mode layer. In addition, it describes only the quick porting of the Linux kernel. It does not include the porting of LiteOS. The user mode layer of OpenHarmony is loosely coupled with the third-party chip platform and is easy to port. The kernel and HDF at the kernel mode layer are closely coupled with the third-party chip platform and are difficult to port. This document focus on the porting of the kernel mode layer. In addition, it describes only the quick porting of the Linux kernel. It does not include the porting of LiteOS.
### Composition of the Kernel Mode Layer<a name="section81437528121"></a> ### Composition of the Kernel Mode Layer
The OpenHarmony kernel mode layer can be further divided as follows: The OpenHarmony kernel mode layer can be further divided as follows:
...@@ -51,7 +51,7 @@ The standard LTS Linux kernel and third-party SoC chip platform code constitute ...@@ -51,7 +51,7 @@ The standard LTS Linux kernel and third-party SoC chip platform code constitute
In the following, we elaborate how to port OpenHarmony that uses with the third-party Linux kernel. In the following, we elaborate how to port OpenHarmony that uses with the third-party Linux kernel.
### Overall Porting Process<a name="section86060191"></a> ### Overall Porting Process
The porting process is as follows: The porting process is as follows:
...@@ -59,11 +59,11 @@ The porting process is as follows: ...@@ -59,11 +59,11 @@ The porting process is as follows:
2. Port the OpenHarmony basic kernel-mode code. 2. Port the OpenHarmony basic kernel-mode code.
3. Port OpenHarmony mandatory kernel-mode features \(such as HDF\). 3. Port OpenHarmony mandatory kernel-mode features \(such as HDF\).
## Procedure<a name="section98871341171310"></a> ## Procedure
The following uses Raspberry Pi 3b \(BCM2837\) as an example to describe how to port OpenHarmony to Raspberry Pi. The following uses Raspberry Pi 3b \(BCM2837\) as an example to describe how to port OpenHarmony to Raspberry Pi.
### Setting Up the Environment<a name="section16584650181314"></a> ### Setting Up the Environment
1. Copy the third-party kernel code to the OpenHarmony build environment. 1. Copy the third-party kernel code to the OpenHarmony build environment.
...@@ -84,7 +84,7 @@ The following uses Raspberry Pi 3b \(BCM2837\) as an example to describe how to ...@@ -84,7 +84,7 @@ The following uses Raspberry Pi 3b \(BCM2837\) as an example to describe how to
# Configure the build environment, and use clang provided by the project to build the Raspberry Pi kernel source code. # Configure the build environment, and use clang provided by the project to build the Raspberry Pi kernel source code.
export PATH=$PROJ_ROOT/prebuilts/clang/ohos/linux-x86_64/llvm/bin:$PROJ_ROOT/prebuilts/gcc/linux-x86/arm/gcc-linaro-7.5.0-arm-linux-gnueabi/bin/:$PATH export PATH=$PROJ_ROOT/prebuilts/clang/ohos/linux-x86_64/llvm/bin:$PROJ_ROOT/prebuilts/gcc/linux-x86/arm/gcc-linaro-7.5.0-arm-linux-gnueabi/bin/:$PATH
export MAKE_OPTIONS="ARCH=arm CROSS_COMPILE=arm-linux-gnueabi- CC=clang HOSTCC=clang" export MAKE_OPTIONS="ARCH=arm CROSS_COMPILE=arm-linux-gnueabi- CC=clang HOSTCC=clang"
export PRODUCT_PATH=vendor/hisilicon/hispark_taurus_standard export PRODUCT_PATH=vendor/hisilicon/hispark_taurus_linux
``` ```
3. Comment out the flags that cannot be recognized by **clang**. 3. Comment out the flags that cannot be recognized by **clang**.
...@@ -96,7 +96,7 @@ The following uses Raspberry Pi 3b \(BCM2837\) as an example to describe how to ...@@ -96,7 +96,7 @@ The following uses Raspberry Pi 3b \(BCM2837\) as an example to describe how to
``` ```
### Porting Basic Kernel-Mode Code<a name="section95112081716"></a> ### Porting Basic Kernel-Mode Code
Currently, the basic kernel-mode code of OpenHarmony is related to the log service. The lightweight kernel log service code includes the following: Currently, the basic kernel-mode code of OpenHarmony is related to the log service. The lightweight kernel log service code includes the following:
...@@ -125,7 +125,7 @@ Enable the CONFIG macros **CONFIG\_HILOG** and **CONFIG\_HIEVENT** in the kernel ...@@ -125,7 +125,7 @@ Enable the CONFIG macros **CONFIG\_HILOG** and **CONFIG\_HIEVENT** in the kernel
For details about how to use the logs, see [Hilog\_lite](https://gitee.com/openharmony/hiviewdfx_hilog_lite/blob/master/README.md). For details about how to use the logs, see [Hilog\_lite](https://gitee.com/openharmony/hiviewdfx_hilog_lite/blob/master/README.md).
### Porting the HDF Feature<a name="section12971205681710"></a> ### Porting the HDF Feature
1. Install HDF patches. 1. Install HDF patches.
...@@ -186,14 +186,14 @@ For details about how to use the logs, see [Hilog\_lite](https://gitee.com/openh ...@@ -186,14 +186,14 @@ For details about how to use the logs, see [Hilog\_lite](https://gitee.com/openh
![](figures/menuconfig.png) ![](figures/menuconfig.png)
### Building the Image<a name="section1681965561911"></a> ### Building the Image
``` ```
# Run the following command: # Run the following command:
make ${MAKE_OPTIONS} -j33 zImage make ${MAKE_OPTIONS} -j33 zImage
``` ```
### \(Optional\) Building and Running HDF Test Cases<a name="section460792312204"></a> ### \(Optional\) Building and Running HDF Test Cases
**Overview** **Overview**
......
...@@ -58,7 +58,7 @@ Perform the steps below in the source code directory: ...@@ -58,7 +58,7 @@ Perform the steps below in the source code directory:
3. Add a component. 3. Add a component.
Modify the **build/lite/components/applications.json** file and add the configuration of **hello_world_app**. The following code snippet is a snippet of the **applications.json** file: The configuration between \#\#start\#\# and \#\#end\#\# is new. (\#\#start\#\# and \#\#end\#\# are only used to identify the location. After the configuration is complete, delete these lines.) Modify the **build/lite/components/communication.json** file and add the configuration of **hello_world_app**. The following code snippet is a snippet of the **communication.json** file: The configuration between \#\#start\#\# and \#\#end\#\# is new. (\#\#start\#\# and \#\#end\#\# are only used to identify the location. After the configuration is complete, delete these lines.)
``` ```
......
...@@ -62,7 +62,7 @@ The following exemplifies how to create a program by modifying the source code. ...@@ -62,7 +62,7 @@ The following exemplifies how to create a program by modifying the source code.
4. Add a component. 4. Add a component.
Modify the **build/lite/components/applications.json** file and add the configuration of **hello_world_app**. The following code snippet is a snippet of the **applications.json** file: The configuration between \#\#start\#\# and \#\#end\#\# is new. (\#\#start\#\# and \#\#end\#\# are only used to identify the location. After the configuration is complete, delete these lines.) Modify the **build/lite/components/communication.json** file and add the configuration of **hello_world_app**. The following code snippet is a snippet of the **communication.json** file: The configuration between \#\#start\#\# and \#\#end\#\# is new. (\#\#start\#\# and \#\#end\#\# are only used to identify the location. After the configuration is complete, delete these lines.)
``` ```
......
...@@ -58,7 +58,7 @@ Perform the steps below in the source code directory: ...@@ -58,7 +58,7 @@ Perform the steps below in the source code directory:
3. Add a component. 3. Add a component.
Modify the **build/lite/components/applications.json** file and add the configuration of **hello_world_app**. The following code snippet is a snippet of the **applications.json** file: The configuration between \#\#start\#\# and \#\#end\#\# is new. (\#\#start\#\# and \#\#end\#\# are only used to identify the location. After the configuration is complete, delete these lines.) Modify the **build/lite/components/communication.json** file and add the configuration of **hello_world_app**. The following code snippet is a snippet of the **communication.json** file: The configuration between \#\#start\#\# and \#\#end\#\# is new. (\#\#start\#\# and \#\#end\#\# are only used to identify the location. After the configuration is complete, delete these lines.)
``` ```
......
...@@ -62,7 +62,7 @@ The following exemplifies how to create a program by modifying the source code. ...@@ -62,7 +62,7 @@ The following exemplifies how to create a program by modifying the source code.
4. Add a component. 4. Add a component.
Modify the **build/lite/components/applications.json** file and add the configuration of **hello_world_app**. The following code snippet is a snippet of the **applications.json** file: The configuration between \#\#start\#\# and \#\#end\#\# is new. (\#\#start\#\# and \#\#end\#\# are only used to identify the location. After the configuration is complete, delete these lines.) Modify the **build/lite/components/communication.json** file and add the configuration of **hello_world_app**. The following code snippet is a snippet of the **communication.json** file: The configuration between \#\#start\#\# and \#\#end\#\# is new. (\#\#start\#\# and \#\#end\#\# are only used to identify the location. After the configuration is complete, delete these lines.)
``` ```
......
...@@ -351,11 +351,11 @@ OpenHarmony支持如下几种系统类型: ...@@ -351,11 +351,11 @@ OpenHarmony支持如下几种系统类型:
当前OpenHarmony社区支持17款开发板,下表介绍3款(此处选择三种系统类型首款进入OpenHarmony主干的开发板),更多开发板信息,请参考[社区支持的开发板清单](device-dev/dev-board-on-the-master.md) 当前OpenHarmony社区支持17款开发板,下表介绍3款(此处选择三种系统类型首款进入OpenHarmony主干的开发板),更多开发板信息,请参考[社区支持的开发板清单](device-dev/dev-board-on-the-master.md)
| 系统类型 | 开发板型号 | 芯片型号 | 主要能力 | 典型应用场景 | 开发板代码仓及社区每日构建版本获取地址 | | 系统类型 | 开发板型号 | 芯片型号 | 主要能力及适配案例 | 典型应用场景 | 开发板代码仓及社区每日构建版本获取地址 |
| -------- | -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- | -------- |
| 标准系统 | 润和DAYU200 | RK3568 | 润和HH-SCDAYU200基于Rockchip&nbsp;RK3568,集成双核心架构GPU以及高效能NPU;板载四核64位Cortex-A55&nbsp;处理器采用22nm先进工艺,主频高达2.0GHz;支持蓝牙、Wi-Fi、音频、视频和摄像头等功能,拥有丰富的扩展接口,支持多种视频输入输出接口;配置双千兆自适应RJ45以太网口,可满足NVR、工业网关等多网口产品需求。 | 影音娱乐、智慧出行、智能家居,如烟机、烤箱、跑步机等。 | 代码仓:<br/>[device_soc_rockchip](https://gitee.com/openharmony/device_soc_rockchip)<br/>[device_board_hihope](https://gitee.com/openharmony/device_board_hihope)<br/>[vendor_hihope](https://gitee.com/openharmony/vendor_hihope) <br/> 社区每日构建版本获取地址:<br/>http://ci.openharmony.cn/dailys/dailybuilds | | 标准系统 | 润和DAYU200 | RK3568 | 主要能力:<br/>润和HH-SCDAYU200基于Rockchip&nbsp;RK3568,集成双核心架构GPU以及高效能NPU;板载四核64位Cortex-A55&nbsp;处理器采用22nm先进工艺,主频高达2.0GHz;支持蓝牙、Wi-Fi、音频、视频和摄像头等功能,拥有丰富的扩展接口,支持多种视频输入输出接口;配置双千兆自适应RJ45以太网口,可满足NVR、工业网关等多网口产品需求。<br/>适配案例:<br/>[DAYU200适配案例](device-dev/porting/porting-dayu200-on_standard-demo.md) | 影音娱乐、智慧出行、智能家居,如烟机、烤箱、跑步机等。 | 代码仓:<br/>[device_soc_rockchip](https://gitee.com/openharmony/device_soc_rockchip)<br/>[device_board_hihope](https://gitee.com/openharmony/device_board_hihope)<br/>[vendor_hihope](https://gitee.com/openharmony/vendor_hihope) <br/> 社区每日构建版本获取地址:<br/>http://ci.openharmony.cn/dailys/dailybuilds |
| 小型系统 | Hispark_Taurus | Hi3516DV300 | Hi3516DV300是新一代Smart&nbsp;HD&nbsp;IP摄像机SOC,集成新一代ISP(Image&nbsp;Signal&nbsp;Processor)、H.265视频压缩编码器、高性能NNIE引擎,在低码率、高画质、智能处理和分析、低功耗等方面有较好的性能。 | 带屏智能硬件,比如带屏冰箱、车机等。 | 代码仓:<br/>[device_soc_hisilicon](https://gitee.com/openharmony/device_soc_hisilicon)<br/>[device_board_hisilicon](https://gitee.com/openharmony/device_board_hisilicon)<br/>[vendor_hisilicon](https://gitee.com/openharmony/vendor_hisilicon) <br/> 社区每日构建版本获取地址:<br/>http://ci.openharmony.cn/dailys/dailybuilds | | 小型系统 | Hispark_Taurus | Hi3516DV300 | 主要能力:<br/>Hi3516DV300是新一代Smart&nbsp;HD&nbsp;IP摄像机SOC,集成新一代ISP(Image&nbsp;Signal&nbsp;Processor)、H.265视频压缩编码器、高性能NNIE引擎,在低码率、高画质、智能处理和分析、低功耗等方面有较好的性能。 | 带屏智能硬件,比如带屏冰箱、车机等。 | 代码仓:<br/>[device_soc_hisilicon](https://gitee.com/openharmony/device_soc_hisilicon)<br/>[device_board_hisilicon](https://gitee.com/openharmony/device_board_hisilicon)<br/>[vendor_hisilicon](https://gitee.com/openharmony/vendor_hisilicon) <br/> 社区每日构建版本获取地址:<br/>http://ci.openharmony.cn/dailys/dailybuilds |
| 轻量系统 | 欧智通V200ZR | BES2600 | Multi-modal&nbsp;V200Z-R开发板是基于恒玄科技BES2600WM芯片的一款高性能、多功能、高性价比AIoT&nbsp;SoC开发板Multi-modal&nbsp;V200Z-R开发板,单模组集成四核ARM处理器(最高主频1GHz),集成双频WiFi&nbsp;+&nbsp;双模蓝牙,支持标准的802.11&nbsp;a/b/g/n/协议,支持BT/BLE&nbsp;5.2协议,内建多种容量的RAM(最大42MB)和Flash(最大32MB),支持MIPI&nbsp;DSI及CSI,适用于各种AIoT多模态VUI&nbsp;+&nbsp;GUI交互硬件场景。 | 智能硬件、带屏类模组产品,如音箱、手表等。 | 代码仓:<br/>[device_soc_bestechnic](https://gitee.com/openharmony/device_soc_bestechnic)<br/>[device_board_fnlink](https://gitee.com/openharmony/device_board_fnlink)<br/>[vendor_bestechnic](https://gitee.com/openharmony/vendor_bestechnic) <br/> 社区每日构建版本获取地址:<br/>http://ci.openharmony.cn/dailys/dailybuilds | | 轻量系统 | Multi-modal V200Z-R | BES2600 | 主要能力:<br/>Multi-modal&nbsp;V200Z-R开发板是基于恒玄科技BES2600WM芯片的一款高性能、多功能、高性价比AIoT&nbsp;SoC开发板Multi-modal&nbsp;V200Z-R开发板,单模组集成四核ARM处理器(最高主频1GHz),集成双频WiFi&nbsp;+&nbsp;双模蓝牙,支持标准的802.11&nbsp;a/b/g/n/协议,支持BT/BLE&nbsp;5.2协议,内建多种容量的RAM(最大42MB)和Flash(最大32MB),支持MIPI&nbsp;DSI及CSI,适用于各种AIoT多模态VUI&nbsp;+&nbsp;GUI交互硬件场景。<br/>适配案例:<br/>[Multi-modal V200Z-R适配案例](device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md) | 智能硬件、带屏类模组产品,如音箱、手表等。 | 代码仓:<br/>[device_soc_bestechnic](https://gitee.com/openharmony/device_soc_bestechnic)<br/>[device_board_fnlink](https://gitee.com/openharmony/device_board_fnlink)<br/>[vendor_bestechnic](https://gitee.com/openharmony/vendor_bestechnic) <br/> 社区每日构建版本获取地址:<br/>http://ci.openharmony.cn/dailys/dailybuilds |
## 快速入门<a name="section44681652104210"></a> ## 快速入门<a name="section44681652104210"></a>
......
# DataAbility开发指导 # DataAbility开发指导
## 场景介绍 ## 场景介绍
基于Data模板的Ability(以下简称“Data”),有助于应用管理其自身和其他应用存储数据的访问,并提供与其他应用共享数据的方法。Data既可用于同设备不同应用的数据共享,也支持跨设备不同应用的数据共享。 基于Data模板的Ability(以下简称“Data”),有助于应用管理其自身和其他应用存储数据的访问,并提供与其他应用共享数据的方法。Data既可用于同设备不同应用的数据共享,也支持跨设备不同应用的数据共享。
Data提供方可以自定义数据的增、删、改、查,以及文件打开等功能,并对外提供这些接口。 Data提供方可以自定义数据的增、删、改、查,以及文件打开等功能,并对外提供这些接口。
## URI介绍 ## URI介绍
Data的提供方和使用方都通过URI(Uniform Resource Identifier)来标识一个具体的数据,例如数据库中的某个表或磁盘上的某个文件。HarmonyOS的URI仍基于URI通用标准,格式如下: Data的提供方和使用方都通过URI(Uniform Resource Identifier)来标识一个具体的数据,例如数据库中的某个表或磁盘上的某个文件。OpenHarmony的URI仍基于URI通用标准,格式如下:
![fa-dataability-uri](figures/fa-dataability-uri.png) ![fa-dataability-uri](figures/fa-dataability-uri.png)
...@@ -21,10 +23,9 @@ URI示例: ...@@ -21,10 +23,9 @@ URI示例:
- 跨设备场景:dataability://*device_id*/*com.domainname.dataability.persondata*/*person*/*10* - 跨设备场景:dataability://*device_id*/*com.domainname.dataability.persondata*/*person*/*10*
- 本地设备:dataability:///*com.domainname.dataability.persondata*/*person*/*10* - 本地设备:dataability:///*com.domainname.dataability.persondata*/*person*/*10*
``` > 说明
说明 >
本地设备的“device_id”字段为空,因此在“dataability:”后面有三个“/”。 > 本地设备的“device_id”字段为空,因此在“dataability:”后面有三个“/”。
```
## 接口说明 ## 接口说明
......
...@@ -17,3 +17,6 @@ ExtensionContext模块提供扩展的上下文的能力,包括允许访问特 ...@@ -17,3 +17,6 @@ ExtensionContext模块提供扩展的上下文的能力,包括允许访问特
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| currentHapModuleInfo | HapModuleInfo | 是 | 否 | 当前Hap包的信息。 | | currentHapModuleInfo | HapModuleInfo | 是 | 否 | 当前Hap包的信息。 |
| config | Configuration | 是 | 否 | 模块的配置信息。 | | config | Configuration | 是 | 否 | 模块的配置信息。 |
| extensionAbilityInfo | [ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md) | 是 | 否 | 服务扩展信息。 |
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册