提交 f3ef4504 编写于 作者: IT_newip's avatar IT_newip

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

...@@ -151,9 +151,9 @@ zh-cn/application-dev/work-scheduler/ @HelloCrease ...@@ -151,9 +151,9 @@ zh-cn/application-dev/work-scheduler/ @HelloCrease
zh-cn/application-dev/internationalization/ @HelloCrease zh-cn/application-dev/internationalization/ @HelloCrease
zh-cn/application-dev/device/usb-overview.md @ge-yafang zh-cn/application-dev/device/usb-overview.md @ge-yafang
zh-cn/application-dev/device/usb-guidelines.md @ge-yafang zh-cn/application-dev/device/usb-guidelines.md @ge-yafang
zh-cn/application-dev/device/device-location-overview.md @sun-yue14 zh-cn/application-dev/device/device-location-overview.md @zengyawen
zh-cn/application-dev/device/device-location-info.md @sun-yue14 zh-cn/application-dev/device/device-location-info.md @zengyawen
zh-cn/application-dev/device/device-location-geocoding.md @sun-yue14 zh-cn/application-dev/device/device-location-geocoding.md @zengyawen
zh-cn/application-dev/device/sensor-overview.md @HelloCrease zh-cn/application-dev/device/sensor-overview.md @HelloCrease
zh-cn/application-dev/device/sensor-guidelines.md @HelloCrease zh-cn/application-dev/device/sensor-guidelines.md @HelloCrease
zh-cn/application-dev/device/vibrator-overview.md @HelloCrease zh-cn/application-dev/device/vibrator-overview.md @HelloCrease
...@@ -277,14 +277,14 @@ zh-cn/application-dev/reference/apis/js-apis-http.md @zengyawen ...@@ -277,14 +277,14 @@ zh-cn/application-dev/reference/apis/js-apis-http.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-request.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-request.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-socket.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-socket.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-webSocket.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-webSocket.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @bmeangel zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @bmeangel zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-nfcTech.md @bmeangel zh-cn/application-dev/reference/apis/js-apis-nfcTech.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-tagSession.md @bmeangel zh-cn/application-dev/reference/apis/js-apis-tagSession.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-connectedTag.md @bmeangel zh-cn/application-dev/reference/apis/js-apis-connectedTag.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-rpc.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-rpc.md @qinxiaowang
zh-cn/application-dev/reference/apis/js-apis-wifi.md @bmeangel zh-cn/application-dev/reference/apis/js-apis-wifi.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-wifiext.md @bmeangel zh-cn/application-dev/reference/apis/js-apis-wifiext.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-accessibility.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-accessibility.md @qinxiaowang
zh-cn/application-dev/reference/apis/js-apis-faultLogger.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-faultLogger.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-hiappevent.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hiappevent.md @zengyawen
...@@ -293,18 +293,18 @@ zh-cn/application-dev/reference/apis/js-apis-hidebug.md @zengyawen ...@@ -293,18 +293,18 @@ zh-cn/application-dev/reference/apis/js-apis-hidebug.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-hilog.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hilog.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-hitracechain.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hitracechain.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-hitracemeter.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hitracemeter.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @bmeangel zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @bmeangel zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @bmeangel zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-system-time.md @bmeangel zh-cn/application-dev/reference/apis/js-apis-system-time.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @bmeangel zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-timer.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-timer.md @HelloCrease
zh-cn/application-dev/reference/apis/js-apis-battery-info.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-battery-info.md @qinxiaowang
zh-cn/application-dev/reference/apis/js-apis-brightness.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-brightness.md @qinxiaowang
zh-cn/application-dev/reference/apis/js-apis-device-info.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-device-info.md @qinxiaowang
zh-cn/application-dev/reference/apis/js-apis-device-manager.md zh-cn/application-dev/reference/apis/js-apis-device-manager.md
zh-cn/application-dev/reference/apis/js-apis-geolocation.md @sun-yue14 zh-cn/application-dev/reference/apis/js-apis-geolocation.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @HelloCrease
zh-cn/application-dev/reference/apis/js-apis-inputdevice.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputdevice.md @HelloCrease
zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @HelloCrease
......
...@@ -50,18 +50,41 @@ The following uses a single KV store as an example to describe the development p ...@@ -50,18 +50,41 @@ The following uses a single KV store as an example to describe the development p
This permission must also be granted by the user when the application is started for the first time. The sample code is as follows: This permission must also be granted by the user when the application is started for the first time. The sample code is as follows:
```js ```js
// FA model
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
function grantPermission() { function grantPermission() {
console.info('grantPermission'); console.info('grantPermission');
let context = featureAbility.getContext(); let context = featureAbility.getContext();
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666).then((data) => {
console.info(`result.requestCode=${result.requestCode}`) console.info('success: ${data}');
}).catch((error) => {
}) console.info('failed: ${error}');
console.info('end grantPermission'); })
} }
grantPermission();
// Stage model
import Ability from '@ohos.application.Ability';
let context = null;
function grantPermission() {
class MainAbility extends Ability {
onWindowStageCreate(windowStage) {
let context = this.context;
}
}
let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC'];
context.requestPermissionsFromUser(permissions).then((data) => {
console.log('success: ${data}');
}).catch((error) => {
console.log('failed: ${error}');
});
}
grantPermission(); grantPermission();
``` ```
...@@ -73,25 +96,39 @@ The following uses a single KV store as an example to describe the development p ...@@ -73,25 +96,39 @@ The following uses a single KV store as an example to describe the development p
The sample code is as follows: The sample code is as follows:
```js ```js
// Obtain the context of the FA model.
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
// Obtain the context of the stage model.
import AbilityStage from '@ohos.application.Ability';
let context = null;
class MainAbility extends AbilityStage{
onWindowStageCreate(windowStage){
context = this.context;
}
}
let kvManager; let kvManager;
try { try {
const kvManagerConfig = { const kvManagerConfig = {
bundleName: 'com.example.datamanagertest', bundleName: 'com.example.datamanagertest',
userInfo: { userInfo: {
context:context,
userId: '0', userId: '0',
userType: distributedData.UserType.SAME_USER_ID userType: distributedData.UserType.SAME_USER_ID
} }
} }
distributedData.createKVManager(kvManagerConfig, function (err, manager) { distributedData.createKVManager(kvManagerConfig, function (err, manager) {
if (err) { if (err) {
console.log("createKVManager err: " + JSON.stringify(err)); console.log('Failed to create KVManager: ${error}');
return; return;
} }
console.log("createKVManager success"); console.log('Created KVManager successfully');
kvManager = manager; kvManager = manager;
}); });
} catch (e) { } catch (e) {
console.log("An unexpected error occurred. Error: " + e); console.log('An unexpected error occurred. Error: ${e}');
} }
``` ```
...@@ -115,14 +152,14 @@ The following uses a single KV store as an example to describe the development p ...@@ -115,14 +152,14 @@ The following uses a single KV store as an example to describe the development p
}; };
kvManager.getKVStore('storeId', options, function (err, store) { kvManager.getKVStore('storeId', options, function (err, store) {
if (err) { if (err) {
console.log("getKVStore err: " + JSON.stringify(err)); console.log('Failed to get KVStore: ${err}');
return; return;
} }
console.log("getKVStore success"); console.log('Got KVStore successfully');
kvStore = store; kvStore = store;
}); });
} catch (e) { } catch (e) {
console.log("An unexpected error occurred. Error: " + e); console.log('An unexpected error occurred. Error: ${e}');
} }
``` ```
...@@ -136,7 +173,7 @@ The following uses a single KV store as an example to describe the development p ...@@ -136,7 +173,7 @@ The following uses a single KV store as an example to describe the development p
```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: ${data}");
}); });
``` ```
...@@ -153,13 +190,13 @@ The following uses a single KV store as an example to describe the development p ...@@ -153,13 +190,13 @@ The following uses a single KV store as an example to describe the development p
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.log("put err: " + JSON.stringify(err)); console.log('Failed to put data: ${error}');
return; return;
} }
console.log("put success"); console.log('Put data successfully');
}); });
} catch (e) { } catch (e) {
console.log("An unexpected error occurred. Error: " + e); console.log('An unexpected error occurred. Error: ${e}');
} }
``` ```
...@@ -176,16 +213,16 @@ The following uses a single KV store as an example to describe the development p ...@@ -176,16 +213,16 @@ The following uses a single KV store as an example to describe the development p
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.log("put err: " + JSON.stringify(err)); console.log('Failed to put data: ${error}');
return; return;
} }
console.log("put success"); console.log('Put data successfully');
kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) {
console.log("get success data: " + data); console.log('Got data successfully: ${data}');
}); });
}); });
} catch (e) { } catch (e) {
console.log("An unexpected error occurred. Error: " + e); console.log('An unexpected error occurred. Error: ${e}');
} }
``` ```
...@@ -204,7 +241,7 @@ The following uses a single KV store as an example to describe the development p ...@@ -204,7 +241,7 @@ The following uses a single KV store as an example to describe the development p
let devManager; let devManager;
// Create deviceManager. // Create deviceManager.
deviceManager.createDeviceManager("bundleName", (err, value) => { deviceManager.createDeviceManager('bundleName', (err, value) => {
if (!err) { if (!err) {
devManager = value; devManager = value;
// deviceIds is obtained by deviceManager by calling getTrustedDeviceListSync(). // deviceIds is obtained by deviceManager by calling getTrustedDeviceListSync().
...@@ -219,7 +256,7 @@ The following uses a single KV store as an example to describe the development p ...@@ -219,7 +256,7 @@ The following uses a single KV store as an example to describe the development p
// 1000 indicates that the maximum delay is 1000 ms. // 1000 indicates that the maximum delay is 1000 ms.
kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000); kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000);
} catch (e) { } catch (e) {
console.log("An unexpected error occurred. Error: " + e); console.log('An unexpected error occurred. Error: ${e}');
} }
} }
}); });
......
# Distributed Data Service Overview # Distributed Data Service Overview
The distributed data service (DDS) implements distributed database collaboration across devices for applications. The distributed data service (DDS) implements distributed database collaboration across devices for applications.
Applications save data to distributed databases by calling the DDS APIs. The DDS isolates data of different applications based on a triplet of account, application, and database to ensure secure data access. The DDS synchronizes application data between trusted devices to provide users with consistent data access experience on different devices. Applications save data to distributed databases by calling the DDS APIs. The DDS isolates data of different applications based on a triplet of account, application, and database to ensure secure data access. The DDS synchronizes application data between trusted devices to provide users with consistent data access experience on different devices.
You do not need to care about the implementation of the database locking mechanism. You do not need to care about the implementation of the database locking mechanism.
## Basic Concepts ## Basic Concepts
- **KV data model** ### KV Data Model
The key-value \(KV\) data model allows data to be organized, indexed, and stored in key-value pairs. The key-value (KV) data model allows data to be organized, indexed, and stored in KV pairs.
The KV data model is suitable for storing service data that is not related. It provides better read and write performance than the SQL database. The KV data model is widely used in distributed scenarios because it handles database version compatibility issues and data synchronization conflicts easily. The distributed database is based on the KV data model and provides KV-based access interfaces. The KV data model is suitable for storing service data that is not related. It provides better read and write performance than the SQL database. The KV data model is widely used in distributed scenarios because it handles database version compatibility issues and data synchronization conflicts easily. The distributed database is based on the KV data model and provides KV-based access interfaces.
- **Distributed database transactions** ### Distributed Database Transaction
Distributed database transactions include local transactions \(same as the transactions of traditional databases\) and synchronization transactions. Synchronization transactions allow data to be synchronized between devices by local transaction. Synchronization of a local transaction modification either succeeds or fails on all the devices. Distributed database transactions include local transactions (same as the transactions of traditional databases) and synchronization transactions. Synchronization transactions allow data to be synchronized between devices by local transaction. Synchronization of a local transaction modification either succeeds or fails on all the devices.
- **Distributed database consistency** ### Distributed Database Consistency
In a distributed scenario, cross-device collaboration demands consistent data between the devices in the same network. The data consistency can be classified into the following types: In a distributed scenario, cross-device collaboration demands consistent data between the devices in the same network. The data consistency can be classified into the following types:
- **Strong consistency**: When data is inserted, deleted, or modified on a device, other devices in the same network will obtain the latest data immediately. - **Strong consistency**: When data is inserted, deleted, or modified on a device, other devices in the same network will obtain the latest data immediately.
- **Weak consistency**: When data is added, deleted, or modified on a device, other devices in the same network may or may not obtain the latest data. The data on these devices may be inconsistent after a certain period of time. - **Weak consistency**: When data is added, deleted, or modified on a device, other devices in the same network may or may not obtain the latest data. The data on these devices may be inconsistent after a certain period of time.
- **Eventual consistency**: When data is added, deleted, or modified on a device, other devices in the same network may not obtain the latest data immediately. However, data on these devices will become consistent after a certain period of time. - **Eventual consistency**: When data is added, deleted, or modified on a device, other devices in the same network may not obtain the latest data immediately. However, data on these devices will become consistent after a certain period of time.
Strong consistency has high requirements on distributed data management and may be used in distributed server deployment. The DDS supports only the eventual consistency because mobile devices are not always online and the network has no center. Strong consistency has high requirements on distributed data management and may be used in distributed server deployment. The DDS supports only the eventual consistency because mobile devices are not always online and the network has no center.
- **Distributed database synchronization** ### Distributed Database Synchronization
After discovering and authenticating a device, the underlying communication component notifies the upper-layer application \(including the DDS\) that the device goes online. The DDS then establishes an encrypted transmission channel to synchronize data between the two devices. After discovering and authenticating a device, the underlying communication component notifies the upper-layer application (including the DDS) that the device goes online. The DDS then establishes an encrypted transmission channel to synchronize data between the two devices.
The DDS provides the following synchronization modes: The DDS provides the following synchronization modes:
- **Manual synchronization**: Applications call **sync** to trigger a synchronization. The list of devices to be synchronized and the synchronization mode must be specified. The synchronization mode can be **PULL\_ONLY** \(pulling remote data to the local end\), **PUSH\_ONLY** \(pushing local data to the remote end\), or **PUSH\_PULL** \(pushing local data to the remote end and pulling remote data to the local end\). The internal interface supports condition-based synchronization. The data that meets the conditions can be synchronized to the remote end. - **Manual synchronization**: Applications call **sync()** to trigger a synchronization. The list of devices to be synchronized and the synchronization mode must be specified. The synchronization mode can be **PULL_ONLY** (pulling remote data to the local end), **PUSH_ONLY** (pushing local data to the remote end), or **PUSH_PULL** (pushing local data to the remote end and pulling remote data to the local end). The internal interface supports condition-based synchronization. The data that meets the conditions can be synchronized to the remote end.
- **Automatic synchronization**: includes full synchronization and condition-based subscription synchronization. In full synchronization, the distributed database automatically pushes local data to the remote end and pulls remote data to the local end when a device goes online or application data is updated. Applications do not need to call **sync**. The internal interface supports condition-based subscription synchronization. The data that meets the subscription conditions on the remote end is automatically synchronized to the local end. - **Automatic synchronization**: includes full synchronization and condition-based subscription synchronization. In full synchronization, the distributed database automatically pushes local data to the remote end and pulls remote data to the local end when a device goes online or application data is updated. Applications do not need to call **sync()**. The internal interface supports condition-based subscription synchronization. The data that meets the subscription conditions on the remote end is automatically synchronized to the local end.
- **Single KV store** ### Single KV Store
Data is saved locally in the unit of a single KV entry. Only one entry is saved for each key. Data can be modified only locally and synchronized to remote devices in sequence based on the update time. Data is saved locally in the unit of a single KV entry. Only one entry is saved for each key. Data can be modified only locally and synchronized to remote devices in sequence based on the update time.
- **Device KV store** ### Device KV Store
The device KV store is based on the single KV store. The local device ID is added to the key when KV data is stored in the device KV store. Data can be isolated, managed, and queried by device. However, the data synchronized from remote devices cannot be modified locally. The device KV store is based on the single KV store. The local device ID is added to the key when KV data is stored in the device KV store. Data can be isolated, managed, and queried by device. However, the data synchronized from remote devices cannot be modified locally.
- **Conflict resolution** ### Conflict Resolution
A data conflict occurs when multiple devices modify the same data and commit the modification to the database. The last write wins \(LWW\) is the default conflict resolution policy used for data conflicts. Based on the commit timestamps, the data with a later timestamp is used. Currently, customized conflict resolution policies are not supported. A data conflict occurs when multiple devices modify the same data and commit the modification to the database. The last write wins (LWW) is the default conflict resolution policy used for data conflicts. Based on the commit timestamps, the data with a later timestamp is used. Currently, customized conflict resolution policies are not supported.
- **Schema-based database management and data query based on predicates** ### Schema-based Database Management and Predicate-based Data Query
A schema is specified when you create or open a single KV store. Based on the schema, the database detects the value format of key-value pairs and checks the value structure. Based on the fields in the values, the database implements index creation and predicate-based query. A schema is specified when you create or open a single KV store. Based on the schema, the database detects the value format of KV pairs and checks the value structure. Based on the fields in the values, the database implements index creation and predicate-based query.
- **Distributed database backup** ### Distributed Database Backup
The DDS provides the database backup capability. You can set **backup** to **true** to enable daily backup. If a distributed database is damaged, the DDS deletes the database and restores the most recent data from the backup database. If no backup database is available, the DDS creates one. The DDS can also back up encrypted databases. The DDS provides the database backup capability. You can set **backup** to **true** to enable daily backup. If a distributed database is damaged, the DDS deletes the database and restores the most recent data from the backup database. If no backup database is available, the DDS creates one. The DDS can also back up encrypted databases.
## Working Principles ## Working Principles
The DDS supports distributed management of application database data in the OpenHarmony system. Data can be synchronized between multiple devices with the same account, delivering a consistent user experience across devices. The DDS consists of the following: The DDS supports distributed management of application database data in the OpenHarmony system. Data can be synchronized between multiple devices with the same account, delivering a consistent user experience across devices.
- **APIs** The DDS consists of the following:
The DDS provides APIs to create databases, access data, and subscribe to data. The APIs support the KV data model and common data types. They are highly compatible and easy to use, and can be released. - **APIs**<br>The DDS provides APIs to create databases, access data, and subscribe to data. The APIs support the KV data model and common data types. They are highly compatible and easy to use, and can be released.
- **Service component** - **Service component**<br>The service component implements management of metadata, permissions, encryption, backup and restore, and multiple users, and completes initialization of the storage component, synchronization component, and communication adaptation layer of the distributed database.
The service component implements management of metadata, permissions, encryption, backup and restore, and multiple users, and completes initialization of the storage component, synchronization component, and communication adaptation layer of the distributed database. - **Storage component**<br>The storage component implements data access, data reduction, transactions, snapshots, database encryption, data combination, and conflict resolution.
- **Storage component** - **Synchronization component**<br>The synchronization component interacts with the storage component and the communication adaptation layer to maintain data consistency between online devices. It synchronizes data generated on the local device to other devices and merges data from other devices into the local device.
The storage component implements data access, data reduction, transactions, snapshots, database encryption, data combination, and conflict resolution. - **Communication adaptation layer**<br>The communication adaptation layer calls APIs of the underlying public communication layer to create and connect to communication channels, receive device online and offline messages, update metadata of the connected and disconnected devices, send device online and offline messages to the synchronization component. The synchronization component updates the list of connected devices, and calls the APIs of the communication adaption layer to encapsulate data and send the data to the connected devices.
- **Synchronization component** Applications call the DDS APIs to create, access, and subscribe to distributed databases. The APIs store data to the storage component based on the capabilities provided by the service component. The storage component interacts with the synchronization component to synchronize data. The synchronization component uses the communication adaptation layer to synchronize data to remote devices, which update the data in the storage component and provide the data for applications through service APIs.
The synchronization component interacts with the storage component and the communication adaptation layer to maintain data consistency between online devices. It synchronizes data generated on the local device to other devices and merges data from other devices into the local device.
- **Communication adaptation layer** **Figure 1** How DDS works
The communication adaptation layer calls APIs of the underlying public communication layer to create and connect to communication channels, receive device online and offline messages, update metadata of the connected and disconnected devices, send device online and offline messages to the synchronization component. The synchronization component updates the list of connected devices, and calls the APIs of the communication adaption layer to encapsulate data and send the data to the connected devices.
![](figures/en-us_image_0000001183386164.png)
Applications call the DDS APIs to create, access, and subscribe to distributed databases. The APIs store data to the storage component based on the capabilities provided by the service component. The storage component interacts with the synchronization component to synchronize data. The synchronization component uses the communication adaptation layer to synchronize data to remote devices, which update the data in the storage component and provide the data for applications through service APIs.
**Figure 1** How DDS works<a name="fig9151258063"></a> ## Constraints
- The DDS supports the KV data model only. It does not support foreign keys or triggers of the relational database.
![](figures/en-us_image_0000001183386164.png) - The KV data model specifications supported by the DDS are as follows:
## Constraints - For each record in a device KV store, the key must be less than or equal to 896 bytes and the value be less than 4 MB.
- For each record in a single KV store, the key must be less than or equal to 1 KB and the value be less than 4 MB.
- An application can open a maximum of 16 KV stores simultaneously.
- The data that needs to be synchronized between devices should be stored in distributed databases rather than local databases.
- The DDS supports the KV data model only. It does not support foreign keys or triggers of the relational database. - The DDS does not support customized conflict resolution policies.
- The KV data model specifications supported by the DDS are as follows:
- For each record in a device KV store, the key must be less than or equal to 896 bytes and the value be less than 4 MB.
- For each record in a single KV store, the key must be less than or equal to 1 KB and the value be less than 4 MB.
- An application can open a maximum of 16 KV stores simultaneously.
- The data that needs to be synchronized between devices should be stored in distributed databases rather than local databases. - The maximum number of access requests to the KvStore API is 1000 per second and 10000 per minute. The maximum number of access requests to the KvManager API is 50 per second and 500 per minute.
- The DDS does not support customized conflict resolution policies.
- The maximum number of access requests to the KvStore API is 1000 per second and 10000 per minute. The maximum number of access requests to the KvManager API is 50 per second and 500 per minute.
- Blocking operations, such as modifying UI components, are not allowed in the distributed database event callback.
- Blocking operations, such as modifying UI components, are not allowed in the distributed database event callback.
...@@ -196,17 +196,41 @@ Table 15 Transaction APIs ...@@ -196,17 +196,41 @@ Table 15 Transaction APIs
(3) Create an RDB store. (3) Create an RDB store.
The sample code is as follows: FA model:
```js ```js
import data_rdb from '@ohos.data.rdb' import data_rdb from '@ohos.data.rdb'
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
let context = featureAbility.getContext()
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; const STORE_CONFIG = { name: "RdbTest.db" }
const STORE_CONFIG = { name: "rdbstore.db" } data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) {
data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) {
rdbStore.executeSql(CREATE_TABLE_TEST) rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.') console.info('create table done.')
}) })
```
Stage model:
```ts
import data_rdb from '@ohos.data.rdb'
// Obtain the context.
import Ability from '@ohos.application.Ability'
let context = null
class MainAbility extends Ability {
onWindowStageCreate(windowStage) {
context = this.context
}
}
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
const STORE_CONFIG = { name: "rdbstore.db" }
data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) {
rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.')
})
``` ```
2. Insert data. 2. Insert data.
......
...@@ -2104,6 +2104,7 @@ Called to return the result of an authentication request. ...@@ -2104,6 +2104,7 @@ Called to return the result of an authentication request.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | -------------------- | ---- | ------ | | ------ | -------------------- | ---- | ------ |
| code | number | Yes | Authentication result code.| | code | number | Yes | Authentication result code.|
...@@ -2134,6 +2135,7 @@ Called to redirect a request. ...@@ -2134,6 +2135,7 @@ Called to redirect a request.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ---- | ---- | ---------- | | ------- | ---- | ---- | ---------- |
| request | Want | Yes | Request to be redirected.| | request | Want | Yes | Request to be redirected.|
...@@ -2191,6 +2193,7 @@ Implicitly adds an app account based on the specified authentication type and op ...@@ -2191,6 +2193,7 @@ Implicitly adds an app account based on the specified authentication type and op
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- | | ---------------- | --------------------- | ---- | --------------- |
| authType | string | Yes | Authentication type. | | authType | string | Yes | Authentication type. |
...@@ -2207,6 +2210,7 @@ Authenticates an app account to obtain the OAuth token. This API uses an asynchr ...@@ -2207,6 +2210,7 @@ Authenticates an app account to obtain the OAuth token. This API uses an asynchr
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- | | ---------------- | --------------------- | ---- | --------------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
...@@ -2224,6 +2228,7 @@ Verifies the credential of an app account. This API uses an asynchronous callbac ...@@ -2224,6 +2228,7 @@ Verifies the credential of an app account. This API uses an asynchronous callbac
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- | | ---------------- | --------------------- | ---- | --------------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
...@@ -2239,6 +2244,7 @@ Sets authenticator properties. This API uses an asynchronous callback to return ...@@ -2239,6 +2244,7 @@ Sets authenticator properties. This API uses an asynchronous callback to return
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- | | ---------------- | --------------------- | ---- | --------------- |
| options | [SetPropertiesOptions](#setpropertiesoptions9) | Yes | Authenticator properties to set. | | options | [SetPropertiesOptions](#setpropertiesoptions9) | Yes | Authenticator properties to set. |
...@@ -2253,6 +2259,7 @@ Checks the account labels. This API uses an asynchronous callback to return the ...@@ -2253,6 +2259,7 @@ Checks the account labels. This API uses an asynchronous callback to return the
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- | | ---------------- | --------------------- | ---- | --------------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
...@@ -2268,6 +2275,7 @@ Checks whether an app account can be deleted. This API uses an asynchronous call ...@@ -2268,6 +2275,7 @@ Checks whether an app account can be deleted. This API uses an asynchronous call
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- | | ---------------- | --------------------- | ---- | --------------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
......
...@@ -21,12 +21,13 @@ Obtains a **DistributedAccountAbility** instance. ...@@ -21,12 +21,13 @@ Obtains a **DistributedAccountAbility** instance.
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
- Return value **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [DistributedAccountAbility](#distributedaccountability) | **DistributedAccountAbility** instance obtained. This instance provides methods for querying and updating the login state of a distributed account.| | [DistributedAccountAbility](#distributedaccountability) | **DistributedAccountAbility** instance obtained. This instance provides methods for querying and updating the login state of a distributed account.|
- Example **Example**
```js ```js
const accountAbility = account_distributedAccount.getDistributedAccountAbility(); const accountAbility = account_distributedAccount.getDistributedAccountAbility();
``` ```
...@@ -45,12 +46,13 @@ Obtains distributed account information. This API uses an asynchronous callback ...@@ -45,12 +46,13 @@ Obtains distributed account information. This API uses an asynchronous callback
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC
- Parameters **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[DistributedInfo](#distributedinfo)&gt; | Yes| Callback invoked to return the distributed account information obtained.| | callback | AsyncCallback&lt;[DistributedInfo](#distributedinfo)&gt; | Yes| Callback invoked to return the distributed account information obtained.|
- Example **Example**
```js ```js
const accountAbility = account_distributedAccount.getDistributedAccountAbility(); const accountAbility = account_distributedAccount.getDistributedAccountAbility();
accountAbility.queryOsAccountDistributedInfo((err, data) => { accountAbility.queryOsAccountDistributedInfo((err, data) => {
...@@ -70,12 +72,13 @@ Obtains distributed account information. This API uses a promise to return the r ...@@ -70,12 +72,13 @@ Obtains distributed account information. This API uses a promise to return the r
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC
- Return value **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[DistributedInfo](#distributedinfo)&gt; | Promise used to return the distributed account information obtained.| | Promise&lt;[DistributedInfo](#distributedinfo)&gt; | Promise used to return the distributed account information obtained.|
- Example **Example**
```js ```js
const accountAbility = account_distributedAccount.getDistributedAccountAbility(); const accountAbility = account_distributedAccount.getDistributedAccountAbility();
accountAbility.queryOsAccountDistributedInfo().then((data) => { accountAbility.queryOsAccountDistributedInfo().then((data) => {
...@@ -96,13 +99,14 @@ Updates distributed account information. This API uses an asynchronous callback ...@@ -96,13 +99,14 @@ Updates distributed account information. This API uses an asynchronous callback
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
- Parameters **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information.| | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked when the distributed account information is updated.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked when the distributed account information is updated.|
- Example **Example**
```js ```js
const accountAbility = account_distributedAccount.getDistributedAccountAbility(); const accountAbility = account_distributedAccount.getDistributedAccountAbility();
let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'};
...@@ -121,17 +125,19 @@ Updates distributed account information. This API uses a promise to return the r ...@@ -121,17 +125,19 @@ Updates distributed account information. This API uses a promise to return the r
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
- Parameters **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information.| | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information.|
- Return value **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise used to return the result.|
- Example **Example**
```js ```js
const accountAbility = account_distributedAccount.getDistributedAccountAbility(); const accountAbility = account_distributedAccount.getDistributedAccountAbility();
let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'};
......
...@@ -22,6 +22,7 @@ Obtains information about the root album or directory in asynchronous mode. This ...@@ -22,6 +22,7 @@ Obtains information about the root album or directory in asynchronous mode. This
**System capability**: SystemCapability.FileManagement.UserFileService **System capability**: SystemCapability.FileManagement.UserFileService
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| --- | --- | --- | -- | | --- | --- | --- | -- |
| options | Object | No| The options are as follows:<br>- &nbsp;**dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| | options | Object | No| The options are as follows:<br>- &nbsp;**dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.|
...@@ -83,6 +84,7 @@ Obtains information about the second-level album or files in asynchronous mode. ...@@ -83,6 +84,7 @@ Obtains information about the second-level album or files in asynchronous mode.
**System capability**: SystemCapability.FileManagement.UserFileService **System capability**: SystemCapability.FileManagement.UserFileService
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| --- | --- | --- | -- | | --- | --- | --- | -- |
| path | string | Yes| URI of the directory to query.| | path | string | Yes| URI of the directory to query.|
...@@ -169,6 +171,7 @@ Creates a file in the specified path in asynchronous mode. This API uses a promi ...@@ -169,6 +171,7 @@ Creates a file in the specified path in asynchronous mode. This API uses a promi
**System capability**: SystemCapability.FileManagement.UserFileService **System capability**: SystemCapability.FileManagement.UserFileService
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| --- | --- | --- | -- | | --- | --- | --- | -- |
| filename | string | Yes| Name of the file to create.| | filename | string | Yes| Name of the file to create.|
......
...@@ -18,26 +18,26 @@ Obtains the number of free bytes of the specified file system in asynchronous mo ...@@ -18,26 +18,26 @@ Obtains the number of free bytes of the specified file system in asynchronous mo
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
- **Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------------- | | ------ | ------ | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.| | path | string | Yes | File path of the file system.|
- Return value **Return value**
| Type | Description | | Type | Description |
| --------------------- | -------------- | | --------------------- | -------------- |
| Promise&lt;number&gt; | Promise used to return the number of free bytes obtained.| | Promise&lt;number&gt; | Promise used to return the number of free bytes obtained.|
- Example **Example**
```js ```js
let path = "/dev"; let path = "/dev";
statfs.getFreeBytes(path).then(function (number){ statfs.getFreeBytes(path).then(function (number) {
console.info("getFreeBytes promise successfully:"+ number); console.info("getFreeBytes promise successfully:" + number);
}).catch(function(err){ }).catch(function (err) {
console.info("getFreeBytes failed with error:"+ err); console.info("getFreeBytes failed with error:" + err);
}); });
``` ```
...@@ -49,21 +49,21 @@ Obtains the number of free bytes of the specified file system in asynchronous mo ...@@ -49,21 +49,21 @@ Obtains the number of free bytes of the specified file system in asynchronous mo
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
- **Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- | | -------- | --------------------------- | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.| | path | string | Yes | File path of the file system.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of free bytes obtained.| | callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of free bytes obtained.|
- Example **Example**
```js ```js
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getFilesDir().then(function (path) { context.getFilesDir().then(function (path) {
statfs.getFreeBytes(path, function(err, number){ statfs.getFreeBytes(path, function (err, number) {
console.info("Got free bytes successfully:"+ number); console.info("getFreeBytes callback successfully:" + number);
}); });
}); });
``` ```
...@@ -76,26 +76,26 @@ Obtains the total number of bytes of the specified file system in asynchronous m ...@@ -76,26 +76,26 @@ Obtains the total number of bytes of the specified file system in asynchronous m
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
- **Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ---- | ------ | ---- | ---------------------------- | | ---- | ------ | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.| | path | string | Yes | File path of the file system.|
- Return value **Return value**
| Type | Description | | Type | Description |
| --------------------- | ------------ | | --------------------- | ------------ |
| Promise&lt;number&gt; | Promise used to return the total number of bytes obtained.| | Promise&lt;number&gt; | Promise used to return the total number of bytes obtained.|
- Example **Example**
```js ```js
let path = "/dev"; let path = "/dev";
statfs.getTotalBytes(path).then(function (number){ statfs.getTotalBytes(path).then(function (number) {
console.info("getTotalBytes promise successfully:"+ number); console.info("getTotalBytes promise successfully:" + number);
}).catch(function(err){ }).catch(function (err) {
console.info("getTotalBytes failed with error:"+ err); console.info("getTotalBytes failed with error:" + err);
}); });
``` ```
...@@ -107,21 +107,21 @@ Obtains the total number of bytes of the specified file system in asynchronous m ...@@ -107,21 +107,21 @@ Obtains the total number of bytes of the specified file system in asynchronous m
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
- **Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- | | -------- | --------------------------- | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.| | path | string | Yes | File path of the file system.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the total number of bytes obtained. | | callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the total number of bytes obtained. |
- Example **Example**
```js ```js
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getFilesDir().then(function (path) { context.getFilesDir().then(function (path) {
statfs.getTotalBytes(path, function(err, number){ statfs.getTotalBytes(path, function(err, number) {
console.info("Got total bytes successfully:"+ number); console.info("getTotalBytes callback successfully:" + number);
}); });
}); });
``` ```
...@@ -25,7 +25,7 @@ Encrypts or decrypts data using RSA. ...@@ -25,7 +25,7 @@ Encrypts or decrypts data using RSA.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| action | string | Yes| Action to perform. The options are as follows:<br>-&nbsp;encrypt<br>-&nbsp;decrypt| | action | string | Yes| Action to perform. The options are as follows:<br>- encrypt<br>- decrypt |
| text | string | Yes| Text to be encrypted or decrypted.<br> The text to be encrypted must be common text that meets the following requirement:<br> Maximum text length = Key length/8 - 66<br>For example, if the key is of 1024 bytes, the text to be encrypted cannot exceed 62 bytes (1024/8 -66 = 62).<br> The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| | text | string | Yes| Text to be encrypted or decrypted.<br> The text to be encrypted must be common text that meets the following requirement:<br> Maximum text length = Key length/8 - 66<br>For example, if the key is of 1024 bytes, the text to be encrypted cannot exceed 62 bytes (1024/8 -66 = 62).<br> The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.|
| key | string | Yes| RSA key. The key is used as a public key in encryption and a private key in decryption.| | key | string | Yes| RSA key. The key is used as a public key in encryption and a private key in decryption.|
| transformation | string | No| RSA padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**.| | transformation | string | No| RSA padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**.|
...@@ -109,7 +109,7 @@ Encrypts or decrypts data using AES. ...@@ -109,7 +109,7 @@ Encrypts or decrypts data using AES.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| action | string | Yes| Action to perform. The options are as follows:<br>-&nbsp;encrypt<br>-&nbsp;decrypt| | action | string | Yes| Action to perform. The options are as follows:<br>- encrypt<br>- decrypt |
| text | string | Yes| Text to be encrypted or decrypted.<br> The text to be encrypted must be common text. The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| | text | string | Yes| Text to be encrypted or decrypted.<br> The text to be encrypted must be common text. The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.|
| key | string | Yes| Key used for encryption or decryption. It is a string encoded in Base64.| | key | string | Yes| Key used for encryption or decryption. It is a string encoded in Base64.|
| transformation | string | No| Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**.| | transformation | string | No| Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**.|
...@@ -165,7 +165,6 @@ export default { ...@@ -165,7 +165,6 @@ export default {
console.log(`operation complete!`); console.log(`operation complete!`);
} }
}); });
});
} }
} }
......
...@@ -2,8 +2,6 @@ ...@@ -2,8 +2,6 @@
The **Vibrator** module provides APIs for triggering or stopping vibration. The **Vibrator** module provides APIs for triggering or stopping vibration.
Misc devices, including vibrators and LED lights, are used to send signals externally. You can call the APIs of this module to control the vibration of vibrators and turning-on/off of LED lights.
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -19,25 +17,26 @@ import vibrator from '@ohos.vibrator'; ...@@ -19,25 +17,26 @@ import vibrator from '@ohos.vibrator';
vibrate(duration: number): Promise&lt;void&gt; vibrate(duration: number): Promise&lt;void&gt;
Triggers vibration with a specific duration. This API uses a promise to return the execution result. Triggers vibration with the specified duration. This API uses a promise to return the result.
**Required permissions**: ohos.permission.VIBRATE (a system permission) **Required permissions**: ohos.permission.VIBRATE
**System capability**: SystemCapability.Sensors.MiscDevice **System capability**: SystemCapability.Sensors.MiscDevice
**Parameters** **Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------ | ---- | ------------ | | Name | Type | Mandatory| Description |
| duration | number | Yes | Vibration duration.| | -------- | ------ | ---- | ---------------------- |
| duration | number | Yes | Vibration duration, in ms.|
**Return value** **Return value**
| Type | Description |
| ------------------- | ----------- |
| Promise&lt;void&gt; | Promise used to indicate whether the vibration is triggered successfully.|
| Type | Description |
| ------------------- | -------------------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Example** **Example**
```js ```js
vibrator.vibrate(1000).then(()=>{ vibrator.vibrate(1000).then(()=>{
console.log("Promise returned to indicate a successful vibration."); console.log("Promise returned to indicate a successful vibration.");
...@@ -46,28 +45,67 @@ Triggers vibration with a specific duration. This API uses a promise to return t ...@@ -46,28 +45,67 @@ Triggers vibration with a specific duration. This API uses a promise to return t
}); });
``` ```
## vibrator.vibrate<sup>9+</sup>
vibrate(effect: VibrateEffect, attribute: VibrateAttribute): Promise&lt;void&gt;
Triggers vibration with the specified effect and attribute. This API uses a promise to return the result.
**Required permissions**: ohos.permission.VIBRATE
**System capability**: SystemCapability.Sensors.MiscDevice
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | -------------------------------------- | ---- | :------------- |
| effect | [VibrateEffect](#vibrateeffect9) | Yes | Vibration effect.|
| attribute | [VibrateAttribute](#vibrateattribute9) | Yes | Vibration attribute.|
**Return value**
| Type | Description |
| ------------------- | -------------------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```js
vibrator.vibrate({
type: 'time',
duration: 1000
}, {
id: 0,
usage: 'alarm'
}).then(()=>{
console.log("Promise returned to indicate a successful vibration");
}).catch((error)=>{
console.log("error.code" + error.code + "error.message" + error.message);
})
```
## vibrator.vibrate ## vibrator.vibrate
vibrate(duration: number, callback?: AsyncCallback&lt;void&gt;): void vibrate(duration: number, callback?: AsyncCallback&lt;void&gt;): void
Triggers vibration with a specific duration. This API uses an asynchronous callback to return the execution result. Triggers vibration with the specified duration. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.VIBRATE (a system permission) **Required permissions**: ohos.permission.VIBRATE
**System capability**: SystemCapability.Sensors.MiscDevice **System capability**: SystemCapability.Sensors.MiscDevice
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ----------------------- | | -------- | ------------------------- | ---- | ---------------------------------------------------------- |
| duration | number | Yes | Vibration duration. | | duration | number | Yes | Vibration duration, in ms. |
| callback | AsyncCallback&lt;void&gt; | No | Callback used to indicate whether the vibration is triggered successfully.| | callback | AsyncCallback&lt;void&gt; | No | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example** **Example**
```js ```js
vibrator.vibrate(1000,function(error){ vibrator.vibrate(1000,function(error){
if(error){ if(error){
console.log("error.code"+error.code+"error.message"+error.message); console.log("error.code" + error.code + "error.message" + error.message);
}else{ }else{
console.log("Callback returned to indicate a successful vibration."); console.log("Callback returned to indicate a successful vibration.");
} }
...@@ -79,28 +117,28 @@ Triggers vibration with a specific duration. This API uses an asynchronous callb ...@@ -79,28 +117,28 @@ Triggers vibration with a specific duration. This API uses an asynchronous callb
vibrate(effectId: EffectId): Promise&lt;void&gt; vibrate(effectId: EffectId): Promise&lt;void&gt;
Triggers vibration with a specific effect. This API uses a promise to return the execution result. Triggers vibration with the specified effect. This API uses a promise to return the result.
**Required permissions**: ohos.permission.VIBRATE (a system permission) **Required permissions**: ohos.permission.VIBRATE
**System capability**: SystemCapability.Sensors.MiscDevice **System capability**: SystemCapability.Sensors.MiscDevice
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------- | | -------- | --------------------- | ---- | ------------------ |
| effectId | [EffectId](#effectid) | Yes | Vibration effect. | | effectId | [EffectId](#effectid) | Yes | Preset vibration effect ID.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ----------- | | ------------------- | -------------------------------------- |
| Promise&lt;void&gt; | Promise used to indicate whether the vibration is triggered successfully.| | Promise&lt;void&gt; | Promise that returns no value.|
**Example** **Example**
```js ```js
vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(()=>{ vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(()=>{
console.log("Promise returned to indicate a successful vibration."); console.log("Promise returned to indicate a successful vibration.");
}, (error)=>{ }, (error)=>{
console.log("error.code"+error.code+"error.message"+error.message); console.log("error.code" + error.code + "error.message" + error.message);
}); });
``` ```
...@@ -109,56 +147,94 @@ Triggers vibration with a specific effect. This API uses a promise to return the ...@@ -109,56 +147,94 @@ Triggers vibration with a specific effect. This API uses a promise to return the
vibrate(effectId: EffectId, callback?: AsyncCallback&lt;void&gt;): void vibrate(effectId: EffectId, callback?: AsyncCallback&lt;void&gt;): void
Triggers vibration with a specific effect. This API uses an asynchronous callback to return the execution result. Triggers vibration with the specified effect. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.VIBRATE (a system permission) **Required permissions**: ohos.permission.VIBRATE
**System capability**: SystemCapability.Sensors.MiscDevice **System capability**: SystemCapability.Sensors.MiscDevice
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ----------------------- | | -------- | ------------------------- | ---- | ---------------------------------------------------------- |
| effectId | [EffectId](#effectid) | Yes | Vibration effect. | | effectId | [EffectId](#effectid) | Yes | Preset vibration effect ID. |
| callback | AsyncCallback&lt;void&gt; | No | Callback used to indicate whether the vibration is triggered successfully.| | callback | AsyncCallback&lt;void&gt; | No | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example** **Example**
```js ```js
vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function(error){ vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function(error){
if(error){ if(error){
console.log("error.code"+error.code+"error.message"+error.message); console.log("error.code" + error.code + "error.message" + error.message);
}else{ }else{
console.log("Callback returned to indicate a successful vibration."); console.log("Callback returned to indicate a successful vibration.");
} }
}) })
``` ```
## vibrator.vibrate<sup>9+</sup>
vibrate(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback&lt;void&gt;): void
Triggers vibration with the specified effect and attribute. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.VIBRATE
**System capability**: SystemCapability.Sensors.MiscDevice
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | -------------------------------------- | ---- | :--------------------------------------------------------- |
| effect | [VibrateEffect](#vibrateeffect9) | Yes | Vibration effect. |
| attribute | [VibrateAttribute](#vibrateattribute9) | Yes | Vibration attribute. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example**
```js
vibrator.vibrate({
type:'time',
duration:1000,
},{
id:0,
usage: 'alarm'
}, (error)=>{
if(error){
console.log("vibrate fail, error.code:" + error.code + ",error.message:" + error.message);
}else{
console.log("Callback returned to indicate a successful vibration.");
}
});
```
## vibrator.stop ## vibrator.stop
stop(stopMode: VibratorStopMode): Promise&lt;void&gt; stop(stopMode: VibratorStopMode): Promise&lt;void&gt;
Stops the vibration based on the specified **stopMode**. This API uses a promise to return the execution result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called. Stops the vibration with the specified **stopMode**. This API uses a promise to return the result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called.
**Required permissions**: ohos.permission.VIBRATE (a system permission) **Required permissions**: ohos.permission.VIBRATE
**System capability**: SystemCapability.Sensors.MiscDevice **System capability**: SystemCapability.Sensors.MiscDevice
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | --------------- | | -------- | ------------------------------------- | ---- | ------------------------ |
| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Vibration mode to stop.| | stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Mode to stop the vibration.|
**Return value** **Return value**
| Type | Description |
| ------------------- | ----------- | | Type | Description |
| Promise&lt;void&gt; | Promise used to indicate whether the vibration is stopped successfully.| | ------------------- | -------------------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Example** **Example**
```js ```js
vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{ vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{
console.log("Promise returned to indicate a successful vibration."); console.log("Promise returned to indicate a successful vibration.");
}, (error)=>{ }, (error)=>{
console.log("error.code"+error.code+"error.message"+error.message); console.log("error.code" + error.code + "error.message" + error.message);
}); });
``` ```
...@@ -167,23 +243,24 @@ Stops the vibration based on the specified **stopMode**. This API uses a promise ...@@ -167,23 +243,24 @@ Stops the vibration based on the specified **stopMode**. This API uses a promise
stop(stopMode: VibratorStopMode, callback?: AsyncCallback&lt;void&gt;): void; stop(stopMode: VibratorStopMode, callback?: AsyncCallback&lt;void&gt;): void;
Stops the vibration based on the specified **stopMode**. This API uses an asynchronous callback to return the execution result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called. Stops the vibration with the specified **stopMode**. This API uses an asynchronous callback to return the result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called.
**Required permissions**: ohos.permission.VIBRATE (a system permission) **Required permissions**: ohos.permission.VIBRATE
**System capability**: SystemCapability.Sensors.MiscDevice **System capability**: SystemCapability.Sensors.MiscDevice
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ----------------------- | | -------- | ------------------------------------- | ---- | ------------------------------------------------------------ |
| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Vibration mode to stop. | | stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Mode to stop the vibration. |
| callback | AsyncCallback&lt;void&gt; | No | Callback used to indicate whether the vibration is stopped successfully.| | callback | AsyncCallback&lt;void&gt; | No | Callback used to the result. If the vibration stops, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example** **Example**
```js ```js
vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function(error){ vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function(error){
if(error){ if(error){
console.log("error.code"+error.code+"error.message"+error.message); console.log("error.code" + error.code + "error.message" + error.message);
}else{ }else{
console.log("Callback returned to indicate a successful stop."); console.log("Callback returned to indicate a successful stop.");
} }
...@@ -193,22 +270,85 @@ Stops the vibration based on the specified **stopMode**. This API uses an asynch ...@@ -193,22 +270,85 @@ Stops the vibration based on the specified **stopMode**. This API uses an asynch
## EffectId ## EffectId
Describes the vibration effect. Describes the vibration effect ID.
**System capability**: SystemCapability.Sensors.MiscDevice **System capability**: SystemCapability.Sensors.MiscDevice
| Name | Default Value | Description | | Name | Default Value | Description |
| ------------------ | -------------------- | --------------- | | ------------------ | -------------------- | ------------------ |
| EFFECT_CLOCK_TIMER | "haptic.clock.timer" | Vibration effect of the vibrator when a user adjusts the timer.| | EFFECT_CLOCK_TIMER | "haptic.clock.timer" | Preset vibration effect ID.|
## VibratorStopMode ## VibratorStopMode
Describes the vibration mode to stop. Enumerates the modes available to stop the vibration.
**System capability**: SystemCapability.Sensors.MiscDevice **System capability**: SystemCapability.Sensors.MiscDevice
| Name | Default Value | Description | | Name | Default Value | Description |
| ------------------------- | -------- | ---------------------------------------- | | ------------------------- | -------- | ------------------------------------------------------------ |
| VIBRATOR_STOP_MODE_TIME | "time" | The vibration to stop is in **duration** mode. This vibration is triggered with the parameter **duration** of the **number** type.| | VIBRATOR_STOP_MODE_TIME | "time" | The vibration to stop is in **duration** mode. This vibration is triggered with the parameter **duration** of the **number** type.|
| VIBRATOR_STOP_MODE_PRESET | "preset" | The vibration to stop is in **EffectId** mode. This vibration is triggered with the parameter **effectId** of the **EffectId** type.| | VIBRATOR_STOP_MODE_PRESET | "preset" | The vibration to stop is in **EffectId** mode. This vibration is triggered with the parameter **effectId** of the **EffectId** type.|
## VibrateEffect<sup>9+</sup>
Describes the vibration effect.
**System capability**: SystemCapability.Sensors.MiscDevice
| Type | Description |
| -------------------------------- | ------------------------------ |
| [VibrateTime](#vibratetime9) | Triggers vibration with the specified duration. This API uses a promise to return the result.|
| [VibratePreset](#vibratepreset9) | Vibration with a preset effect.|
## VibrateTime<sup>9+</sup>
Describes the vibration with the specified duration.
**System capability**: SystemCapability.Sensors.MiscDevice
| Name | Default Value| Description |
| -------- | ------ | ------------------------------ |
| type | "time" | Vibration with the specified duration.|
| duration | - | Vibration duration, in ms. |
## VibratePreset<sup>9+</sup>
Describes the vibration with a preset effect.
**System capability**: SystemCapability.Sensors.MiscDevice
| Name | Default Value | Description |
| -------- | -------- | ------------------------------ |
| type | "preset" | Vibration with the specified effect.|
| effectId | - | Preset vibration effect ID. |
| count | - | Number of vibrations to repeat. |
## VibrateAttribute<sup>9+</sup>
Describes the vibration attribute.
**System capability**: SystemCapability.Sensors.MiscDevice
| Name | Default Value| Description |
| ----- | ------ | -------------- |
| id | 0 | Vibrator ID. |
| usage | - | Vibration scenario.|
## Usage<sup>9+</sup>
Enumerates the vibration scenarios.
**System capability**: SystemCapability.Sensors.MiscDevice
| Name | Type | Description |
| ---------------- | ------ | ------------------------------ |
| unknown | string | Unknown scenario, with the lowest priority.|
| alarm | string | Vibration for alarms. |
| ring | string | Vibration for incoming calls. |
| notification | string | Vibration for notifications. |
| communication | string | Vibration for communication. |
| touch | string | Touch vibration scenario. |
| media | string | Multimedia vibration scenario. |
| physicalFeedback | string | Physical feedback vibration scenario. |
| simulateReality | string | Simulated reality vibration scenario. |
...@@ -30,13 +30,13 @@ For easier maintenance and evolution, comply with the following principles when ...@@ -30,13 +30,13 @@ For easier maintenance and evolution, comply with the following principles when
2. Provide a sound reason for software introduction. If the software to be introduced already exists in the OpenHarmony project, reuse it to avoid maintenance complexity caused by coexistence of multiple versions. 2. Provide a sound reason for software introduction. If the software to be introduced already exists in the OpenHarmony project, reuse it to avoid maintenance complexity caused by coexistence of multiple versions.
3. Introduce the software in the form of source code, rather than binary files. If a piece of software needs to be introduced in the form of binary files, the PMC should review the request and make a decision. 3. Introduce the software in the form of source code, rather than binary files. If a piece of software needs to be introduced in the form of binary files, the PMC should review the request and make a decision.
4. Make sure the software can be correctly built on the OpenHarmony project. If the software has dependency software that has not been introduced, or the running or build of the software depends on a component that cannot be introduced, the SIG-Architecture should review the request and make a decision. 4. Make sure the software can be correctly built on the OpenHarmony project. If the software has dependency software that has not been introduced, or the running or build of the software depends on a component that cannot be introduced, the SIG-Architecture should review the request and make a decision.
5. Place the software in an independent code repository and name it in the format of **third_party_*****softwareName***, where *softwareName* must be an official name. 5. Place the software in an independent code repository and name it in the format of **third_party**_**softwareName**, where *softwareName* must be an official name.
6. Retain the directory structure, license, and copyright information of the official code repository of the software. Do not modify the original license and copyright information. 6. Retain the directory structure, license, and copyright information of the official code repository of the software. Do not modify the original license and copyright information.
7. Do not introduce any software version that has not been officially released, for example, the Beta version. 7. Do not introduce any software version that has not been officially released, for example, the Beta version.
8. Do not introduce any software version that has high-risk vulnerabilities and does not provide solutions. 8. Do not introduce any software version that has high-risk vulnerabilities and does not provide solutions.
9. If you need to modify the software, place the new code in the software repository and ensure that the new code meets the license requirements of the software. Retain the original license for the modified files, and use the same license for the new files (recommended). 9. If you need to modify the software, place the new code in the software repository and ensure that the new code meets the license requirements of the software. Retain the original license for the modified files, and use the same license for the new files (recommended).
10. Provide the **README.OpenSource** file in the root directory of the software repository. Include the following information in the file: software name, license, license file location, version, upstream community address of the corresponding version, software maintenance owner, function description, and introduction reason. 10. Provide the **README.OpenSource** file in the root directory of the software repository. Include the following information in the file: software name, license, license file location, version, upstream community address of the corresponding version, software maintenance owner, function description, and introduction reason.
11. Make sure the software you introduce is under the custody of a domain SIG. In principle, the SIG-Architecture will deny the introduction of a piece of software without the confirmation of the SIG-Compliance and the corresponding domain SIG. When introducing multiple pieces of software at a time, you can ask the PMC to hold a temporary review meeting between SIGs for faster introduction. If you want to introduce a piece of software but fail to meet the preceding requirements, send an email to law@openatom.org. 11. Make sure the software you introduce is under the custody of a domain SIG. In principle, the SIG-Architecture will deny the introduction of a piece of software without the confirmation of the SIG-Compliance and the corresponding domain SIG. When introducing multiple pieces of software at a time, you can ask the PMC to hold a temporary review meeting between SIGs for faster introduction. If you want to introduce a piece of software but fail to meet the preceding requirements, send an email to oh-legal@openatom.io.
12. When software introduction depends on other dependency software, it is not allowed to nest the dependency software in the subdirectory of the software introduction, and all dependency softwares must be placed in separate repository, and name it in the format of **third_party_*****softwareName***, because nested placement of dependency software may lead to multiple versions of the same software, old versions of security vulnerabilities cannot be fixed in a timely, and will risk the opensource compliance issues. 12. When software introduction depends on other dependency software, it is not allowed to nest the dependency software in the subdirectory of the software introduction, and all dependency softwares must be placed in separate repository, and name it in the format of **third_party_*****softwareName***, because nested placement of dependency software may lead to multiple versions of the same software, old versions of security vulnerabilities cannot be fixed in a timely, and will risk the opensource compliance issues.
- Dependency software are named in the compiled BUILD.gn with part name by prefixing the newly software introduction name, e.g. part_name = "software_introduction_name_dependency software_name". - Dependency software are named in the compiled BUILD.gn with part name by prefixing the newly software introduction name, e.g. part_name = "software_introduction_name_dependency software_name".
- The inter-component dependencies between software introduction and dependency software are resolved via external_deps. - The inter-component dependencies between software introduction and dependency software are resolved via external_deps.
...@@ -51,7 +51,7 @@ For easier maintenance and evolution, comply with the following principles when ...@@ -51,7 +51,7 @@ For easier maintenance and evolution, comply with the following principles when
| Source| Check whether the software is downloaded from its official website or source specified on the official website.| | Source| Check whether the software is downloaded from its official website or source specified on the official website.|
| Community activeness| 1. Do not introduce software from a community or organization that notifies users of software maintenance termination by releasing a bullet, modifying the software repository status, or moving the software repository in a specified directory.<br>2. Do not introduce software from an individual, a small community, or an organization that has not released a version (either official or test version) within two years, does not have a clear version roadmap, or does not respond to any valid bug or pull request in the community.<br>3. Do not introduce software from a community that is not longer maintained or does not respond to any operating status related issue or email for more than half a year.| | Community activeness| 1. Do not introduce software from a community or organization that notifies users of software maintenance termination by releasing a bullet, modifying the software repository status, or moving the software repository in a specified directory.<br>2. Do not introduce software from an individual, a small community, or an organization that has not released a version (either official or test version) within two years, does not have a clear version roadmap, or does not respond to any valid bug or pull request in the community.<br>3. Do not introduce software from a community that is not longer maintained or does not respond to any operating status related issue or email for more than half a year.|
| Security vulnerability| 1. Search for disclosed security vulnerabilities in the industry, and check whether solutions are provided if there are high-risk vulnerabilities in the software.| | Security vulnerability| 1. Search for disclosed security vulnerabilities in the industry, and check whether solutions are provided if there are high-risk vulnerabilities in the software.|
| Software name| 1. Name the repository in the format of **third_party_*****softwareName***, where *softwareName* must be the same as the official name.<br>2. Do not use the sub-module name of the software as the software name.<br>3. If the software has development libraries in multiple languages, add prefixes such as **python-** to the official software name for standardized management.| | Software name| 1. Name the repository in the format of **third_party**_**softwareName**, where **softwareName** must be the same as the official name.<br>2. Do not use the sub-module name of the software as the software name.<br>3. If the software has development libraries in multiple languages, add prefixes such as **python-** to the official software name for standardized management.|
| Official website information| 1. Describe the official website of the software in the request. If there is no official website, provide the project URL on a mainstream code hosting platform. Dot not use the hosting library addresses such as Maven, mvnrepository, and SpringSource.<br>2. Provide the official download address of the software version source package for traceability. If a binary package is required, provide the official download address of the binary package.| | Official website information| 1. Describe the official website of the software in the request. If there is no official website, provide the project URL on a mainstream code hosting platform. Dot not use the hosting library addresses such as Maven, mvnrepository, and SpringSource.<br>2. Provide the official download address of the software version source package for traceability. If a binary package is required, provide the official download address of the binary package.|
| License| 1. Check whether the software to be introduced has a license.<br>2. Check whether the imported license is consistent with the license of the corresponding version on the official website of the software.<br>3. Exercise caution when introducing open-source software with high-risk licenses. Before introducing the software, fully evaluate the risk and attach the analysis conclusion in the request.| | License| 1. Check whether the software to be introduced has a license.<br>2. Check whether the imported license is consistent with the license of the corresponding version on the official website of the software.<br>3. Exercise caution when introducing open-source software with high-risk licenses. Before introducing the software, fully evaluate the risk and attach the analysis conclusion in the request.|
...@@ -63,7 +63,7 @@ Follow the process described in the [SIG Management Regulations](https://gitee.c ...@@ -63,7 +63,7 @@ Follow the process described in the [SIG Management Regulations](https://gitee.c
| Check Item| Description| Self-Check Result Example| | Check Item| Description| Self-Check Result Example|
| :----- | :----- | :----- | | :----- | :----- | :----- |
| Software name| Provide the official name of the software and the repository name to which the software is introduced. The repository name is in the format of **third_party_*****softwareName***.| third_party_*softwareName*| | Software name| Provide the official name of the software and the repository name to which the software is introduced. The repository name is in the format of **third_party**_**softwareName**.| third_party_**softwareName**|
| Official website| Provide the official website link of the software.| https://softwaresite | | Official website| Provide the official website link of the software.| https://softwaresite |
| Software version| Provide the version number of the software to be introduced. The version number must be an official version number released by the community. Do not modify the version number or introduce a version that is not officially released.| 1.0.0 | | Software version| Provide the version number of the software to be introduced. The version number must be an official version number released by the community. Do not modify the version number or introduce a version that is not officially released.| 1.0.0 |
| Software version release date| Provide the official release date of the software version.| 2021.01.01 | | Software version release date| Provide the official release date of the software version.| 2021.01.01 |
...@@ -192,7 +192,7 @@ Refer to the [SIG Management Regulations](https://gitee.com/openharmony/communit ...@@ -192,7 +192,7 @@ Refer to the [SIG Management Regulations](https://gitee.com/openharmony/communit
* Ruby License * Ruby License
* Eclipse Public License 2.0: EPL 2.0 * Eclipse Public License 2.0: EPL 2.0
If you want to introduce the software that complies with the unrecommended licenses listed in **4** or other licenses that are not mentioned, send an email to law@openatom.org. If you want to introduce the software that complies with the unrecommended licenses listed in **4** or other licenses that are not mentioned, send an email to oh-legal@openatom.io.
## Software Exit and Exit Principles ## Software Exit and Exit Principles
......
...@@ -56,17 +56,21 @@ ...@@ -56,17 +56,21 @@
- **Possible Causes** - **Possible Causes**
You do not have the permission to access files in the RISC-V compiler directory. You do not have the permission to access files in the RISC-V compiler directory.
- **Solution** - **Solution**
1. Run the following command to locate **gcc_riscv32**: 1. Run the following command to locate **gcc_riscv32**:
```shell
which riscv32-unknown-elf-gcc
```
```shell
which riscv32-unknown-elf-gcc
```
2. Run the **chmod** command to change the directory permission to **755**. 2. Run the **chmod** command to change the directory permission to **755**.
### "No module named 'Crypto'" Displayed During the Build Process ### "No module named 'Crypto'" Displayed During the Build Process
...@@ -76,7 +80,7 @@ ...@@ -76,7 +80,7 @@
- **Possible Causes** - **Possible Causes**
Crypto is not installed in Python 3. Crypto is not installed in Python3.
- **Solution** - **Solution**
...@@ -109,4 +113,21 @@ ...@@ -109,4 +113,21 @@
sudo ln -s /bin/bash /bin/sh sudo ln -s /bin/bash /bin/sh
``` ```
### "some services are not authenticated. Listed as follows" Displayed During the Build Process
- **Symptom**
The build fails, and "some services are not authenticated. Listed as follows" is displayed.
- **Possible Causes**
For the processes listed in the error information, the UID is set to **root** or **system** in the process configuration files. However, these processes are not high-privilege processes defined by the product.
- **Solution**
Modify the process configuration file to reduce the privilege level. Do not set **UID** to **root** or **system** unless necessary.
If a process must have the **root** or **system** privilege due to service requirements, modify the **high_privilege_process_list.json** file with the approval of security experts. The **high_privilege_process_list.json** file is located in **vendor/**{*company_name*}/{*product_name*}**/security_config**. For example, the file for rk3586 is **//vendor/hihope/rk3568/security_config/high_privilege_process_list.json**.
# Network Management
## Introduction
As a mandatory component for device networking, the network management subsystem implements unified connection management, traffic management, policy management, network sharing of different types of networks, and provides network protocol stack capabilities. An application can call APIs to obtain connection information of a data network, query and subscribe to connection status, network traffic data, and network policy, share the network, and transfer data using a network protocol stack.
The figure below shows the architecture of the network management subsystem. The network management subsystem consists of the following components:
- Basic network management: provides basic network connection management and related JS and native APIs, including connection priority management, connection information query, connection status observation, DNS resolution, traffic management, networking policy management, and physical network management.
- Extended network management: provides extended network management capabilities and related JS and native APIs, including Ethernet connection and hotspot sharing.
- Network protocol stacks: provides basic network protocol stacks (such as HTTP, HTTPS, WebSocket, and TCP/UDP/TLS socket) and related JS APIs.
**Figure 1** Architecture of the network management subsystem
![](figures/en_architecture-of-netmanager-subsystem.png)
## Directory Structure
```
foundation/communication/
├── netmanager_base # Basic network management
├── netmanager_ext # Extended network management
└── netstack # Network protocol stacks
```
## Usage
### Observing Network Status Changes
1. Import the connection namespace from **@ohos.net.connection.d.ts**.
2. Call **createNetConnection()** to create a **NetConnection** object. You can specify the network type, capability, and timeout interval. If you do not specify parameters, the default values will be used.
3. Call **conn.on()** to subscribe to the target event. You must pass in **type** and **callback**.
4. Call **conn.register()** to subscribe to network status changes of the specified network.
6. Call **conn.unregister()** to unsubscribe from the network status changes if required.
```
// Import the connection namespace.
import connection from '@ohos.net.connection'
let netCap = {
// Set the network type to cellular network.
bearerTypes: [connection.NetBearType.BEARER_CELLULAR],
// Set the network capability to Internet.
networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET],
};
let netSpec = {
netCapabilities: netCap,
};
// Set the timeout interval to 10s.
let timeout = 10 * 1000;
// Create a NetConnection object.
let conn = connection.createNetConnection(netSpec, timeout);
// Subscribe to the netAvailable event. When the network is available, the callback will be invoked to report the event.
conn.on('netAvailable', (data=> {
console.log("net is available, netId is " + data.netId);
}));
// Register an observer for network status changes.
conn.register((err, data) => {});
// Unregister the observer for network status changes.
conn.unregister((err, data) => {});
```
### Sharing a Network
1. Import the network sharing namespace from **@ohos.net.sharing**.
2. Set the network sharing type.
3. Start network sharing.
4. Stop network sharing.
```
// Import the network sharing namespace.
import sharing from '@ohos.net.sharing';
// Set the network sharing type.
this.sharingType = 0; // The value 0 indicates Wi-Fi, 1 indicates USB, and 2 indicates Bluetooth.
// Start network sharing.
sharing.startSharing(this.sharingType,(err)=>{
this.callBack(err);
})
// Stop network sharing.
sharing.stopSharing(this.sharingType,(err)=>{
this.callBack(err);
})
```
### Initiating a Network Request
1. Import the HTTP namespace from **@ohos.net.http.d.ts**.
2. Call **createHttp()** to create an **HttpRequest** object.
3. Call **httpRequest.on()** to subscribe to an HTTP response header. This method returns a response earlier than the request. You can subscribe to HTTP response header events based on service requirements.
4. Call **httpRequest.request()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
5. Parse the returned result based on service requirements.
6. Call **httpRequest.destroy()** to release resources after the request is processed.
```
// Import the HTTP namespace.
import http from '@ohos.net.http';
// Each httpRequest corresponds to an HttpRequestTask object and cannot be reused.
let httpRequest = http.createHttp();
// Subscribe to the HTTP response header, which is returned earlier than the response to httpRequest.
httpRequest.on('headersReceive', (data) => {
console.info('header: ' + data.header);
});
httpRequest.request(
// Set the URL for the httpRequest. You must specify the URL address, and set httpRequestOptions as required. You can specify the parameters for GET in extraData.
"EXAMPLE_URL",
{
method: 'POST', // Optional. The default value is GET.
// You can add header fields based on service requirements.
header: {
'Content-Type': 'application/json'
},
// This field is used to transfer data when the POST request is used.
extraData: {
"data": "data to send",
},
connectTimeout: 60000, // This parameter is optional. The default value is 60000, that is, 60s.
readTimeout: 60000, // This parameter is optional. The default value is 60000, that is, 60s.
},(err, data) => {
if (!err) {
// data.result carries the HTTP response. Parse the response based on service requirements.
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
// data.header carries the HTTP response header. Parse the content based on service requirements.
console.info('header:' + data.header);
console.info('header:' + data.cookies);
} else {
console.info('error:' + err);
}
// Call destroy() to release resources after HttpRequest is complete.
httpRequest.destroy();
}
);
```
## Repositories Involved
**Network Management Subsystem**
[communication_netmanager_base](https://gitee.com/openharmony/communication_netmanager_base)
[communication_netmanager_ext](https://gitee.com/openharmony/communication_netmanager_ext)
[communication_netstack](https://gitee.com/openharmony/communication_netstack)
\ No newline at end of file
# OpenHarmony Version Definitions
## Branches
To ensure smooth version evolution and continuous stability and reliability of historical versions, the OpenHarmony community periodically pulls branches such as Long Term Support (LTS), Release, and Beta from Master and manages them based on the OpenHarmony lifecycle definition.
![1.png](figures/1.png)
### Master
Master is the main branch in the OpenHarmony community, to which code updates of all software packages' Master branches in the community are proactively merged for real-time build.
### LTS
LTS is a branch pulled from Master in the OpenHarmony community in the third quarter of each year. This branch is compiled, built, and tested in a centralized manner, and finally reviewed and released by the community.
### Release
Release is a branch pulled from Master in the OpenHarmony community in the first quarter of each year. This branch is compiled, built, and tested in a centralized manner, and finally reviewed and released by the community. A Release branch has the same release requirements but a shorter maintenance period when compared with an LTS branch.
### Beta
Beta is a branch pulled from Master in the OpenHarmony community irregularly. This branch has centralized compilation, building, and basic function verification finished, and can be used for development and debugging.
### Tag
A tag version is a stable and reliable version created by applying patches to an LTS or a Release branch, with the purpose of fixing individual bugs, security vulnerabilities, and other necessary adaptation modifications.
## Maintenance Policies
### Lifecycle Policies
OpenHarmony provides lifecycle management services for LTS and Release branches as follows:
#### Release -> Stop proactive maintenance
The Release SIG periodically makes and maintains tag version plans to resolve individual bugs, security vulnerabilities, and other major issues to ensure continuously stable and available branches.
#### Stop proactive maintenance -> Stop maintenance
The Release SIG no longer proactively plans and releases tag versions. It only fixes security vulnerabilities and major defects in corresponding branches.
### LTS and Release Maintenance Policies
For an LTS branch, the OpenHarmony community provides 2-year proactive maintenance and 1.5-year passive maintenance since its release.
For a Release branch, the OpenHarmony community provides 1-year proactive maintenance and 1-year passive maintenance since its release.
### Branch Merge Policies
The Release SIG is responsible for lifecycle management of an LTS or a Release branch. During the maintenance period, the SIG accepts only code updates that resolve security vulnerabilities, ACTS issues, and other major issues. All code updates can be merged into the branch only after the related pull request has been approved by the [owner](https://gitee.com/openharmony/community/blob/master/zh/BRANCHOWNER).
### Maintenance Schedule
The following table lists the maintenance schedule of the LTS and Release branches that have been released in the OpenHarmony community.
| No. | Branch Name | Branch Type| Release Date | End of Proactive Maintenance| End of Maintenance |
| :--- | ------------- | :------- | :-------- | :----------- | :-------- |
| 1 | 1.0.1-Release | Release | 2021-03-30| 2022-03-30 | 2023-03-30|
| 2 | 3.0-LTS | LTS | 2021-09-30| 2023-09-30 | 2025-03-30|
| 3 | 3.1-Release | Release | 2022-03-30| 2023-03-30 | 2024-03-30|
### Version Plan
The OpenHarmony Release SIG periodically releases, updates, and maintains branch version plans. For details, visit [OpenHarmony-SIG-RoadMap](https://gitee.com/openharmony-sig/oh-inner-release-management/blob/master/OpenHarmony-SIG-RoadMap.md).
...@@ -20,5 +20,5 @@ display.getDefaultDisplay((err, data) => { ...@@ -20,5 +20,5 @@ display.getDefaultDisplay((err, data) => {
} }
console.info('Test Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); console.info('Test Succeeded in obtaining the default display object. Data:' + JSON.stringify(data));
console.info('Test densityDPI:' + JSON.stringify(data.densityDPI)); console.info('Test densityDPI:' + JSON.stringify(data.densityDPI));
});https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-device-info.md) });
``` ```
...@@ -13,25 +13,33 @@ convertxml中convert方法提供了转换xml文本为JavaScript对象的能力 ...@@ -13,25 +13,33 @@ convertxml中convert方法提供了转换xml文本为JavaScript对象的能力
``` ```
import convertxml from '@ohos.convertxml'; import convertxml from '@ohos.convertxml';
// 代码片段 // xml格式的字符串
xml = let xml =
'<?xml version="1.0" encoding="utf-8"?>' + '<?xml version="1.0" encoding="utf-8"?>' +
'<note importance="high" logged="true">' + '<note importance="high" logged="true">' +
' <title>Happy</title>' + ' <title>Happy</title>' +
' <todo>Work</todo>' + ' <todo>Work</todo>' +
' <todo>Play</todo>' + ' <todo>Play</todo>' +
'</note>'; '</note>';
let conv = new convertxml.ConvertXML(); let conv = new convertxml.ConvertXML();
// 转换选项, 参考文档使用 // 转换选项, 参考文档使用
let options = {trim : false, declarationKey:"_declaration", let options = {
instructionKey : "_instruction", attributesKey : "_attributes", trim: false,
textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype", declarationKey: "_declaration",
commentKey : "_comment", parentKey : "_parent", typeKey : "_type", instructionKey: "_instruction",
nameKey : "_name", elementsKey : "_elements"} attributesKey: "_attributes",
let result:any = conv.convert(xml, options) // 将xml文本转为JS对象 textKey: "_text",
cdataKey: "_cdata",
doctypeKey: "_doctype",
commentKey: "_comment",
parentKey: "_parent",
typeKey: "_type",
nameKey: "_name",
elementsKey: "_elements"
}
let result: any = conv.convert(xml, options) // 将xml文本转为JS对象
console.log('Test: ' + JSON.stringify(result)) console.log('Test: ' + JSON.stringify(result))
console.log('Test: ' + result._declaration._attributes.version) // xml代码片段version字段信息 console.log('Test: ' + result._declaration._attributes.version) // xml字符串中version字段信息console.log('Test: ' + result._elements[0]._elements[0]._elements[0]._text) // xml字符串中title字段内容
console.log('Test: ' + result._elements[0]._elements[0]._elements[0]._text) // xml代码片段title字段内容
``` ```
参考文档:[xml转换JavaScript](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-convertxml.md) 参考文档:[xml转换JavaScript](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-convertxml.md)
......
...@@ -21,45 +21,43 @@ let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { ...@@ -21,45 +21,43 @@ let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: {
// 创建pixelmap对象 // 创建pixelmap对象
const color = new ArrayBuffer(96); const color = new ArrayBuffer(96);
let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } } let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } }
image.createPixelMap(color, opts, pixelmap => { image.createPixelMap(color, opts, pixelmap => {
expect(pixelmap !== null).assertTrue(); console.log('Succeeded in creating pixelmap.');
console.info('TC_001-1 success'); })
done();
})
// 用于读像素 // 用于读像素
pixelmap.readPixels(area,(data) => { pixelmap.readPixels(area,(data) => {
if(data !== null) { if(data !== null) {
var bufferArr = new Uint8Array(area.pixels); var bufferArr = new Uint8Array(area.pixels);
var res = true; var res = true;
for (var i = 0; i < bufferArr.length; i++) { for (var i = 0; i < bufferArr.length; i++) {
console.info('TC_021-1 buffer ' + bufferArr[i]); console.info(' buffer ' + bufferArr[i]);
if(res) { if(res) {
if(bufferArr[i] == 0) { if(bufferArr[i] == 0) {
res = false; res = false;
console.info('TC_021-1 Success'); console.log('readPixels end.');
expect(true).assertTrue(); break;
done();
break;
}
}
} }
}
}
}
})
// 用于存像素 // 用于存像素
const readBuffer = new ArrayBuffer(96); const readBuffer = new ArrayBuffer(96);
pixelmap.readPixelsToBuffer(readBuffer,() => { pixelmap.readPixelsToBuffer(readBuffer,() => {
var bufferArr = new Uint8Array(readBuffer); var bufferArr = new Uint8Array(readBuffer);
var res = true; var res = true;
for (var i = 0; i < bufferArr.length; i++) { for (var i = 0; i < bufferArr.length; i++) {
if(res) { if(res) {
if (bufferArr[i] !== 0) { if (bufferArr[i] !== 0) {
res = false; res = false;
console.info('TC_020-1 Success'); console.log('readPixelsToBuffer end.');
expect(true).assertTrue(); break;
done(); }
break;
} }
} }
} })
// 用于写像素 // 用于写像素
pixelmap.writePixels(area,() => { pixelmap.writePixels(area,() => {
...@@ -71,56 +69,51 @@ pixelmap.writePixels(area,() => { ...@@ -71,56 +69,51 @@ pixelmap.writePixels(area,() => {
if(res) { if(res) {
if (readArr[i] !== 0) { if (readArr[i] !== 0) {
res = false; res = false;
console.info('TC_022-1 Success'); console.log('readPixels end.please check buffer');
expect(true).assertTrue();
done();
break; break;
} }
} }
} }
})
})
// 用于写像素到缓冲区 // 用于写像素到缓冲区
pixelmap.writeBufferToPixels(writeColor).then(() => { pixelmap.writeBufferToPixels(writeColor).then(() => {
const readBuffer = new ArrayBuffer(96); const readBuffer = new ArrayBuffer(96);
pixelmap.readPixelsToBuffer(readBuffer).then (() => { pixelmap.readPixelsToBuffer(readBuffer).then (() => {
var bufferArr = new Uint8Array(readBuffer); var bufferArr = new Uint8Array(readBuffer);
var res = true; var res = true;
for (var i = 0; i < bufferArr.length; i++) { for (var i = 0; i < bufferArr.length; i++) {
if(res) { if(res) {
if (bufferArr[i] !== i) { if (bufferArr[i] !== i) {
res = false; res = false;
console.info('TC_023 Success'); console.log('readPixels end.please check buffer');
expect(true).assertTrue()
done();
break; break;
} }
} }
} }
})
})
// 用于获取图片信息 // 用于获取图片信息
pixelmap.getImageInfo( imageInfo => { pixelmap.getImageInfo( imageInfo => {
if (imageInfo !== null) { if (imageInfo !== null) {
console.info('TC_024-1 imageInfo is ready'); console.log('Succeeded in getting imageInfo');
expect(imageInfo.size.height == 4).assertTrue();
expect(imageInfo.size.width == 6).assertTrue();
expect(imageInfo.pixelFormat == 4).assertTrue();
done();
} }
}) })
// 用于释放pixelmap // 用于释放pixelmap
pixelmap.release(()=>{ pixelmap.release(()=>{
expect(true).assertTrue(); console.log('Succeeded in releasing pixelmap');
console.log('TC_027-1 suc');
done();
}) })
let path = '/data/local/tmp/test.jpg';
// 用于创建imagesource(uri) // 用于创建imagesource(uri)
const imageSourceApi = image.createImageSource(path); // '/data/local/tmp/test.jpg' let path = '/data/local/tmp/test.jpg';
const imageSourceApi = image.createImageSource(path);
// 用于创建imagesource(fd) // 用于创建imagesource(fd)
const imageSourceApi = image.createImageSource(29); let fd = 29;
const imageSourceApi = image.createImageSource(fd);
// 用于创建imagesource(data) // 用于创建imagesource(data)
const data = new ArrayBuffer(96); const data = new ArrayBuffer(96);
...@@ -128,15 +121,15 @@ const imageSourceApi = image.createImageSource(data); ...@@ -128,15 +121,15 @@ const imageSourceApi = image.createImageSource(data);
// 用于释放imagesource // 用于释放imagesource
imageSourceApi.release(() => { imageSourceApi.release(() => {
console.info('TC_044-1 Success'); console.log('Succeeded in releasing imagesource');
}) })
// 用于编码 // 用于编码
const imagePackerApi = image.createImagePacker(); const imagePackerApi = image.createImagePacker();
const imageSourceApi = image.createImageSource(0);
let packOpts = { format:"image/jpeg", quality:98 };
imagePackerApi.packing(imageSourceApi, packOpts, data => { imagePackerApi.packing(imageSourceApi, packOpts, data => {
console.info('TC_062-1 finished'); console.log('Succeeded in packing');
expect(data !== null).assertTrue();
done();
}) })
// 用于释放imagepacker // 用于释放imagepacker
...@@ -164,75 +157,54 @@ let decodingOptions = { ...@@ -164,75 +157,54 @@ let decodingOptions = {
// 用于回调方式创建pixelmap // 用于回调方式创建pixelmap
imageSourceApi.createPixelMap(decodingOptions, pixelmap => { imageSourceApi.createPixelMap(decodingOptions, pixelmap => {
console.info('TC_050 createPixelMap '); console.log('Succeeded in creating pixelmap.');
expect(pixelmap !== null ).assertTrue(); })
done();
})
}
// 用于promise创建pixelmap // 用于promise创建pixelmap
imageSourceApi.createPixelMap().then(pixelmap => { imageSourceApi.createPixelMap().then(pixelmap => {
console.info('TC_050-11 createPixelMap '); console.log('Succeeded in creating pixelmap.');
expect(pixelmap !== null ).assertTrue();
done();
}) })
// 函数调用发生异常时,捕捉错误信息 // 函数调用发生异常时,捕捉错误信息
catch(error => { catch(error => {
console.log('TC_050-11 error: ' + error); console.log('Failed in creating pixelmap.' + error);
expect().assertFail();
done();
}) })
// 用于获取像素每行字节数 // 用于获取像素每行字节数
pixelmap.getBytesNumberPerRow( num => { pixelmap.getBytesNumberPerRow( num => {
console.info('TC_025-1 num is ' + num); console.log('Succeeded in getting BytesNumber PerRow.');
expect(num == expectNum).assertTrue();
done();
}) })
// 用于获取像素总字节数 // 用于获取像素总字节数
pixelmap.getPixelBytesNumber(num => { pixelmap.getPixelBytesNumber(num => {
console.info('TC_026-1 num is ' + num); console.log('Succeeded in getting PixelBytesNumber.');
expect(num == expectNum).assertTrue();
done();
}) })
// 用于获取pixelmap信息 // 用于获取pixelmap信息
pixelmap.getImageInfo( imageInfo => {}) pixelmap.getImageInfo( imageInfo => {})
// 用于打印获取失败信息
console.info('TC_024-1 imageInfo is empty');
expect(false).assertTrue()
// 用于释放pixelmap // 用于释放pixelmap
pixelmap.release(()=>{ pixelmap.release(()=>{
expect(true).assertTrue(); console.log('Succeeded in releasing pixelmap');
console.log('TC_027-1 suc');
done();
}) })
// 用于捕捉释放失败信息 // 用于捕捉释放失败信息
catch(error => { catch(error => {
console.log('TC_027-1 error: ' + error); console.log('Failed in releasing pixelmap.' + error);
expect().assertFail();
done();
}) })
``` ```
### 编码场景 ### 编码场景
```js ```js
let path = '/data/local/tmp/test.png' // 设置创建imagesource的路径 let path = '/data/local/tmp/test.png'; // 设置创建imagesource的路径
// 用于设置imagesource // 用于设置imagesource
const imageSourceApi = image.createImageSource(path); // '/data/local/tmp/test.png' const imageSourceApi = image.createImageSource(path); // '/data/local/tmp/test.png'
// 如果创建imagesource失败,打印错误信息 // 如果创建imagesource失败,打印错误信息
if (imageSourceApi == null) { if (imageSourceApi == null) {
console.info('TC_062 create image source failed'); console.log('Failed in creating imageSource.');
expect(false).assertTrue();
done();
} }
// 如果创建imagesource成功,则创建imagepacker // 如果创建imagesource成功,则创建imagepacker
...@@ -240,9 +212,7 @@ const imagePackerApi = image.createImagePacker(); ...@@ -240,9 +212,7 @@ const imagePackerApi = image.createImagePacker();
// 如果创建失败,打印错误信息 // 如果创建失败,打印错误信息
if (imagePackerApi == null) { if (imagePackerApi == null) {
console.info('TC_062 create image packer failed'); console.log('Failed in creating imagePacker.');
expect(false).assertTrue();
done();
} }
// 如果创建imagepacker成功,则设置编码参数 // 如果创建imagepacker成功,则设置编码参数
...@@ -252,19 +222,15 @@ let packOpts = { format:["image/jpeg"], // 支持编码的格式为jpg ...@@ -252,19 +222,15 @@ let packOpts = { format:["image/jpeg"], // 支持编码的格式为jpg
// 用于编码 // 用于编码
imagePackerApi.packing(imageSourceApi, packOpts) imagePackerApi.packing(imageSourceApi, packOpts)
.then( data => { .then( data => {
console.info('TC_062 finished'); console.log('Succeeded in packing');
expect(data !== null).assertTrue();
done();
}) })
// 编码完成,释放imagepacker // 编码完成,释放imagepacker
imagePackerApi.release(); imagePackerApi.release();
// 用于获取imagesource信息 // 用于获取imagesource信息
imageSourceApi.getImageInfo(imageInfo => { imageSourceApi.getImageInfo(imageInfo => {
console.info('TC_045 imageInfo'); console.log('Succeeded in getting imageInfo');
expect(imageInfo !== null).assertTrue();
done();
}) })
// 用于更新增量数据 // 用于更新增量数据
......
...@@ -16,11 +16,11 @@ ...@@ -16,11 +16,11 @@
OpenHarmony提供了一套UI开发框架,即方舟开发框架(ArkUI框架)。方舟开发框架可为开发者提供应用UI开发所必需的能力,比如多种组件、布局计算、动画能力、UI交互、绘制等。 OpenHarmony提供了一套UI开发框架,即方舟开发框架(ArkUI框架)。方舟开发框架可为开发者提供应用UI开发所必需的能力,比如多种组件、布局计算、动画能力、UI交互、绘制等。
方舟开发框架针对不同目的和技术背景的开发者提供了两种开发范式,分别是基于TS扩展的声明式开发范式(简称“声明式开发范式”)和基于JS扩展的类Web开发范式(简称“类Web开发范式”)。以下是两种开发范式的简单对比。 方舟开发框架针对不同目的和技术背景的开发者提供了两种开发范式,分别是基于eTS的声明式开发范式(简称“声明式开发范式”)和兼容JS的类Web开发范式(简称“类Web开发范式”)。以下是两种开发范式的简单对比。
| **开发范式名称** | **语言生态** | **UI更新方式** | **适用场景** | **适用人群** | | **开发范式名称** | **语言生态** | **UI更新方式** | **适用场景** | **适用人群** |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| 声明式开发范式 | 扩展的TS语言(eTS) | 数据驱动更新 | 复杂度较大、团队合作度较高的程序 | 移动系统应用开发人员、系统应用开发人员 | | 声明式开发范式 | eTS语言 | 数据驱动更新 | 复杂度较大、团队合作度较高的程序 | 移动系统应用开发人员、系统应用开发人员 |
| 类Web开发范式 | JS语言 | 数据驱动更新 | 界面较为简单的程序应用和卡片 | Web前端开发人员 | | 类Web开发范式 | JS语言 | 数据驱动更新 | 界面较为简单的程序应用和卡片 | Web前端开发人员 |
更多UI框架的开发内容及指导,详见[UI开发](../ui/arkui-overview.md) 更多UI框架的开发内容及指导,详见[UI开发](../ui/arkui-overview.md)
......
...@@ -796,7 +796,7 @@ call.reject(rejectMessageOptions, (err, data) => { ...@@ -796,7 +796,7 @@ call.reject(rejectMessageOptions, (err, data) => {
## call.reject<sup>7+</sup> ## call.reject<sup>7+</sup>
reject(callId: number, callback: AsyncCallback<void\>): <void\> reject(callId: number, callback: AsyncCallback\<void>): void
拒绝来电。使用callback异步回调。 拒绝来电。使用callback异步回调。
...@@ -811,20 +811,11 @@ reject(callId: number, callback: AsyncCallback<void\>): <void\> ...@@ -811,20 +811,11 @@ reject(callId: number, callback: AsyncCallback<void\>): <void\>
| callId | number | 是 | 呼叫Id。可以通过订阅callDetailsChange事件获得。 | | callId | number | 是 | 呼叫Id。可以通过订阅callDetailsChange事件获得。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
**返回值:**
| 类型 | 说明 |
| ------------------- | --------------------------- |
| Promise&lt;void&gt; | 以Promise形式异步返回结果。 |
**示例:** **示例:**
```js ```js
let promise = call.reject(1); call.reject(1, (err, data) => {
promise.then(data => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
console.log(`reject success, promise: data->${JSON.stringify(data)}`);
}).catch(err => {
console.error(`reject fail, promise: err->${JSON.stringify(err)}`);
}); });
``` ```
...@@ -1624,8 +1615,8 @@ on\(type: 'callDetailsChange', callback: Callback<CallAttributeOptions\>\): void ...@@ -1624,8 +1615,8 @@ on\(type: 'callDetailsChange', callback: Callback<CallAttributeOptions\>\): void
**示例:** **示例:**
```js ```js
call.on('callDetailsChange', (err, data) => { call.on('callDetailsChange', data => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -1649,8 +1640,8 @@ on\(type: 'callEventChange', callback: Callback<CallEventOptions\>\): void ...@@ -1649,8 +1640,8 @@ on\(type: 'callEventChange', callback: Callback<CallEventOptions\>\): void
**示例:** **示例:**
```js ```js
call.on('callEventChange', (err, data) => { call.on('callEventChange', data => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -1674,8 +1665,8 @@ on\(type: 'callDisconnectedCause', callback: Callback<DisconnectedDetails\>): vo ...@@ -1674,8 +1665,8 @@ on\(type: 'callDisconnectedCause', callback: Callback<DisconnectedDetails\>): vo
**示例:** **示例:**
```js ```js
call.on('callDisconnectedCause', (err, data) => { call.on('callDisconnectedCause', data => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -1699,8 +1690,8 @@ on\(type: 'mmiCodeResult', callback: Callback<MmiCodeResults\>\): void ...@@ -1699,8 +1690,8 @@ on\(type: 'mmiCodeResult', callback: Callback<MmiCodeResults\>\): void
**示例:** **示例:**
```js ```js
call.on('mmiCodeResult', (err, data) => { call.on('mmiCodeResult', data => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -1724,8 +1715,8 @@ off\(type: 'callDetailsChange', callback?: Callback<CallAttributeOptions\>\): vo ...@@ -1724,8 +1715,8 @@ off\(type: 'callDetailsChange', callback?: Callback<CallAttributeOptions\>\): vo
**示例:** **示例:**
```js ```js
call.off('callDetailsChange', (err, data) => { call.off('callDetailsChange', data => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -1749,8 +1740,8 @@ off\(type: 'callEventChange', callback?: Callback<CallEventOptions\>\): void ...@@ -1749,8 +1740,8 @@ off\(type: 'callEventChange', callback?: Callback<CallEventOptions\>\): void
**示例:** **示例:**
```js ```js
call.off('callEventChange', (err, data) => { call.off('callEventChange', data => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -1774,8 +1765,8 @@ off\(type: 'callDisconnectedCause', callback?: Callback<DisconnectedDetails\>\): ...@@ -1774,8 +1765,8 @@ off\(type: 'callDisconnectedCause', callback?: Callback<DisconnectedDetails\>\):
**示例:** **示例:**
```js ```js
call.off('callDisconnectedCause', (err, data) => { call.off('callDisconnectedCause', data => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -1799,8 +1790,8 @@ off\(type: 'mmiCodeResult', callback?: Callback<MmiCodeResults\>\): void ...@@ -1799,8 +1790,8 @@ off\(type: 'mmiCodeResult', callback?: Callback<MmiCodeResults\>\): void
**示例:** **示例:**
```js ```js
call.off('mmiCodeResult', (err, data) => { call.off('mmiCodeResult', data => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -2389,7 +2380,7 @@ setAudioDevice\(device: AudioDevice, options: AudioDeviceOptions, callback: Asyn ...@@ -2389,7 +2380,7 @@ setAudioDevice\(device: AudioDevice, options: AudioDeviceOptions, callback: Asyn
let audioDeviceOptions={ let audioDeviceOptions={
bluetoothAddress: "IEEE 802-2014" bluetoothAddress: "IEEE 802-2014"
} }
call.setAudioDevice(1, audioDeviceOptions, (err, value) => { call.setAudioDevice(1, audioDeviceOptions, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
``` ```
......
# 公共文件访问与管理
该模块提供公共文件访问和管理模块中RootInfo与FileInfo中部分属性值的定义。
>![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
>
>- 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
>- 本模块接口为系统接口。
## 导入模块
```js
import fileExtensionInfo from '@ohos.fileExtensionInfo';
```
## fileExtensionInfo.DeviceType
组成RootInfo中的deviceType字段,表明此设备的类型。
**系统能力**:SystemCapability.FileManagement.UserFileService
| 名称 | 值 | 说明 |
| ----- | ------ | ------ |
| DEVICE_LOCAL_DISK | 1 | 本地c,d...盘。 |
| DEVICE_SHARED_DISK | 2 | 多用户共享盘。 |
| DEVICE_SHARED_TERMINAL | 3 | 分布式网络终端设备。 |
| DEVICE_NETWORK_NEIGHBORHOODS | 4 | 网络邻居设备。 |
| DEVICE_EXTERNAL_MTP | 5 | MTP设备。 |
| DEVICE_EXTERNAL_USB | 6 | USB设备。 |
| DEVICE_EXTERNAL_CLOUD | 7 | 云盘设备。 |
## fileExtensionInfo.DeviceFlag
组成RootInfo中的deviceFlags字段,通过与运算判断是否具备某种能力。
**系统能力**:SystemCapability.FileManagement.UserFileService
### 属性
| 名称 | 类型 | 值 | 可读 | 可写 | 说明 |
| ------ | ------ | ---- | ---- | ---- | -------- |
| SUPPORTS_READ | number | 0b1 | 是 | 否 | 支持读 |
| SUPPORTS_WRITE | number | 0b10 | 是 | 否 | 支持写 |
## fileExtensionInfo.DocumentFlag
组成FileInfo中的mode字段,通过与运算判断是否具备某种能力。
**系统能力**:SystemCapability.FileManagement.UserFileService
### 属性
| 名称 | 类型 | 值 | 可读 | 可写 | 说明 |
| ------ | ------ | ---- | ---- | ---- | -------- |
| REPRESENTS_FILE | number | 0b1 | 是 | 否 | 代表文件 |
| REPRESENTS_DIR | number | 0b10 | 是 | 否 | 代表目录 |
| SUPPORTS_READ | number | 0b100 | 是 | 否 | 支持读 |
| SUPPORTS_WRITE | number | 0b1000 | 是 | 否 | 支持写 |
...@@ -73,6 +73,9 @@ function listener(data) { ...@@ -73,6 +73,9 @@ function listener(data) {
console.log("type: " + data.type + ", deviceId: " + data.deviceId); console.log("type: " + data.type + ", deviceId: " + data.deviceId);
} }
// 监听输入设备的热插拔事件
inputDevice.on("change", listener);
// 单独取消listener的监听。 // 单独取消listener的监听。
inputDevice.off("change", listener); inputDevice.off("change", listener);
......
...@@ -228,7 +228,7 @@ Codec MIME类型枚举。 ...@@ -228,7 +228,7 @@ Codec MIME类型枚举。
| VIDEO_MPEG2 | 'video/mpeg2' | 表示视频/mpeg2类型。 | | VIDEO_MPEG2 | 'video/mpeg2' | 表示视频/mpeg2类型。 |
| VIDEO_MPEG4 | 'video/mp4v-es' | 表示视频/mpeg4类型。 | | VIDEO_MPEG4 | 'video/mp4v-es' | 表示视频/mpeg4类型。 |
| VIDEO_VP8 | 'video/x-vnd.on2.vp8' | 表示视频/vp8类型。 | | VIDEO_VP8 | 'video/x-vnd.on2.vp8' | 表示视频/vp8类型。 |
| AUDIO_AAC | "audio/mp4a-latm" | 表示音频/mp4a-latm类型。 | | AUDIO_AAC | 'audio/mp4a-latm' | 表示音频/mp4a-latm类型。 |
| AUDIO_VORBIS | 'audio/vorbis' | 表示音频/vorbis类型。 | | AUDIO_VORBIS | 'audio/vorbis' | 表示音频/vorbis类型。 |
| AUDIO_FLAC | 'audio/flac' | 表示音频/flac类型。 | | AUDIO_FLAC | 'audio/flac' | 表示音频/flac类型。 |
...@@ -240,16 +240,16 @@ Codec MIME类型枚举。 ...@@ -240,16 +240,16 @@ Codec MIME类型枚举。
| 名称 | 值 | 说明 | | 名称 | 值 | 说明 |
| ------------------------ | --------------- | ------------------------------------------------------------ | | ------------------------ | --------------- | ------------------------------------------------------------ |
| MD_KEY_TRACK_INDEX | "track_index" | 表示轨道序号,其对应键值类型为number。 | | MD_KEY_TRACK_INDEX | 'track_index' | 表示轨道序号,其对应键值类型为number。 |
| MD_KEY_TRACK_TYPE | "track_type" | 表示轨道类型,其对应键值类型为number,参考[MediaType](#mediatype8)。 | | MD_KEY_TRACK_TYPE | 'track_type' | 表示轨道类型,其对应键值类型为number,参考[MediaType](#mediatype8)。 |
| MD_KEY_CODEC_MIME | "codec_mime" | 表示codec_mime类型,其对应键值类型为string。 | | MD_KEY_CODEC_MIME | 'codec_mime' | 表示codec_mime类型,其对应键值类型为string。 |
| MD_KEY_DURATION | "duration" | 表示媒体时长,其对应键值类型为number,单位为毫秒(ms)。 | | MD_KEY_DURATION | 'duration' | 表示媒体时长,其对应键值类型为number,单位为毫秒(ms)。 |
| MD_KEY_BITRATE | "bitrate" | 表示比特率,其对应键值类型为number,单位为比特率(bps)。 | | MD_KEY_BITRATE | 'bitrate' | 表示比特率,其对应键值类型为number,单位为比特率(bps)。 |
| MD_KEY_WIDTH | "width" | 表示视频宽度,其对应键值类型为number,单位为像素(px)。 | | MD_KEY_WIDTH | 'width' | 表示视频宽度,其对应键值类型为number,单位为像素(px)。 |
| MD_KEY_HEIGHT | "height" | 表示视频高度,其对应键值类型为number,单位为像素(px)。 | | MD_KEY_HEIGHT | 'height' | 表示视频高度,其对应键值类型为number,单位为像素(px)。 |
| MD_KEY_FRAME_RATE | "frame_rate" | 表示视频帧率,其对应键值类型为number,单位为100帧每秒(100fps)。 | | MD_KEY_FRAME_RATE | 'frame_rate' | 表示视频帧率,其对应键值类型为number,单位为100帧每秒(100fps)。 |
| MD_KEY_AUD_CHANNEL_COUNT | "channel_count" | 表示声道数,其对应键值类型为number。 | | MD_KEY_AUD_CHANNEL_COUNT | 'channel_count' | 表示声道数,其对应键值类型为number。 |
| MD_KEY_AUD_SAMPLE_RATE | "sample_rate" | 表示采样率,其对应键值类型为number,单位为赫兹(Hz)。 | | MD_KEY_AUD_SAMPLE_RATE | 'sample_rate' | 表示采样率,其对应键值类型为number,单位为赫兹(Hz)。 |
## BufferingInfoType<sup>8+</sup> ## BufferingInfoType<sup>8+</sup>
...@@ -441,10 +441,10 @@ function printfDescription(obj) { ...@@ -441,10 +441,10 @@ function printfDescription(obj) {
} }
} }
audioPlayer.getTrackDescription((error, arrlist) => { audioPlayer.getTrackDescription((error, arrList) => {
if (arrlist != null) { if (arrList != null) {
for (let i = 0; i < arrlist.length; i++) { for (let i = 0; i < arrList.length; i++) {
printfDescription(arrlist[i]); printfDescription(arrList[i]);
} }
} else { } else {
console.log(`audio getTrackDescription fail, error:${error}`); console.log(`audio getTrackDescription fail, error:${error}`);
...@@ -477,9 +477,9 @@ function printfDescription(obj) { ...@@ -477,9 +477,9 @@ function printfDescription(obj) {
} }
} }
let arrayDescription = null let arrayDescription = null
audioPlayer.getTrackDescription().then((arrlist) => { audioPlayer.getTrackDescription().then((arrList) => {
if (arrlist != null) { if (arrList != null) {
arrayDescription = arrlist; arrayDescription = arrList;
} else { } else {
console.log('audio getTrackDescription fail'); console.log('audio getTrackDescription fail');
} }
...@@ -1234,10 +1234,10 @@ function printfDescription(obj) { ...@@ -1234,10 +1234,10 @@ function printfDescription(obj) {
} }
} }
videoPlayer.getTrackDescription((error, arrlist) => { videoPlayer.getTrackDescription((error, arrList) => {
if ((arrlist) != null) { if ((arrList) != null) {
for (let i = 0; i < arrlist.length; i++) { for (let i = 0; i < arrList.length; i++) {
printfDescription(arrlist[i]); printfDescription(arrList[i]);
} }
} else { } else {
console.log(`video getTrackDescription fail, error:${error}`); console.log(`video getTrackDescription fail, error:${error}`);
...@@ -1271,9 +1271,9 @@ function printfDescription(obj) { ...@@ -1271,9 +1271,9 @@ function printfDescription(obj) {
} }
let arrayDescription; let arrayDescription;
videoPlayer.getTrackDescription().then((arrlist) => { videoPlayer.getTrackDescription().then((arrList) => {
if (arrlist != null) { if (arrList != null) {
arrayDescription = arrlist; arrayDescription = arrList;
} else { } else {
console.log('video getTrackDescription fail'); console.log('video getTrackDescription fail');
} }
...@@ -1617,10 +1617,10 @@ function printfItemDescription(obj, key) { ...@@ -1617,10 +1617,10 @@ function printfItemDescription(obj, key) {
console.info('audio value is ' + property); //对应key值得value。其类型可为任意类型,具体key对应value的类型可参考[MediaDescriptionKey] console.info('audio value is ' + property); //对应key值得value。其类型可为任意类型,具体key对应value的类型可参考[MediaDescriptionKey]
} }
let audioPlayer = media.createAudioPlayer(); let audioPlayer = media.createAudioPlayer();
audioPlayer.getTrackDescription((error, arrlist) => { audioPlayer.getTrackDescription((error, arrList) => {
if (arrlist != null) { if (arrList != null) {
for (let i = 0; i < arrlist.length; i++) { for (let i = 0; i < arrList.length; i++) {
printfItemDescription(arrlist[i], media.MediaDescriptionKey.MD_KEY_TRACK_TYPE); //打印出每条轨道MD_KEY_TRACK_TYPE的值 printfItemDescription(arrList[i], media.MediaDescriptionKey.MD_KEY_TRACK_TYPE); //打印出每条轨道MD_KEY_TRACK_TYPE的值
} }
} else { } else {
console.log(`audio getTrackDescription fail, error:${error}`); console.log(`audio getTrackDescription fail, error:${error}`);
...@@ -2532,8 +2532,8 @@ videoRecorder.on('error', (error) => { // 设 ...@@ -2532,8 +2532,8 @@ videoRecorder.on('error', (error) => { // 设
| 名称 | 值 | 说明 | | 名称 | 值 | 说明 |
| ----------- | ----- | --------------------- | | ----------- | ----- | --------------------- |
| CFT_MPEG_4 | "mp4" | 视频的容器格式,MP4。 | | CFT_MPEG_4 | 'mp4' | 视频的容器格式,MP4。 |
| CFT_MPEG_4A | "m4a" | 音频的容器格式,M4A。 | | CFT_MPEG_4A | 'm4a' | 音频的容器格式,M4A。 |
## Location ## Location
......
...@@ -162,7 +162,7 @@ connection.getAllNets(function (error, nets) { ...@@ -162,7 +162,7 @@ connection.getAllNets(function (error, nets) {
getAllNets(): Promise&lt;Array&lt;NetHandle&gt;&gt; getAllNets(): Promise&lt;Array&lt;NetHandle&gt;&gt;
获取所有处于连接状态的网络列表,使用promise方式作为异步方法。 获取所有处于连接状态的网络列表,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.GET_NETWORK_INFO **需要权限**:ohos.permission.GET_NETWORK_INFO
...@@ -336,7 +336,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -336,7 +336,7 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt; reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;
向网络管理报告网络处于可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。 向网络管理报告网络处于可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。
使用promise方式作为异步方法。 使用Promise方式作为异步方法。
**需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET **需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET
...@@ -351,7 +351,7 @@ reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt; ...@@ -351,7 +351,7 @@ reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | 以Promise形式返回执行结果。 | | Promise&lt;void&gt; | 无返回值的Promise对象。 |
**示例:** **示例:**
...@@ -398,7 +398,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -398,7 +398,7 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt; reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt;
向网络管理报告网络处于不可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。 向网络管理报告网络处于不可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。
使用promise方式作为异步方法。 使用Promise方式作为异步方法。
**需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET **需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET
...@@ -413,7 +413,7 @@ reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt; ...@@ -413,7 +413,7 @@ reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt;
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | 以Promise形式返回执行结果。 | | Promise&lt;void&gt; | 无返回值的Promise对象。 |
**示例:** **示例:**
...@@ -522,7 +522,7 @@ enableAirplaneMode(): Promise\<void> ...@@ -522,7 +522,7 @@ enableAirplaneMode(): Promise\<void>
| 类型 | 说明 | | 类型 | 说明 |
| ------------------------------------------- | ----------------------------- | | ------------------------------------------- | ----------------------------- |
| Promise\<void> | 以Promise形式返回结果。 | | Promise\<void> | 无返回值的Promise对象。 |
**示例:** **示例:**
...@@ -571,7 +571,7 @@ disableAirplaneMode(): Promise\<void> ...@@ -571,7 +571,7 @@ disableAirplaneMode(): Promise\<void>
| 类型 | 说明 | | 类型 | 说明 |
| ------------------------------------------- | ----------------------------- | | ------------------------------------------- | ----------------------------- |
| Promise\<void> | 以Promise形式返回结果。 | | Promise\<void> | 无返回值的Promise对象。 |
**示例:** **示例:**
...@@ -890,7 +890,7 @@ bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\<void>; ...@@ -890,7 +890,7 @@ bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\<void>;
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ---------------------- | | -------------- | ---------------------- |
| Promise\<void> | 以Promise形式返回结果。 | | Promise\<void> | 无返回值的Promise对象。 |
**示例:** **示例:**
......
...@@ -312,7 +312,7 @@ NDEF Record的TNF(Type Name Field)类型值,参考NDEF标签技术规范《NFC ...@@ -312,7 +312,7 @@ NDEF Record的TNF(Type Name Field)类型值,参考NDEF标签技术规范《NFC
| TNF_UNKNOWN | 0x05 | Unknown。| | TNF_UNKNOWN | 0x05 | Unknown。|
| TNF_UNCHANGED | 0x06 | Unchanged (see section 2.3.3)。| | TNF_UNCHANGED | 0x06 | Unchanged (see section 2.3.3)。|
## RtdType<sup>9+</sup> ## NDEF Record RTD类型定义
NDEF Record的RTD(Record Type Definition)类型值,参考NDEF标签技术规范《NFCForum-TS-NDEF_1.0》的定义细节。 NDEF Record的RTD(Record Type Definition)类型值,参考NDEF标签技术规范《NFCForum-TS-NDEF_1.0》的定义细节。
**需要权限**:ohos.permission.NFC_TAG **需要权限**:ohos.permission.NFC_TAG
...@@ -320,8 +320,8 @@ NDEF Record的RTD(Record Type Definition)类型值,参考NDEF标签技术规 ...@@ -320,8 +320,8 @@ NDEF Record的RTD(Record Type Definition)类型值,参考NDEF标签技术规
**系统能力**:SystemCapability.Communication.NFC.Core **系统能力**:SystemCapability.Communication.NFC.Core
| **参数名** | **常量值** | **说明** | | **参数名** | **常量值** | **说明** |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RTD_TEXT | 常量 'T' | 文本类型的NDEF Record。| | RTD_TEXT<sup>9+</sup> | [0x54] | 文本类型的NDEF Record。|
| RTD_URI | 常量 'U' | URI类型的NDEF Record。| | RTD_URI<sup>9+</sup> | [0x55] | URI类型的NDEF Record。|
## NfcForumType<sup>9+</sup> ## NfcForumType<sup>9+</sup>
NFC Forum标准里面Tag类型的定义。 NFC Forum标准里面Tag类型的定义。
......
...@@ -728,9 +728,9 @@ ndef.writeNdef(ndefMessage, (err, data)=> { ...@@ -728,9 +728,9 @@ ndef.writeNdef(ndefMessage, (err, data)=> {
### NdefTag.canSetReadOnly<sup>9+</sup> ### NdefTag.canSetReadOnly<sup>9+</sup>
canSetReadOnly(): Promise\<boolean> canSetReadOnly(): boolean
检查ndef标签是否可以设置为只读,使用promise方式作为异步方法 检查NDEF标签是否可以设置为只读
**需要权限**:ohos.permission.NFC_TAG **需要权限**:ohos.permission.NFC_TAG
...@@ -740,7 +740,7 @@ canSetReadOnly(): Promise\<boolean> ...@@ -740,7 +740,7 @@ canSetReadOnly(): Promise\<boolean>
| **类型** | **说明** | | **类型** | **说明** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| Promise&lt;boolean&gt; | true: NDEF标签可设置为只读, false: NDEF标签不可设置为只读。 | | boolean| true: NDEF标签可设置为只读, false: NDEF标签不可设置为只读。 |
**示例:** **示例:**
...@@ -748,43 +748,8 @@ canSetReadOnly(): Promise\<boolean> ...@@ -748,43 +748,8 @@ canSetReadOnly(): Promise\<boolean>
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. // see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly.
ndef.canSetReadOnly() var canSetReadOnly = ndef.canSetReadOnly();
.then((data) => { console.log("ndef canSetReadOnly: " + canSetReadOnly);
console.log("ndef canSetReadOnly data: " + data);
}).catch((err)=> {
console.log("ndef canSetReadOnly err: " + err);
});
```
### NdefTag.canSetReadOnly<sup>9+</sup>
canSetReadOnly(callback: AsyncCallback&lt;boolean&gt;): void;
检查ndef标签是否可以设置为只读,使用callback方式作为异步方法。
**需要权限**:ohos.permission.NFC_TAG
**系统能力**:SystemCapability.Communication.NFC
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<boolean> | 是 | 回调函数,NDEF标签可设置为只读,返回true。 |
**示例:**
```js
import tag from '@ohos.nfc.tag';
// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly.
ndef.canSetReadOnly((err, data)=> {
if (err) {
console.log("ndef canSetReadOnly err: " + err);
} else {
console.log("ndef canSetReadOnly data: " + data);
}
});
``` ```
### NdefTag.setReadOnly<sup>9+</sup> ### NdefTag.setReadOnly<sup>9+</sup>
......
...@@ -35,6 +35,8 @@ prompt.showToast({ ...@@ -35,6 +35,8 @@ prompt.showToast({
}); });
``` ```
![zh-cn_image_0001](figures/zh-cn_image_0001.gif)
## ShowToastOptions ## ShowToastOptions
文本提示框的选项。 文本提示框的选项。
...@@ -92,6 +94,8 @@ prompt.showDialog({ ...@@ -92,6 +94,8 @@ prompt.showDialog({
}) })
``` ```
![zh-cn_image_0002](figures/zh-cn_image_0002.gif)
## prompt.showDialog ## prompt.showDialog
showDialog(options: ShowDialogOptions, callback: AsyncCallback&lt;ShowDialogSuccessResponse&gt;):void showDialog(options: ShowDialogOptions, callback: AsyncCallback&lt;ShowDialogSuccessResponse&gt;):void
...@@ -132,6 +136,8 @@ prompt.showDialog({ ...@@ -132,6 +136,8 @@ prompt.showDialog({
}); });
``` ```
![zh-cn_image_0004](figures/zh-cn_image_0004.gif)
## ShowDialogOptions ## ShowDialogOptions
对话框的选项。 对话框的选项。
...@@ -170,7 +176,6 @@ showActionMenu(options: ActionMenuOptions, callback: AsyncCallback&lt;ActionMenu ...@@ -170,7 +176,6 @@ showActionMenu(options: ActionMenuOptions, callback: AsyncCallback&lt;ActionMenu
| options | [ActionMenuOptions](#actionmenuoptions) | 是 | 操作菜单选项。 | | options | [ActionMenuOptions](#actionmenuoptions) | 是 | 操作菜单选项。 |
| callback | AsyncCallback&lt;[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | 是 | 菜单响应结果回调。 | | callback | AsyncCallback&lt;[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | 是 | 菜单响应结果回调。 |
**示例:** **示例:**
```js ```js
...@@ -195,6 +200,8 @@ prompt.showActionMenu({ ...@@ -195,6 +200,8 @@ prompt.showActionMenu({
}) })
``` ```
![zh-cn_image_0005](figures/zh-cn_image_0005.gif)
## prompt.showActionMenu ## prompt.showActionMenu
showActionMenu(options: ActionMenuOptions): Promise&lt;ActionMenuSuccessResponse&gt; showActionMenu(options: ActionMenuOptions): Promise&lt;ActionMenuSuccessResponse&gt;
...@@ -238,6 +245,8 @@ prompt.showActionMenu({ ...@@ -238,6 +245,8 @@ prompt.showActionMenu({
console.info('showActionMenu error: ' + err); console.info('showActionMenu error: ' + err);
}) })
``` ```
![zh-cn_image_0006](figures/zh-cn_image_0006.gif)
## ActionMenuOptions ## ActionMenuOptions
操作菜单的选项。 操作菜单的选项。
......
...@@ -710,7 +710,7 @@ setShowName\(slotId: number, name: string, callback: AsyncCallback<void\>\): voi ...@@ -710,7 +710,7 @@ setShowName\(slotId: number, name: string, callback: AsyncCallback<void\>\): voi
**示例:** **示例:**
```js ```js
let name = "中国移动"; let name = "ShowName";
sim.setShowName(0, name, (err, data) => { sim.setShowName(0, name, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
...@@ -744,7 +744,7 @@ setShowName\(slotId: number, name: string\): Promise\<void\> ...@@ -744,7 +744,7 @@ setShowName\(slotId: number, name: string\): Promise\<void\>
**示例:** **示例:**
```js ```js
let name = "中国移动"; let name = "ShowName";
let promise = sim.setShowName(0, name); let promise = sim.setShowName(0, name);
promise.then(data => { promise.then(data => {
console.log(`setShowName success, promise: data->${JSON.stringify(data)}`); console.log(`setShowName success, promise: data->${JSON.stringify(data)}`);
......
...@@ -25,7 +25,7 @@ URLSearchParams的构造函数。 ...@@ -25,7 +25,7 @@ URLSearchParams的构造函数。
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| init | string[][]&nbsp;\|&nbsp;Record&lt;string,&nbsp;string&gt;&nbsp;\|&nbsp;string&nbsp;\|&nbsp;URLSearchParams | 否 | 入参对象。<br/>-&nbsp;string[][]:字符串二维数组<br/>-&nbsp;Record&lt;string,&nbsp;string&gt;:对象列表<br/>-&nbsp;string:字符串<br/>-&nbsp;URLSearchParams:对象 | | init | string[][] \| Record&lt;string, string&gt; \| string \| URLSearchParams | 否 | 入参对象。<br/>- string[][]:字符串二维数组<br/>- Record&lt;string, string&gt;:对象列表<br/>- string:字符串<br/>- URLSearchParams:对象 |
**示例:** **示例:**
...@@ -127,7 +127,7 @@ entries(): IterableIterator<[string, string]> ...@@ -127,7 +127,7 @@ entries(): IterableIterator<[string, string]>
| 类型 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| IterableIterator&lt;[string,&nbsp;string]&gt; | 返回一个ES6的迭代器。 | | IterableIterator&lt;[string, string]&gt; | 返回一个ES6的迭代器。 |
**示例:** **示例:**
...@@ -191,7 +191,7 @@ get(name: string): string | null ...@@ -191,7 +191,7 @@ get(name: string): string | null
| 类型 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| string | 返回第一个值。 | | string | 返回第一个值。 |
| null | 如果没找到,返回&nbsp;null。 | | null | 如果没找到,返回 null。 |
**示例:** **示例:**
...@@ -332,7 +332,7 @@ for (var value of searchParams.values()) { ...@@ -332,7 +332,7 @@ for (var value of searchParams.values()) {
| 类型 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| IterableIterator&lt;[string,&nbsp;string]&gt; | 返回一个ES6的迭代器。 | | IterableIterator&lt;[string, string]&gt; | 返回一个ES6的迭代器。 |
**示例:** **示例:**
...@@ -403,7 +403,7 @@ URL的构造函数。 ...@@ -403,7 +403,7 @@ URL的构造函数。
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| url | string | 是 | 入参对象。 | | url | string | 是 | 入参对象。 |
| base | string&nbsp;\|&nbsp;URL | 否 | 入参字符串或者对象。<br/>-&nbsp;string:字符串<br/>-&nbsp;URL:字符串或对象 | | base | string \| URL | 否 | 入参字符串或者对象。<br/>- string:字符串<br/>- URL:字符串或对象 |
**示例:** **示例:**
...@@ -441,7 +441,7 @@ toString(): string ...@@ -441,7 +441,7 @@ toString(): string
```js ```js
const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da');
url.toString() url.toString();
``` ```
...@@ -462,5 +462,5 @@ toJSON(): string ...@@ -462,5 +462,5 @@ toJSON(): string
**示例:** **示例:**
```js ```js
const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da');
url.toJSON() url.toJSON();
``` ```
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
## 子组件 ## 子组件
支持子组件&lt;span&gt;
## 属性 ## 属性
......
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
## 子组件 ## 子组件
支持除&lt;list&gt;之外的子组件。 可以包含子组件。
## 属性 ## 属性
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册