You need to sign in or sign up before continuing.
提交 e74ddfc5 编写于 作者: W wangshuainan1 提交者: Gitee

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

Signed-off-by: Nwangshuainan1 <wangshuainan1@huawei.com>
...@@ -231,7 +231,7 @@ zh-cn/application-dev/reference/apis/js-apis-audio.md @zengyawen ...@@ -231,7 +231,7 @@ zh-cn/application-dev/reference/apis/js-apis-audio.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-camera.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-camera.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-image.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-image.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-media.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-media.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-i18n.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-i18n.md @HelloCrease
zh-cn/application-dev/reference/apis/js-apis-intl.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-intl.md @HelloCrease
zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @HelloCrease
...@@ -365,4 +365,7 @@ zh-cn/application-dev/reference/apis/js-apis-buffer.md @zengyawen ...@@ -365,4 +365,7 @@ zh-cn/application-dev/reference/apis/js-apis-buffer.md @zengyawen
zh-cn/application-dev/reference/js-service-widget-ui @HelloCrease zh-cn/application-dev/reference/js-service-widget-ui @HelloCrease
zh-cn/application-dev/website.md @zengyawen zh-cn/application-dev/website.md @zengyawen
zh-cn/application-dev/faqs/ @zengyawen zh-cn/application-dev/faqs/ @zengyawen
zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md @zengyawen
\ No newline at end of file zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md @zengyawen
zh-cn/application-dev/reference/apis/Readme-CN.md @zengyawen
\ No newline at end of file
...@@ -81,7 +81,7 @@ import Ability from '@ohos.application.Ability' ...@@ -81,7 +81,7 @@ import Ability from '@ohos.application.Ability'
```ts ```ts
export default class MySequenceable { export default class MySequenceable {
num: number = 0 num: number = 0
str: String = "" str: string = ""
constructor(num, string) { constructor(num, string) {
this.num = num this.num = num
......
...@@ -26,70 +26,30 @@ ...@@ -26,70 +26,30 @@
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.sensor | sensor.on(sensorType, callback:AsyncCallback&lt;Response&gt;): void | Subscribes to data changes of a type of sensor.| | ohos.sensor | sensor.on(sensorType, callback:AsyncCallback&lt;Response&gt;): void | Subscribes to data changes of a type of sensor.|
| ohos.sensor | sensor.once(sensorType, callback:AsyncCallback&lt;Response&gt;): void | Subscribes to only one data change of a type of sensor.| | ohos.sensor | sensor.once(sensorType, callback:AsyncCallback&lt;Response&gt;): void | Subscribes to only one data change of a type of sensor.|
| ohos.sensor | sensor.off(sensorType, callback:AsyncCallback&lt;void&gt;): void | Unsubscribes from sensor data changes.| | ohos.sensor | sensor.off(sensorType, callback?:AsyncCallback&lt;void&gt;): void | Unsubscribes from sensor data changes.|
## How to Develop ## How to Develop
1. To obtain data from a type of sensor, configure the requested permissions in the **config.json** file. 1. Before obtaining data from a type of sensor, check whether the required permission has been configured.<br>
The system provides the following sensor-related permissions:
``` - ohos.permission.ACCELEROMETER
"reqPermissions": [
{ - ohos.permission.GYROSCOPE
"name": "ohos.permission.ACCELEROMETER",
"reason": "", - ohos.permission.ACTIVITY_MOTION
"usedScene": {
"ability": [ - ohos.permission.READ_HEALTH_DATA
"sensor.index.MainAbility",
".MainAbility" For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md).
],
"when": "inuse"
}
},
{
"name": "ohos.permission.GYROSCOPE",
"reason": "",
"usedScene": {
"ability": [
"sensor.index.MainAbility",
".MainAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.ACTIVITY_MOTION",
"reason": "ACTIVITY_MOTION_TEST",
"usedScene": {
"ability": [
"sensor.index.MainAbility",
".MainAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.READ_HEALTH_DATA",
"reason": "HEALTH_DATA_TEST",
"usedScene": {
"ability": [
"sensor.index.MainAbility",
".MainAbility"
],
"when": "inuse"
}
}
]
```
2. Subscribe to data changes of a type of sensor. 2. Subscribe to data changes of a type of sensor.
``` ```
import sensor from "@ohos.sensor" import sensor from "@ohos.sensor";
sensor.on(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data){ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data){
console.info("Subscription succeeded. data = " + data); // The call is successful, and the obtained sensor data is printed. console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
} });
);
``` ```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**. The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**.
...@@ -99,11 +59,8 @@ ...@@ -99,11 +59,8 @@
3. Unsubscribe from sensor data changes. 3. Unsubscribe from sensor data changes.
``` ```
import sensor from "@ohos.sensor" import sensor from "@ohos.sensor";
sensor.off(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function() { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER);
console.info("Succeeded in unsubscribing from acceleration sensor data."); // The unsubscription is successful, and the result is printed.
}
);
``` ```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**. The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**.
...@@ -113,11 +70,10 @@ ...@@ -113,11 +70,10 @@
4. Subscribe to only one data change of a type of sensor. 4. Subscribe to only one data change of a type of sensor.
``` ```
import sensor from "@ohos.sensor" import sensor from "@ohos.sensor";
sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data) {
console.info("Data obtained successfully. data=" + data); // The call is successful, and the obtained sensor data is printed. console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
} });
);
``` ```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**. The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**.
...@@ -127,11 +83,12 @@ ...@@ -127,11 +83,12 @@
If the API fails to be called, you are advised to use the **try/catch** statement to capture error information that may occur in the code. Example: If the API fails to be called, you are advised to use the **try/catch** statement to capture error information that may occur in the code. Example:
``` ```
import sensor from "@ohos.sensor";
try { try {
sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data) {
console.info("Data obtained successfully. data=" + data); // The call is successful, and the obtained sensor data is printed. console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
}); });
} catch (error) { } catch (error) {
console.error(error); console.error("Failed to get sensor data");
} }
``` ```
\ No newline at end of file
...@@ -52,15 +52,12 @@ The following modules work cooperatively to implement OpenHarmony sensors: Senso ...@@ -52,15 +52,12 @@ The following modules work cooperatively to implement OpenHarmony sensors: Senso
1. To obtain data of the following sensors, you must claim the required permissions. 1. To obtain data of the following sensors, you must claim the required permissions.
Table 7 Sensor data permissions | Sensor | Permission | Sensitivity | Permission Description |
| ------------------------- | -------------------------------- | ------------ | ----------------------- |
| Sensor | Permission | Sensitivity | Permission Description | | Acceleration sensor, uncalibrated acceleration sensor, and linear acceleration sensor| ohos.permission.ACCELEROMETER | system_grant | Allows an application to subscribe to data of these acceleration-related sensors in the motion category.|
| ------------------------- | -------------------------------- | ------------ | ----------------------- | | Gyroscope sensor and uncalibrated gyroscope sensor | ohos.permission.GYROSCOPE | system_grant | Allows an application to subscribe to data of the gyroscope-related sensors in the motion category.|
| Acceleration sensor, uncalibrated acceleration sensor, and linear acceleration sensor| ohos.permission.ACCELEROMETER | system_grant | Allows an application to subscribe to data of these acceleration-related sensors in the motion category.| | Pedometer sensor | ohos.permission.ACTIVITY_MOTION | user_grant | Allows an application to subscribe to the motion status. |
| Gyroscope sensor and uncalibrated gyroscope sensor | ohos.permission.GYROSCOPE | system_grant | Allows an application to subscribe to data of the gyroscope-related sensors in the motion category.| | Heart rate sensor | ohos.permission.READ_HEALTH_DATA | user_grant | Allows an application to read health data. |
| Pedometer sensor | ohos.permission.ACTIVITY_MOTION | user_grant | Allows an application to subscribe to the motion status. |
| Heart rate sensor | ohos.permission.READ_HEALTH_DATA | user_grant | Allows an application to read health data. |
2. The APIs for subscribing to and unsubscribing from sensor data work in pairs. If you do not need sensor data, call the unsubscription API to stop sensor data reporting. 2. The APIs for subscribing to and unsubscribing from sensor data work in pairs. If you do not need sensor data, call the unsubscription API to stop sensor data reporting.
...@@ -22,42 +22,7 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md ...@@ -22,42 +22,7 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md
## How to Develop ## How to Develop
1. Declare the permissions required for controlling vibrators on the hardware device in the `config.json` file. 1. Before using the vibrator on a device, you must declare the **ohos.permission.VIBRATE** permission. For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md).
```
"reqPermissions": [
{
"name": "ohos.permission.ACCELEROMETER",
"reason": "",
"usedScene": {
"ability": [
".MainAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.VIBRATE",
"reason": "",
"usedScene": {
"ability": [
".MainAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.ACTIVITY_MOTION",
"reason": "",
"usedScene": {
"ability": [
".MainAbility"
],
"when": "inuse"
}
}
]
```
2. Trigger the device to vibrate. 2. Trigger the device to vibrate.
......
...@@ -23,4 +23,4 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra ...@@ -23,4 +23,4 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra
## Constraints ## Constraints
When using a vibrator, you must declare the **ohos.permission.VIBRATE** permission before you can control the vibration effect. The authorization mode of this permission is **system_grant**. When using a vibrator, you must declare the **ohos.permission.VIBRATE** permission before you can control the vibration effect.
...@@ -6,8 +6,8 @@ This module provides APIs for accessing ability-specific resources. You can use ...@@ -6,8 +6,8 @@ This module provides APIs for accessing ability-specific resources. You can use
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model. > - The APIs of this module can be used only in the stage model.
## Usage ## Usage
......
...@@ -4,12 +4,12 @@ The **wantConstant** module provides the actions, entities, and flags used in ** ...@@ -4,12 +4,12 @@ The **wantConstant** module provides the actions, entities, and flags used in **
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
``` ```js
import wantConstant from '@ohos.ability.wantConstant' import wantConstant from '@ohos.ability.wantConstant';
``` ```
## wantConstant.Action ## wantConstant.Action
...@@ -46,8 +46,13 @@ Enumerates the action constants of the **Want** object. ...@@ -46,8 +46,13 @@ Enumerates the action constants of the **Want** object.
| ACTION_FILE_SELECT<sup>7+</sup> | ohos.action.fileSelect | Action of selecting a file. | | ACTION_FILE_SELECT<sup>7+</sup> | ohos.action.fileSelect | Action of selecting a file. |
| PARAMS_STREAM<sup>7+</sup> | ability.params.stream | URI of the data stream associated with the target when the data is sent. | | PARAMS_STREAM<sup>7+</sup> | ability.params.stream | URI of the data stream associated with the target when the data is sent. |
| ACTION_APP_ACCOUNT_OAUTH <sup>8+</sup> | ohos.account.appAccount.action.oauth | Action of providing the OAuth service. | | ACTION_APP_ACCOUNT_OAUTH <sup>8+</sup> | ohos.account.appAccount.action.oauth | Action of providing the OAuth service. |
| ACTION_MARKER_DOWNLOAD <sup>9+</sup> | ohos.want.action.marketDownload | Action of downloading an application from the application market.<br>**System API**: This is a system API and cannot be called by third-party applications. | | ACTION_MARKET_DOWNLOAD <sup>9+</sup> | ohos.want.action.marketDownload | Action of downloading an application from the application market.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| ACTION_MARKET_CROWDTEST <sup>9+</sup> | ohos.want.action.marketCrowdTest | Action of crowdtesting an application from the application market.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| DLP_PARAMS_SANDBOX<sup>9+</sup> |ohos.dlp.params.sandbox | Action of obtaining the sandbox flag.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| DLP_PARAMS_BUNDLE_NAME<sup>9+</sup> |ohos.dlp.params.bundleName |Action of obtaining the DLP bundle name.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| DLP_PARAMS_MODULE_NAME<sup>9+</sup> |ohos.dlp.params.moduleName |Action of obtaining the DLP module name.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| DLP_PARAMS_ABILITY_NAME<sup>9+</sup> |ohos.dlp.params.abilityName |Action of obtaining the DLP ability name.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| DLP_PARAMS_INDEX<sup>9+</sup> |ohos.dlp.params.index |Action of obtaining the DLP index.<br>**System API**: This is a system API and cannot be called by third-party applications. |
## wantConstant.Entity ## wantConstant.Entity
......
...@@ -78,7 +78,7 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility { ...@@ -78,7 +78,7 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility {
## WindowExtensionAbility.onWindowReady ## WindowExtensionAbility.onWindowReady
onWindowReady(window: Window): void onWindowReady(window: window.Window): void
Called when a window is ready. Called when a window is ready.
...@@ -88,7 +88,7 @@ Called when a window is ready. ...@@ -88,7 +88,7 @@ Called when a window is ready.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| window | [Window](js-apis-window.md) | Yes| Current **Window** instance.| | window | [window.Window](js-apis-window.md#window) | Yes| Current **Window** instance.|
**Example** **Example**
...@@ -99,7 +99,7 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility { ...@@ -99,7 +99,7 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility {
onWindowReady(window) { onWindowReady(window) {
window.loadContent('WindowExtAbility/pages/index1').then(() => { window.loadContent('WindowExtAbility/pages/index1').then(() => {
window.getProperties().then((pro) => { window.getProperties().then((pro) => {
console.log("WindowExtension " + JSON.stringify(pro)); console.log('WindowExtension ' + JSON.stringify(pro));
}) })
window.show(); window.show();
}) })
......
...@@ -4,7 +4,7 @@ The **Ability** module manages the ability lifecycle and context, such as creati ...@@ -4,7 +4,7 @@ The **Ability** module manages the ability lifecycle and context, such as creati
This module provides the following common ability-related functions: This module provides the following common ability-related functions:
- [Caller](#caller): implements sending of sequenceable data to the target ability when an ability (caller) invokes the target ability (callee). - [Caller](#caller): implements sending of sequenceable data to the target ability when an ability (caller ability) invokes the target ability (callee ability).
- [Callee](#callee): implements callbacks for registration and deregistration of caller notifications. - [Callee](#callee): implements callbacks for registration and deregistration of caller notifications.
> **NOTE** > **NOTE**
...@@ -22,12 +22,12 @@ import Ability from '@ohos.application.Ability'; ...@@ -22,12 +22,12 @@ import Ability from '@ohos.application.Ability';
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| context | [AbilityContext](js-apis-ability-context.md) | Yes| No| Context of an ability.| | context | [AbilityContext](js-apis-ability-context.md) | Yes| No| Context of an ability.|
| launchWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters for starting the ability.| | launchWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters for starting the ability.|
| lastRequestWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters used when the ability was started last time.| | lastRequestWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters used when the ability was started last time.|
| callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.| | callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.|
## Ability.onCreate ## Ability.onCreate
...@@ -39,13 +39,13 @@ Called to initialize the service logic when an ability is created. ...@@ -39,13 +39,13 @@ Called to initialize the service logic when an ability is created.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | Yes| Information related to this ability, including the ability name and bundle name.| | want | [Want](js-apis-application-Want.md) | Yes| Information related to this ability, including the ability name and bundle name.|
| param | AbilityConstant.LaunchParam | Yes| Parameters for starting the ability, and the reason for the last abnormal exit.| | param | AbilityConstant.LaunchParam | Yes| Parameters for starting the ability, and the reason for the last abnormal exit.|
**Example**
**Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
onCreate(want, param) { onCreate(want, param) {
...@@ -65,12 +65,12 @@ Called when a **WindowStage** is created for this ability. ...@@ -65,12 +65,12 @@ Called when a **WindowStage** is created for this ability.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| windowStage | window.WindowStage | Yes| **WindowStage** information.| | windowStage | window.WindowStage | Yes| **WindowStage** information.|
**Example**
**Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
...@@ -88,8 +88,8 @@ Called when the **WindowStage** is destroyed for this ability. ...@@ -88,8 +88,8 @@ Called when the **WindowStage** is destroyed for this ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example** **Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
onWindowStageDestroy() { onWindowStageDestroy() {
...@@ -109,12 +109,12 @@ Called when the **WindowStage** is restored during the migration of this ability ...@@ -109,12 +109,12 @@ Called when the **WindowStage** is restored during the migration of this ability
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| windowStage | window.WindowStage | Yes| **WindowStage** information.| | windowStage | window.WindowStage | Yes| **WindowStage** information.|
**Example**
**Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
onWindowStageRestore(windowStage) { onWindowStageRestore(windowStage) {
...@@ -132,8 +132,8 @@ Called when this ability is destroyed to clear resources. ...@@ -132,8 +132,8 @@ Called when this ability is destroyed to clear resources.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example** **Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
onDestroy() { onDestroy() {
...@@ -151,8 +151,8 @@ Called when this ability is switched from the background to the foreground. ...@@ -151,8 +151,8 @@ Called when this ability is switched from the background to the foreground.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example** **Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
onForeground() { onForeground() {
...@@ -170,8 +170,8 @@ Called when this ability is switched from the foreground to the background. ...@@ -170,8 +170,8 @@ Called when this ability is switched from the foreground to the background.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example** **Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
onBackground() { onBackground() {
...@@ -191,18 +191,18 @@ Called to save data during the ability migration preparation process. ...@@ -191,18 +191,18 @@ Called to save data during the ability migration preparation process.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| wantParam | {[key:&nbsp;string]:&nbsp;any} | Yes| **want** parameter.| | wantParam | {[key:&nbsp;string]:&nbsp;any} | Yes| **want** parameter.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| AbilityConstant.OnContinueResult | Continuation result.| | AbilityConstant.OnContinueResult | Continuation result.|
**Example**
**Example**
```js ```js
import AbilityConstant from "@ohos.application.AbilityConstant" import AbilityConstant from "@ohos.application.AbilityConstant"
class myAbility extends Ability { class myAbility extends Ability {
...@@ -225,20 +225,17 @@ Called when the ability startup mode is set to singleton. ...@@ -225,20 +225,17 @@ Called when the ability startup mode is set to singleton.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | Yes| Want parameters, such as the ability name and bundle name.| | want | [Want](js-apis-application-Want.md) | Yes| Want parameters, such as the ability name and bundle name.|
| launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.| | launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.|
**Example**
**Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
onNewWant(want, launchParams) { onNewWant(want) {
console.log('onNewWant, want:' + want.abilityName); console.log('onNewWant, want:' + want.abilityName);
if (launchParams.launchReason === AbilityConstant.LaunchReason.CONTINUATION) {
console.log('onNewWant, launchReason is continuation');
}
} }
} }
``` ```
...@@ -254,12 +251,12 @@ Called when the configuration of the environment where the ability is running is ...@@ -254,12 +251,12 @@ Called when the configuration of the environment where the ability is running is
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| | config | [Configuration](js-apis-configuration.md) | Yes| New configuration.|
**Example**
**Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
onConfigurationUpdated(config) { onConfigurationUpdated(config) {
...@@ -278,12 +275,12 @@ Dumps client information. ...@@ -278,12 +275,12 @@ Dumps client information.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| params | Array\<string> | Yes| Parameters in the form of a command.| | params | Array\<string> | Yes| Parameters in the form of a command.|
**Example**
**Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
dump(params) { dump(params) {
...@@ -293,11 +290,35 @@ Dumps client information. ...@@ -293,11 +290,35 @@ Dumps client information.
} }
``` ```
## Ability.onMemoryLevel
onMemoryLevel(level: AbilityConstant.MemoryLevel): void;
Called when the system has decided to adjust the memory level. For example, this API can be used when there is not enough memory to run as many background processes as possible.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.|
**Example**
```js
class myAbility extends Ability {
onMemoryLevel(level) {
console.log('onMemoryLevel, level:' + JSON.stringify(level));
}
}
```
## Caller ## Caller
Implements sending of sequenceable data to the target ability when an ability (caller) invokes the target ability (callee). Implements sending of sequenceable data to the target ability when an ability (caller ability) invokes the target ability (callee ability).
## Caller.call ## Caller.call
...@@ -310,19 +331,19 @@ Sends sequenceable data to the target ability. ...@@ -310,19 +331,19 @@ Sends sequenceable data to the target ability.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| | method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.|
| data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| | data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise used to return a response.| | Promise&lt;void&gt; | Promise used to return a response.|
**Example**
**Example**
```js ```js
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
class MyMessageAble{ // Custom sequenceable data structure class MyMessageAble{ // Custom sequenceable data structure
...@@ -383,19 +404,19 @@ Sends sequenceable data to the target ability and obtains the sequenceable data ...@@ -383,19 +404,19 @@ Sends sequenceable data to the target ability and obtains the sequenceable data
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| | method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.|
| data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| | data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;rpc.MessageParcel&gt; | Promise used to return the sequenceable data from the target ability.| | Promise&lt;rpc.MessageParcel&gt; | Promise used to return the sequenceable data from the target ability.|
**Example**
**Example**
```js ```js
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
class MyMessageAble{ class MyMessageAble{
...@@ -455,8 +476,8 @@ Releases the caller interface of the target ability. ...@@ -455,8 +476,8 @@ Releases the caller interface of the target ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example** **Example**
```js ```js
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
var caller; var caller;
...@@ -492,12 +513,12 @@ Registers a callback that is invoked when the stub on the target ability is disc ...@@ -492,12 +513,12 @@ Registers a callback that is invoked when the stub on the target ability is disc
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.| | callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.|
**Example**
**Example**
```js ```js
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
var caller; var caller;
...@@ -540,12 +561,13 @@ Registers a caller notification callback, which is invoked when the target abili ...@@ -540,12 +561,13 @@ Registers a caller notification callback, which is invoked when the target abili
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities.| | method | string | Yes| Notification message string negotiated between the two abilities.|
| callback | CalleeCallBack | Yes| JS notification synchronization callback of the **rpc.MessageParcel** type. The callback must return at least one empty **rpc.Sequenceable** object. Otherwise, the function execution fails.| | callback | CalleeCallBack | Yes| JS notification synchronization callback of the **rpc.MessageParcel** type. The callback must return at least one empty **rpc.Sequenceable** object. Otherwise, the function execution fails.|
**Example** **Example**
```js ```js
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
class MyMessageAble{ class MyMessageAble{
...@@ -595,9 +617,9 @@ Deregisters a caller notification callback, which is invoked when the target abi ...@@ -595,9 +617,9 @@ Deregisters a caller notification callback, which is invoked when the target abi
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| method | string | Yes| Registered notification message string.| | method | string | Yes| Registered notification message string.|
**Example** **Example**
...@@ -618,17 +640,16 @@ Deregisters a caller notification callback, which is invoked when the target abi ...@@ -618,17 +640,16 @@ Deregisters a caller notification callback, which is invoked when the target abi
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| (msg: string) | function | Yes| No| Prototype of the listener function registered by the caller.| | (msg: string) | function | Yes| No| Prototype of the listener function registered by the caller.|
## CalleeCallBack ## CalleeCallBack
(indata: rpc.MessageParcel): rpc.Sequenceable; (indata: rpc.MessageParcel): rpc.Sequenceable;
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| (indata: rpc.MessageParcel) | rpc.Sequenceable | Yes| No| Prototype of the listener function registered by the callee.| | (indata: rpc.MessageParcel) | rpc.Sequenceable | Yes| No| Prototype of the listener function registered by the callee.|
...@@ -65,7 +65,7 @@ Enumerates ability continuation results. ...@@ -65,7 +65,7 @@ Enumerates ability continuation results.
## AbilityConstant.WindowMode ## AbilityConstant.WindowMode
Enumerates the window modes when an ability is started. Enumerates the window modes in which an ability can be displayed at startup.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -76,3 +76,15 @@ Enumerates the window modes when an ability is started. ...@@ -76,3 +76,15 @@ Enumerates the window modes when an ability is started.
| WINDOW_MODE_SPLIT_PRIMARY | 100 | The ability is displayed in the primary window in split-screen mode. | | WINDOW_MODE_SPLIT_PRIMARY | 100 | The ability is displayed in the primary window in split-screen mode. |
| WINDOW_MODE_SPLIT_SECONDARY | 101 | The ability is displayed in the secondary window in split-screen mode. | | WINDOW_MODE_SPLIT_SECONDARY | 101 | The ability is displayed in the secondary window in split-screen mode. |
| WINDOW_MODE_FLOATING | 102 | The ability is displayed in a floating window.| | WINDOW_MODE_FLOATING | 102 | The ability is displayed in a floating window.|
## AbilityConstant.MemoryLevel
Enumerates the memory levels.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Value| Description |
| --- | --- | --- |
| MEMORY_LEVEL_MODERATE | 0 | Moderate memory usage. |
| MEMORY_LEVEL_LOW | 1 | Low memory usage. |
| MEMORY_LEVEL_CRITICAL | 2 | High memory usage. |
...@@ -875,3 +875,265 @@ abilityDelegator.finishTest(msg, 0).then(() => { ...@@ -875,3 +875,265 @@ abilityDelegator.finishTest(msg, 0).then(() => {
console.info("finishTest promise"); console.info("finishTest promise");
}); });
``` ```
### addAbilityStageMonitor<sup>9+</sup>
addAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\<void>): void;
Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes of an ability stage. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ |
| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
var abilityDelegator;
var monitor = {
moduleName: "moduleName",
srcEntrance: "srcEntrance",
}
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.addAbilityStageMonitor(monitor, (err : any) => {
console.info("addAbilityStageMonitor callback");
});
```
### addAbilityStageMonitor<sup>9+</sup>
addAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\<void>;
Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes of an ability stage. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.|
**Return value**
| Type | Description |
| -------------- | ------------------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
var abilityDelegator;
var monitor = {
moduleName: "moduleName",
srcEntrance: "srcEntrance",
}
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.addAbilityStageMonitor(monitor).then(() => {
console.info("addAbilityStageMonitor promise");
});
```
### removeAbilityStageMonitor<sup>9+</sup>
removeAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\<void>): void;
Removes an **AbilityStageMonitor** instance from the application memory. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ |
| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
var abilityDelegator;
var monitor = {
moduleName: "moduleName",
srcEntrance: "srcEntrance",
}
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.removeAbilityStageMonitor(monitor, (err : any) => {
console.info("removeAbilityStageMonitor callback");
});
```
### removeAbilityStageMonitor<sup>9+</sup>
removeAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\<void>;
Removes an **AbilityStageMonitor** object from the application memory. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.|
**Return value**
| Type | Description |
| -------------- | ------------------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
var abilityDelegator;
var monitor = {
moduleName: "moduleName",
srcEntrance: "srcEntrance",
}
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.removeAbilityStageMonitor(monitor).then(() => {
console.info("removeAbilityStageMonitor promise");
});
```
### waitAbilityStageMonitor<sup>9+</sup>
waitAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\<AbilityStage>): void;
Waits for an **AbilityStage** instance that matches the conditions set in an **AbilityStageMonitor** instance and returns the **AbilityStage** instance. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ |
| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.|
| callback | AsyncCallback\<AbilityStage> | Yes | Callback used to return the result. If the operation is successful, an **AbilityStage** instance is returned. Otherwise, no value is returned. |
**Example**
```js
var abilityDelegator;
function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback");
}
var monitor = {
moduleName: "moduleName",
srcEntrance: "srcEntrance",
}
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.waitAbilityStageMonitor(monitor, (err : any, data : any) => {
console.info("waitAbilityStageMonitor callback");
});
```
### waitAbilityStageMonitor<sup>9+</sup>
waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout?: number): Promise\<AbilityStage>;
Waits for an **AbilityStage** instance that matches the conditions set in an **AbilityStageMonitor** instance and returns the **AbilityStage** instance. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.|
| timeout | number | No | Maximum waiting time, in milliseconds.|
**Return value**
| Type | Description |
| -------------- | ------------------- |
| Promise\<AbilityStage> | Promise used to return the result. If the operation is successful, an **AbilityStage** instance is returned. Otherwise, no value is returned.|
**Example**
```js
var abilityDelegator;
function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback");
}
var monitor = {
moduleName: "moduleName",
srcEntrance: "srcEntrance",
}
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.waitAbilityStageMonitor(monitor).then((data : any) => {
console.info("waitAbilityStageMonitor promise");
});
```
### waitAbilityStageMonitor<sup>9+</sup>
waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout: number, callback: AsyncCallback\<AbilityStage>): void;
Waits a period of time for an **AbilityStage** instance that matches the conditions set in an **AbilityStageMonitor** instance and returns the **AbilityStage** instance. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.|
| timeout | number | No | Maximum waiting time, in milliseconds.|
| callback | AsyncCallback\<AbilityStage> | Yes | Callback used to return the result. If the operation is successful, an **AbilityStage** instance is returned. Otherwise, no value is returned. |
**Example**
```js
var abilityDelegator;
var timeout = 100;
function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback");
}
var monitor = {
moduleName: "moduleName",
srcEntrance: "srcEntrance",
}
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.waitAbilityStageMonitor(monitor, timeout, (err : any, data : any) => {
console.info("waitAbilityStageMonitor callback");
});
```
## AbilityStageMonitor
Provides conditions for matching **AbilityStage** instances. The most recently matched **AbilityStage** instance is saved in an **AbilityStageMonitor** instance.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Type | Readable| Writable| Description |
| ------------------------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ |
| moduleName<sup>9+</sup> | string | Yes | Yes | Module name of the **AbilityStage** instance.|
| srcEntrance<sup>9+</sup> | string | Yes | Yes | Source path of the **AbilityStage** instance.|
...@@ -11,7 +11,7 @@ The **AbilityDelegatorArgs** module provides a global register to store the regi ...@@ -11,7 +11,7 @@ The **AbilityDelegatorArgs** module provides a global register to store the regi
The ability delegator arguments are obtained by calling **getArguments** in **AbilityDelegatorRegistry**. The ability delegator arguments are obtained by calling **getArguments** in **AbilityDelegatorRegistry**.
```js ```js
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry';
var args = AbilityDelegatorRegistry.getArguments(); var args = AbilityDelegatorRegistry.getArguments();
``` ```
......
...@@ -89,6 +89,31 @@ Called when the global configuration is updated. ...@@ -89,6 +89,31 @@ Called when the global configuration is updated.
} }
} }
``` ```
## AbilityStage.onMemoryLevel
onMemoryLevel(level: AbilityConstant.MemoryLevel): void;
Called when the system has decided to adjust the memory level. For example, this API can be used when there is not enough memory to run as many background processes as possible.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.|
**Example**
```js
class MyAbilityStage extends AbilityStage {
onMemoryLevel(level) {
console.log('onMemoryLevel, level:' + JSON.stringify(level));
}
}
```
## AbilityStage.context ## AbilityStage.context
context: AbilityStageContext; context: AbilityStageContext;
......
...@@ -22,9 +22,9 @@ Checks whether this application is undergoing a stability test. This API uses an ...@@ -22,9 +22,9 @@ Checks whether this application is undergoing a stability test. This API uses an
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| | callback | AsyncCallback&lt;boolean&gt; | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.|
**Example** **Example**
...@@ -46,9 +46,9 @@ Checks whether this application is undergoing a stability test. This API uses a ...@@ -46,9 +46,9 @@ Checks whether this application is undergoing a stability test. This API uses a
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| | Promise&lt;boolean&gt; | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.|
**Example** **Example**
...@@ -72,9 +72,9 @@ Checks whether this application is running on a RAM constrained device. This API ...@@ -72,9 +72,9 @@ Checks whether this application is running on a RAM constrained device. This API
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| | Promise&lt;boolean&gt; | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.|
**Example** **Example**
...@@ -96,9 +96,9 @@ Checks whether this application is running on a RAM constrained device. This API ...@@ -96,9 +96,9 @@ Checks whether this application is running on a RAM constrained device. This API
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | No| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| | callback | AsyncCallback&lt;boolean&gt; | No| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.|
**Example** **Example**
...@@ -119,9 +119,9 @@ Obtains the memory size of this application. This API uses a promise to return t ...@@ -119,9 +119,9 @@ Obtains the memory size of this application. This API uses a promise to return t
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Size of the application memory.| | Promise&lt;number&gt; | Size of the application memory.|
**Example** **Example**
...@@ -143,9 +143,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb ...@@ -143,9 +143,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;number&gt; | No| Size of the application memory.| | callback | AsyncCallback&lt;number&gt; | No| Size of the application memory.|
**Example** **Example**
...@@ -157,14 +157,12 @@ Obtains the memory size of this application. This API uses an asynchronous callb ...@@ -157,14 +157,12 @@ Obtains the memory size of this application. This API uses an asynchronous callb
``` ```
## appManager.getProcessRunningInfos<sup>(deprecated)</sup> ## appManager.getProcessRunningInfos<sup>(deprecated)</sup>
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation<sup>9+</sup>](#appmanagergetprocessrunninginformation9) instead.
getProcessRunningInfos(): Promise\<Array\<ProcessRunningInfo>>; getProcessRunningInfos(): Promise\<Array\<ProcessRunningInfo>>;
Obtains information about the running processes. This API uses a promise to return the result. Obtains information about the running processes. This API uses a promise to return the result.
> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation<sup>9+</sup>](#appmanagergetprocessrunninginformation9) instead.
**Required permissions**: ohos.permission.GET_RUNNING_INFO **Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -187,14 +185,12 @@ Obtains information about the running processes. This API uses a promise to retu ...@@ -187,14 +185,12 @@ Obtains information about the running processes. This API uses a promise to retu
## appManager.getProcessRunningInfos<sup>(deprecated)</sup> ## appManager.getProcessRunningInfos<sup>(deprecated)</sup>
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation<sup>9+</sup>](#appmanagergetprocessrunninginformation9-1) instead.
getProcessRunningInfos(callback: AsyncCallback\<Array\<ProcessRunningInfo>>): void; getProcessRunningInfos(callback: AsyncCallback\<Array\<ProcessRunningInfo>>): void;
Obtains information about the running processes. This API uses an asynchronous callback to return the result. Obtains information about the running processes. This API uses an asynchronous callback to return the result.
> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation<sup>9+</sup>](#appmanagergetprocessrunninginformation9-1) instead.
**Required permissions**: ohos.permission.GET_RUNNING_INFO **Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -228,7 +224,7 @@ Obtains information about the running processes. This API uses a promise to retu ...@@ -228,7 +224,7 @@ Obtains information about the running processes. This API uses a promise to retu
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<Array\<ProcessRunningInformation>> | Promise used to return the process information.| | Promise\<Array\<[ProcessRunningInformation](#processrunninginformation)>> | Promise used to return the process information.|
**Example** **Example**
...@@ -254,7 +250,7 @@ Obtains information about the running processes. This API uses an asynchronous c ...@@ -254,7 +250,7 @@ Obtains information about the running processes. This API uses an asynchronous c
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<Array\<ProcessRunningInformation>> | No| Callback used to return the process information.| | callback | AsyncCallback\<Array\<[ProcessRunningInformation](#processrunninginformation)>> | No| Callback used to return the process information.|
**Example** **Example**
...@@ -269,7 +265,7 @@ Obtains information about the running processes. This API uses an asynchronous c ...@@ -269,7 +265,7 @@ Obtains information about the running processes. This API uses an asynchronous c
registerApplicationStateObserver(observer: ApplicationStateObserver): number; registerApplicationStateObserver(observer: ApplicationStateObserver): number;
Registers an observer to listen for the state of all applications. Registers an observer to listen for the state changes of all applications.
**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER **Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER
...@@ -307,9 +303,9 @@ Registers an observer to listen for the state of all applications. ...@@ -307,9 +303,9 @@ Registers an observer to listen for the state of all applications.
## appManager.registerApplicationStateObserver<sup>9+</sup> ## appManager.registerApplicationStateObserver<sup>9+</sup>
registerApplicationStateObserver(observer: ApplicationStateObserver, bundleNameList: Array<string>): number; registerApplicationStateObserver(observer: ApplicationStateObserver, bundleNameList: Array\<string>): number;
Registers an observer to listen for the state of a specified application. Registers an observer to listen for the state changes of a specified application.
**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER **Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER
...@@ -322,7 +318,7 @@ Registers an observer to listen for the state of a specified application. ...@@ -322,7 +318,7 @@ Registers an observer to listen for the state of a specified application.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| observer | [ApplicationStateObserver](#applicationstateobserver) | No| Numeric code of the observer.| | observer | [ApplicationStateObserver](#applicationstateobserver) | No| Numeric code of the observer.|
| bundleNameList | Array<string> | No| **bundleName** array to be registered for listening. The maximum value is 128.| | bundleNameList | Array<string> | No| **bundleName** array of the application. A maximum of 128 bundle names can be passed.|
**Example** **Example**
...@@ -359,7 +355,7 @@ Deregisters the application state observer. This API uses an asynchronous callba ...@@ -359,7 +355,7 @@ Deregisters the application state observer. This API uses an asynchronous callba
**System API**: This is a system API and cannot be called by third-party applications. **System API**: This is a system API and cannot be called by third-party applications.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| observerId | number | No| Numeric code of the observer.| | observerId | number | No| Numeric code of the observer.|
...@@ -491,10 +487,10 @@ Kills a process by bundle name and account ID. This API uses a promise to return ...@@ -491,10 +487,10 @@ Kills a process by bundle name and account ID. This API uses a promise to return
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name of an application.| | bundleName | string | Yes| Bundle name of an application.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
**Example** **Example**
...@@ -525,11 +521,11 @@ Kills a process by bundle name and account ID. This API uses an asynchronous cal ...@@ -525,11 +521,11 @@ Kills a process by bundle name and account ID. This API uses an asynchronous cal
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name of an application.| | bundleName | string | Yes| Bundle name of an application.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| callback | AsyncCallback\<void\> | Yes| Callback used to return the result.| | callback | AsyncCallback\<void\> | Yes| Callback used to return the result.|
**Example** **Example**
...@@ -708,9 +704,14 @@ Called when the application state changes. ...@@ -708,9 +704,14 @@ Called when the application state changes.
**Example** **Example**
```js ```js
import ApplicationStateObserver from '@ohos.application.ApplicationStateObserver' var applicationStateObserver = {
const foregroundApplicationInfo = ApplicationStateObserver.onForegroundApplicationChanged(); onForegroundApplicationChanged(appStateData) {
console.log('-------- foregroundApplicationInfo: ---------', foregroundApplicationInfo); console.log('------------ onForegroundApplicationChanged -----------', appStateData);
}
}
const observerCode = app.registerApplicationStateObserver(applicationStateObserver);
console.log('-------- observerCode: ---------', observerCode);
``` ```
## ApplicationStateObserver.onAbilityStateChanged<sup>8+</sup> ## ApplicationStateObserver.onAbilityStateChanged<sup>8+</sup>
...@@ -732,9 +733,13 @@ Called when the ability state changes. ...@@ -732,9 +733,13 @@ Called when the ability state changes.
**Example** **Example**
```js ```js
import ApplicationStateObserver from '@ohos.application.ApplicationStateObserver' var applicationStateObserver = {
const abilityStateChangedInfo = ApplicationStateObserver.onAbilityStateChanged(); onAbilityStateChanged(abilityStateData) {
console.log('-------- abilityStateChangedInfo: ---------', abilityStateChangedInfo); console.log('------------ onAbilityStateChanged -----------', abilityStateData);
}
}
const observerCode = app.registerApplicationStateObserver(applicationStateObserver);
console.log('-------- observerCode: ---------', observerCode);
``` ```
## ApplicationStateObserver.onProcessCreated<sup>8+</sup> ## ApplicationStateObserver.onProcessCreated<sup>8+</sup>
...@@ -756,9 +761,13 @@ Called when a process is created. ...@@ -756,9 +761,13 @@ Called when a process is created.
**Example** **Example**
```js ```js
import ApplicationStateObserver from '@ohos.application.ApplicationStateObserver' var applicationStateObserver = {
const processCreatedInfo = ApplicationStateObserver.onProcessCreated(); onProcessCreated(processData) {
console.log('-------- processCreatedInfo: ---------', processCreatedInfo); console.log('------------ onProcessCreated -----------', processData);
}
}
const observerCode = app.registerApplicationStateObserver(applicationStateObserver);
console.log('-------- observerCode: ---------', observerCode);
``` ```
## ApplicationStateObserver.onProcessDied<sup>8+</sup> ## ApplicationStateObserver.onProcessDied<sup>8+</sup>
...@@ -775,14 +784,46 @@ Called when a process is terminated. ...@@ -775,14 +784,46 @@ Called when a process is terminated.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| processData | ProcessData | No| Process information.| | processData | [ProcessData](#processdata) | No| Process information.|
**Example** **Example**
```js ```js
import ApplicationStateObserver from '@ohos.application.ApplicationStateObserver' var applicationStateObserver = {
const processDiedInfo = ApplicationStateObserver.onProcessDied(); onProcessDied(processData) {
console.log('-------- processDiedInfo: ---------', processDiedInfo); console.log('------------ onProcessDied -----------', processData);
}
}
const observerCode = app.registerApplicationStateObserver(applicationStateObserver);
console.log('-------- observerCode: ---------', observerCode);
```
## ApplicationStateObserver.onProcessStateChanged<sup>9+</sup>
onProcessStateChanged(processData: ProcessData): void;
Called when the process state changes.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| processData | [ProcessData](#processdata) | No| Process information.|
**Example**
```js
var applicationStateObserver = {
onProcessStateChanged(processData) {
console.log('------------ onProcessStateChanged -----------', processData);
}
}
const observerCode = app.registerApplicationStateObserver(applicationStateObserver);
console.log('-------- observerCode: ---------', observerCode);
``` ```
## AppStateData ## AppStateData
...@@ -815,7 +856,7 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo); ...@@ -815,7 +856,7 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo);
## ProcessData ## ProcessData
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission **System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications. **System API**: This is a system API and cannot be called by third-party applications.
...@@ -824,19 +865,19 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo); ...@@ -824,19 +865,19 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo);
| pid<sup>8+</sup> | number | Yes | No | Process ID. | | pid<sup>8+</sup> | number | Yes | No | Process ID. |
| bundleName<sup>8+</sup> | string | Yes | No | Bundle name of an application. | | bundleName<sup>8+</sup> | string | Yes | No | Bundle name of an application. |
| uid<sup>8+</sup> | number | Yes | No | User ID. | | uid<sup>8+</sup> | number | Yes | No | User ID. |
| isContinuousTask<sup>9+</sup> | boolean | Yes | No | Whether the process is a continuous task. |
| isKeepAlive<sup>9+</sup> | boolean | Yes | No | Whether the process remains active. |
## ProcessRunningInfo ## ProcessRunningInfo
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Mission
| Name | Readable/Writable| Type | Mandatory| Description | | Name | Readable/Writable| Type | Mandatory| Description |
| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | | ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| pid<sup>9+</sup> | Read only | number | No | Process ID. | | pid<sup>8+</sup> | Read only | number | No | Process ID. |
| uid<sup>9+</sup> | Read only | number | No | User ID.| | uid<sup>8+</sup> | Read only | number | No | User ID.|
| processName<sup>9+</sup> | Read only | string | No | Process name.| | processName<sup>8+</sup> | Read only | string | No | Process name.|
| bundleNames<sup>9+</sup> | Read only | Array\<string> | No | **bundleName** array in the running processes.| | bundleNames<sup>8+</sup> | Read only | Array\<string> | No | **bundleName** array in the running processes.|
## ApplicationStateObserver ## ApplicationStateObserver
...@@ -850,3 +891,44 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo); ...@@ -850,3 +891,44 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo);
| [onAbilityStateChanged<sup>8+</sup>](#applicationstateobserveronabilitystatechanged8) | AsyncCallback\<void> | Yes | No | Callback invoked when the ability state changes. | | [onAbilityStateChanged<sup>8+</sup>](#applicationstateobserveronabilitystatechanged8) | AsyncCallback\<void> | Yes | No | Callback invoked when the ability state changes. |
| [onProcessCreated<sup>8+</sup>](#applicationstateobserveronprocesscreated8) | AsyncCallback\<void> | Yes | No | Callback invoked when a process is created. | | [onProcessCreated<sup>8+</sup>](#applicationstateobserveronprocesscreated8) | AsyncCallback\<void> | Yes | No | Callback invoked when a process is created. |
| [onProcessDied<sup>8+</sup>](#applicationstateobserveronprocessdied8) | AsyncCallback\<void> | Yes | No | Callback invoked when a process is destroyed. | | [onProcessDied<sup>8+</sup>](#applicationstateobserveronprocessdied8) | AsyncCallback\<void> | Yes | No | Callback invoked when a process is destroyed. |
## ProcessRunningInformation
Defines the process running information.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Readable/Writable| Type | Mandatory| Description |
| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| pid<sup>9+</sup> | Read only | number | No | Process ID. |
| uid<sup>9+</sup> | Read only | number | No | User ID.|
| processName<sup>9+</sup> | Read only | string | No | Process name.|
| bundleNames<sup>9+</sup> | Read only | Array\<string> | No | **bundleName** array in the running processes.|
## ApplicationState<sup>9+</sup>
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
| Name | Value | Description |
| -------------------- | --- | --------------------------------- |
| STATE_CREATE | 1 | State indicating that the application is being created. |
| STATE_FOREGROUND | 2 | State indicating that the application is running in the foreground. |
| STATE_ACTIVE | 3 | State indicating that the application is active. |
| STATE_BACKGROUND | 4 | State indicating that the application is running in the background. |
| STATE_DESTROY | 5 | State indicating that the application is destroyed. |
## ProcessState<sup>9+</sup>
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
| Name | Value | Description |
| -------------------- | --- | --------------------------------- |
| STATE_CREATE | 1 | State indicating that the process is being created. |
| STATE_FOREGROUND | 2 | State indicating that the process is running in the foreground. |
| STATE_ACTIVE | 3 | State indicating that the process is active. |
| STATE_BACKGROUND | 4 | State indicating that the process is running in the background. |
| STATE_DESTROY | 5 | State indicating that the process is destroyed. |
...@@ -12,6 +12,9 @@ When compared with **[LinkedList](js-apis-linkedlist.md)**, **ArrayList** is mor ...@@ -12,6 +12,9 @@ When compared with **[LinkedList](js-apis-linkedlist.md)**, **ArrayList** is mor
**Recommended use case**: Use **ArrayList** when elements in a container need to be frequently read. **Recommended use case**: Use **ArrayList** when elements in a container need to be frequently read.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -72,7 +75,7 @@ Adds an element at the end of this container. ...@@ -72,7 +75,7 @@ Adds an element at the end of this container.
let result1 = arrayList.add(1); let result1 = arrayList.add(1);
let b = [1, 2, 3]; let b = [1, 2, 3];
let result2 = arrayList.add(b); let result2 = arrayList.add(b);
let c = {name: "lala", age: "13"}; let c = {name: "Dylon", age: "13"};
let result3 = arrayList.add(false); let result3 = arrayList.add(false);
``` ```
...@@ -124,9 +127,9 @@ Checks whether this container has the specified element. ...@@ -124,9 +127,9 @@ Checks whether this container has the specified element.
```ts ```ts
let arrayList = new ArrayList(); let arrayList = new ArrayList();
let result = arrayList.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result = arrayList.has("squirrel");
arrayList.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); arrayList.add("squirrel");
let result1 = arrayList.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result1 = arrayList.has("squirrel");
``` ```
### getIndexOf ### getIndexOf
...@@ -361,7 +364,7 @@ arrayList.add(4); ...@@ -361,7 +364,7 @@ arrayList.add(4);
arrayList.add(5); arrayList.add(5);
arrayList.add(4); arrayList.add(4);
arrayList.forEach((value, index) => { arrayList.forEach((value, index) => {
console.log("value:" + value, index); console.log(`value:${value}`, index);
}); });
``` ```
...@@ -623,14 +626,14 @@ arrayList.add(4); ...@@ -623,14 +626,14 @@ arrayList.add(4);
// Method 1: // Method 1:
for (let item of arrayList) { for (let item of arrayList) {
console.log("value:" + item); console.log(`value:${item}`);
} }
// Method 2: // Method 2:
let iter = arrayList[Symbol.iterator](); let iter = arrayList[Symbol.iterator]();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
console.log("value:" + temp); console.log(`value:${temp}`);
temp = iter.next().value; temp = iter.next().value;
} }
``` ```
# ExtensionAbilityInfo # ExtensionAbilityInfo
The **ExtensionAbilityInfo** module provides Extension ability information. Unless otherwise specified, all attributes are obtained through [getBundleInfo](js-apis-Bundle.md#bundlegetbundleinfo), and flags are obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md#bundleflag).
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
The **ExtensionAbilityInfo** module provides Extension ability information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**.
## ExtensionAbilityInfo ## ExtensionAbilityInfo
**System capability**: SystemCapability.BundleManager.BundleFramework **System capability**: SystemCapability.BundleManager.BundleFramework
......
# LauncherAbilityInfo # LauncherAbilityInfo
The **LauncherAbilityInfo** module provides information about a launcher ability. The **LauncherAbilityInfo** module provides information about the launcher ability, which is obtained through [innerBundleManager.getLauncherAbilityInfos](js-apis-Bundle-InnerBundleManager.md).
> **NOTE** > **NOTE**
> >
...@@ -12,8 +12,8 @@ The **LauncherAbilityInfo** module provides information about a launcher ability ...@@ -12,8 +12,8 @@ The **LauncherAbilityInfo** module provides information about a launcher ability
**System API**: This is a system API and cannot be called by third-party applications. **System API**: This is a system API and cannot be called by third-party applications.
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| --------------- | ---------------------------------------------------- | ---- | ---- | ------------------------------------ | | --------------- | ---------------------------------------------------- | ---- | ---- | -------------------------------------- |
| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information of the launcher ability.| | applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information of the launcher ability.|
| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name of the launcher ability. | | elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name of the launcher ability. |
| labelId | number | Yes | No | Label ID of the launcher ability. | | labelId | number | Yes | No | Label ID of the launcher ability. |
......
# ShortcutInfo # ShortcutInfo
The **ShortcutInfo** module provides shortcut information defined in the configuration file. The **ShortcutInfo** module provides shortcut information defined in the configuration file. For details about the configuration in the FA model, see [config.json](../../quick-start/package-structure.md). For details about the configuration in the stage model, see [Internal Structure of the shortcuts Attribute](../../quick-start/stage-structure.md#internal-structure-of-the-shortcuts-attribute).
> **NOTE** > **NOTE**
> >
......
...@@ -812,7 +812,7 @@ Obtains the zoom ratio range. This API uses an asynchronous callback to return t ...@@ -812,7 +812,7 @@ Obtains the zoom ratio range. This API uses an asynchronous callback to return t
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------ | ---- | ------------------------ | | -------- | ------------------------------ | ---- | ------------------------ |
| callback | AsyncCallback<Array<number\>\> | Yes | Callback used to return the result.| | callback | AsyncCallback<Array<number\>\> | Yes | Callback used to return an array containing the minimum and maximum zoom ratios.|
**Example** **Example**
...@@ -838,7 +838,7 @@ Obtains the zoom ratio range. This API uses a promise to return the result. ...@@ -838,7 +838,7 @@ Obtains the zoom ratio range. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| ------------------------ | ------------------------------------------- | | ------------------------ | ------------------------------------------- |
| Promise<Array<number\>\> | Promise used to return the zoom ratio range.| | Promise<Array<number\>\> | Promise used to return an array containing the minimum and maximum zoom ratios.|
**Example** **Example**
......
...@@ -12,6 +12,9 @@ Double-ended queue (deque) is a sequence container implemented based on the queu ...@@ -12,6 +12,9 @@ Double-ended queue (deque) is a sequence container implemented based on the queu
**Recommended use case**: Use **Deque** when you need to frequently insert or remove elements at both the ends of a container. **Recommended use case**: Use **Deque** when you need to frequently insert or remove elements at both the ends of a container.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -64,7 +67,7 @@ deque.insertFront("a"); ...@@ -64,7 +67,7 @@ deque.insertFront("a");
deque.insertFront(1); deque.insertFront(1);
let b = [1, 2, 3]; let b = [1, 2, 3];
deque.insertFront(b); deque.insertFront(b);
let c = {name : "lala", age : "13"}; let c = {name : "Dylon", age : "13"};
deque.insertFront(false); deque.insertFront(false);
``` ```
...@@ -90,7 +93,7 @@ deque.insertEnd("a"); ...@@ -90,7 +93,7 @@ deque.insertEnd("a");
deque.insertEnd(1); deque.insertEnd(1);
let b = [1, 2, 3]; let b = [1, 2, 3];
deque.insertEnd(b); deque.insertEnd(b);
let c = {name : "lala", age : "13"}; let c = {name : "Dylon", age : "13"};
deque.insertEnd(false); deque.insertEnd(false);
``` ```
...@@ -118,9 +121,9 @@ Checks whether this container has the specified element. ...@@ -118,9 +121,9 @@ Checks whether this container has the specified element.
```ts ```ts
let deque = new Deque(); let deque = new Deque();
let result = deque.has("Ahfbrgrbgnutfodgorrogorg"); let result = deque.has("squirrel");
deque.insertFront("Ahfbrgrbgnutfodgorrogorg"); deque.insertFront("squirrel");
let result1 = deque.has("Ahfbrgrbgnutfodgorrogorg"); let result1 = deque.has("squirrel");
``` ```
### popFirst ### popFirst
......
...@@ -4,7 +4,7 @@ The **EffectKit** module provides basic image processing capabilities, including ...@@ -4,7 +4,7 @@ The **EffectKit** module provides basic image processing capabilities, including
This module provides the following classes: This module provides the following classes:
- [Filter](#filter): a class that provides the effect chain. - [Filter](#filter): a class that provides the effect chain, which is a linked list of image processing effects.
- [Color](#color): a class used to store the color picked. - [Color](#color): a class used to store the color picked.
- [ColorPicker](#colorpicker): a smart color picker. - [ColorPicker](#colorpicker): a smart color picker.
...@@ -155,7 +155,7 @@ Obtains the main color of the image and writes the result to a **[Color](#color) ...@@ -155,7 +155,7 @@ Obtains the main color of the image and writes the result to a **[Color](#color)
```js ```js
colorPicker.getMainColor().then(color => { colorPicker.getMainColor().then(color => {
console.log('Succeeded in getting main color.'); console.log('Succeeded in getting main color.');
console.info("color[ARGB]=" + color.alpha + "," + color.red + "," + color.green + "," + color.blue); console.info(`color[ARGB]=${color.alpha},${color.red},${color.green},${color.blue}`);
}).catch(error => { }).catch(error => {
console.log('Failed to get main color.'); console.log('Failed to get main color.');
}) })
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
The **FormInfo** module provides widget information and state. The **FormInfo** module provides widget information and state.
> **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.
## Modules to Import ## Modules to Import
...@@ -120,3 +120,14 @@ Enumerates the widget dimensions. ...@@ -120,3 +120,14 @@ Enumerates the widget dimensions.
| Dimension_2_4<sup>9+</sup> | 3 | 2 x 4. | | Dimension_2_4<sup>9+</sup> | 3 | 2 x 4. |
| Dimension_4_4<sup>9+</sup> | 4 | 4 x 4. | | Dimension_4_4<sup>9+</sup> | 4 | 4 x 4. |
| Dimension_2_1<sup>9+</sup> | 5 | 2 x 1. | | Dimension_2_1<sup>9+</sup> | 5 | 2 x 1. |
## FormInfoFilter
Defines the widget information filter. Only the widget information that meets the filter is returned.
**System capability**: SystemCapability.Ability.Form
| Name | Yes | Description |
| ----------- | ---- | ------------ |
| moduleName<sup>9+</sup> | No | Module name.|
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release. The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release.
> **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.
## Modules to Import ## Modules to Import
...@@ -183,7 +183,7 @@ Obtains the application's widget information that meets a filter criterion on th ...@@ -183,7 +183,7 @@ Obtains the application's widget information that meets a filter criterion on th
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| filter | formInfo.FormInfoFilter | Yes| Filter criterion.| | filter | [formInfo.FormInfoFilter](./js-apis-formInfo.md#forminfofilter) | Yes| Filter criterion.|
| callback | AsyncCallback&lt;Array&lt;[FormInfo](./js-apis-formInfo.md#forminfo-1)&gt;&gt; | Yes| Callback used to return the widget information.| | callback | AsyncCallback&lt;Array&lt;[FormInfo](./js-apis-formInfo.md#forminfo-1)&gt;&gt; | Yes| Callback used to return the widget information.|
**Example** **Example**
...@@ -214,7 +214,7 @@ Obtains the application's widget information on the device. This API uses a prom ...@@ -214,7 +214,7 @@ Obtains the application's widget information on the device. This API uses a prom
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| filter | formInfo.FormInfoFilter | No| Filter criterion.| | filter | [formInfo.FormInfoFilter](./js-apis-formInfo.md) | No| Filter criterion.|
**Return value** **Return value**
......
...@@ -12,6 +12,10 @@ ...@@ -12,6 +12,10 @@
**Recommended use case**: Use **HashMap** when you need to quickly access, remove, and insert key-value pairs. **Recommended use case**: Use **HashMap** when you need to quickly access, remove, and insert key-value pairs.
This topic uses the following to identify the use of generics:
- K: Key
- V: Value
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -90,9 +94,9 @@ Checks whether this container contains the specified key. ...@@ -90,9 +94,9 @@ Checks whether this container contains the specified key.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
let result = hashMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result = hashMap.hasKey("squirrel");
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
let result1 = hashMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result1 = hashMap.hasKey("squirrel");
``` ```
...@@ -121,7 +125,7 @@ Checks whether this container contains the specified value. ...@@ -121,7 +125,7 @@ Checks whether this container contains the specified value.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
let result = hashMap.hasValue(123); let result = hashMap.hasValue(123);
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
let result1 = hashMap.hasValue(123); let result1 = hashMap.hasValue(123);
``` ```
...@@ -150,9 +154,9 @@ Obtains the value of the specified key in this container. ...@@ -150,9 +154,9 @@ Obtains the value of the specified key in this container.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
hashMap.set("sdfs", 356); hashMap.set("sparrow", 356);
let result = hashMap.get("sdfs"); let result = hashMap.get("sparrow");
``` ```
...@@ -174,8 +178,8 @@ Adds all elements in a **HashMap** instance to this container. ...@@ -174,8 +178,8 @@ Adds all elements in a **HashMap** instance to this container.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
hashMap.set("sdfs", 356); hashMap.set("sparrow", 356);
let newHashMap = new HashMap(); let newHashMap = new HashMap();
hashMap.setAll(newHashMap); hashMap.setAll(newHashMap);
``` ```
...@@ -194,7 +198,7 @@ Adds an element to this container. ...@@ -194,7 +198,7 @@ Adds an element to this container.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| key | K | Yes| Key of the target element.| | key | K | Yes| Key of the target element.|
| value | V | Yes| Value of the element.| | value | V | Yes| Value of the target element.|
**Return value** **Return value**
...@@ -206,7 +210,7 @@ Adds an element to this container. ...@@ -206,7 +210,7 @@ Adds an element to this container.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
let result = hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); let result = hashMap.set("squirrel", 123);
``` ```
...@@ -234,9 +238,9 @@ Removes an element with the specified key from this container. ...@@ -234,9 +238,9 @@ Removes an element with the specified key from this container.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
hashMap.set("sdfs", 356); hashMap.set("sparrow", 356);
let result = hashMap.remove("sdfs"); let result = hashMap.remove("sparrow");
``` ```
...@@ -252,8 +256,8 @@ Clears this container and sets its length to **0**. ...@@ -252,8 +256,8 @@ Clears this container and sets its length to **0**.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
hashMap.set("sdfs", 356); hashMap.set("sparrow", 356);
hashMap.clear(); hashMap.clear();
``` ```
...@@ -276,8 +280,8 @@ Obtains an iterator that contains all the elements in this container. ...@@ -276,8 +280,8 @@ Obtains an iterator that contains all the elements in this container.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
hashMap.set("sdfs", 356); hashMap.set("sparrow", 356);
let iter = hashMap.keys(); let iter = hashMap.keys();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -305,8 +309,8 @@ Obtains an iterator that contains all the values in this container. ...@@ -305,8 +309,8 @@ Obtains an iterator that contains all the values in this container.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
hashMap.set("sdfs", 356); hashMap.set("sparrow", 356);
let iter = hashMap.values(); let iter = hashMap.values();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -341,8 +345,8 @@ Replaces an element in this container. ...@@ -341,8 +345,8 @@ Replaces an element in this container.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("sdfs", 123); hashMap.set("sparrow", 123);
let result = hashMap.replace("sdfs", 357); let result = hashMap.replace("sparrow", 357);
``` ```
...@@ -372,8 +376,8 @@ callbackfn ...@@ -372,8 +376,8 @@ callbackfn
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("sdfs", 123); hashMap.set("sparrow", 123);
hashMap.set("dfsghsf", 357); hashMap.set("gull", 357);
hashMap.forEach((value, key) => { hashMap.forEach((value, key) => {
console.log("value:" + value, key); console.log("value:" + value, key);
}); });
...@@ -398,8 +402,8 @@ Obtains an iterator that contains all the elements in this container. ...@@ -398,8 +402,8 @@ Obtains an iterator that contains all the elements in this container.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
hashMap.set("sdfs", 356); hashMap.set("sparrow", 356);
let iter = hashMap.entries(); let iter = hashMap.entries();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -427,8 +431,8 @@ Obtains an iterator, each item of which is a JavaScript object. ...@@ -427,8 +431,8 @@ Obtains an iterator, each item of which is a JavaScript object.
**Example** **Example**
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
hashMap.set("sdfs", 356); hashMap.set("sparrow", 356);
// Method 1: // Method 1:
for (let item of hashMap) { for (let item of hashMap) {
......
...@@ -10,6 +10,9 @@ Unlike [TreeSet](js-apis-treeset.md), which stores and accesses data in sorted o ...@@ -10,6 +10,9 @@ Unlike [TreeSet](js-apis-treeset.md), which stores and accesses data in sorted o
**Recommended use case**: Use **HashSet** when you need a set that has only unique elements or need to deduplicate a set. **Recommended use case**: Use **HashSet** when you need a set that has only unique elements or need to deduplicate a set.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -26,6 +29,17 @@ import HashSet from '@ohos.util.HashSet'; ...@@ -26,6 +29,17 @@ import HashSet from '@ohos.util.HashSet';
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| length | number | Yes| No| Number of elements in a hash set (called container later).| | length | number | Yes| No| Number of elements in a hash set (called container later).|
**Example**
```ts
let hashSet = new HashSet();
hashSet.add(1);
hashSet.add(2);
hashSet.add(3);
hashSet.add(4);
hashSet.add(5);
let res = hashSet.length;
```
### constructor ### constructor
...@@ -88,9 +102,9 @@ Checks whether this container contains the specified element. ...@@ -88,9 +102,9 @@ Checks whether this container contains the specified element.
```ts ```ts
let hashSet = new HashSet(); let hashSet = new HashSet();
let result = hashSet.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result = hashSet.has("squirrel");
hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); hashSet.add("squirrel");
let result1 = hashSet.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result1 = hashSet.has("squirrel");
``` ```
...@@ -118,7 +132,7 @@ Adds an element to this container. ...@@ -118,7 +132,7 @@ Adds an element to this container.
```ts ```ts
let hashSet = new HashSet(); let hashSet = new HashSet();
let result = hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result = hashSet.add("squirrel");
``` ```
...@@ -146,9 +160,9 @@ Removes an element from this container. ...@@ -146,9 +160,9 @@ Removes an element from this container.
```ts ```ts
let hashSet = new HashSet(); let hashSet = new HashSet();
hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); hashSet.add("squirrel");
hashSet.add("sdfs"); hashSet.add("sparrow");
let result = hashSet.remove("sdfs"); let result = hashSet.remove("sparrow");
``` ```
...@@ -164,8 +178,8 @@ Clears this container and sets its length to **0**. ...@@ -164,8 +178,8 @@ Clears this container and sets its length to **0**.
```ts ```ts
let hashSet = new HashSet(); let hashSet = new HashSet();
hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); hashSet.add("squirrel");
hashSet.add("sdfs"); hashSet.add("sparrow");
hashSet.clear(); hashSet.clear();
``` ```
...@@ -188,8 +202,8 @@ Obtains an iterator that contains all the values in this container. ...@@ -188,8 +202,8 @@ Obtains an iterator that contains all the values in this container.
```ts ```ts
let hashSet = new HashSet(); let hashSet = new HashSet();
hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); hashSet.add("squirrel");
hashSet.add("sdfs"); hashSet.add("sparrow");
let iter = hashSet.values(); let iter = hashSet.values();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -225,8 +239,8 @@ callbackfn ...@@ -225,8 +239,8 @@ callbackfn
```ts ```ts
let hashSet = new HashSet(); let hashSet = new HashSet();
hashSet.add("sdfs"); hashSet.add("sparrow");
hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); hashSet.add("squirrel");
hashSet.forEach((value, key) => { hashSet.forEach((value, key) => {
console.log("value:" + value, key); console.log("value:" + value, key);
}); });
...@@ -250,8 +264,8 @@ Obtains an iterator that contains all the elements in this container. ...@@ -250,8 +264,8 @@ Obtains an iterator that contains all the elements in this container.
```ts ```ts
let hashSet = new HashSet(); let hashSet = new HashSet();
hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); hashSet.add("squirrel");
hashSet.add("sdfs"); hashSet.add("sparrow");
let iter = hashSet.entries(); let iter = hashSet.entries();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -280,8 +294,8 @@ Obtains an iterator, each item of which is a JavaScript object. ...@@ -280,8 +294,8 @@ Obtains an iterator, each item of which is a JavaScript object.
```ts ```ts
let hashSet = new HashSet(); let hashSet = new HashSet();
hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); hashSet.add("squirrel");
hashSet.add("sdfs"); hashSet.add("sparrow");
// Method 1: // Method 1:
for (let item of hashSet) { for (let item of hashSet) {
......
...@@ -115,7 +115,7 @@ const readBuffer = new ArrayBuffer(96); ...@@ -115,7 +115,7 @@ const readBuffer = new ArrayBuffer(96);
pixelmap.readPixelsToBuffer(readBuffer).then(() => { pixelmap.readPixelsToBuffer(readBuffer).then(() => {
console.log('Succeeded in reading image pixel data.'); // Called if the condition is met. console.log('Succeeded in reading image pixel data.'); // Called if the condition is met.
}).catch(error => { }).catch(error => {
('Failed to read image pixel data.'); // Called if no condition is met. console.log('Failed to read image pixel data.'); // Called if no condition is met.
}) })
``` ```
...@@ -261,12 +261,7 @@ image.createPixelMap(color, opts) ...@@ -261,12 +261,7 @@ image.createPixelMap(color, opts)
} }
pixelmap.writePixels(area).then(() => { pixelmap.writePixels(area).then(() => {
const readArea = { pixels: new ArrayBuffer(8), console.info('Succeeded to write pixelmap into the specified area.');
offset: 0,
stride: 8,
// region.size.width + x < opts.width, region.size.height + y < opts.height
region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
}
}) })
}).catch(error => { }).catch(error => {
console.log('error: ' + error); console.log('error: ' + error);
...@@ -291,17 +286,20 @@ Writes image pixel map data to an area. This API uses an asynchronous callback t ...@@ -291,17 +286,20 @@ Writes image pixel map data to an area. This API uses an asynchronous callback t
**Example** **Example**
```js ```js
const area = new ArrayBuffer(400); const area = { pixels: new ArrayBuffer(8),
offset: 0,
stride: 8,
region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
}
let bufferArr = new Uint8Array(area.pixels);
for (var i = 0; i < bufferArr.length; i++) {
bufferArr[i] = i + 1;
}
pixelmap.writePixels(area, (error) => { pixelmap.writePixels(area, (error) => {
if (error != undefined) { if (error != undefined) {
console.info('Failed to write pixelmap into the specified area.'); console.info('Failed to write pixelmap into the specified area.');
} else { } else {
const readArea = { console.info('Succeeded to write pixelmap into the specified area.');
pixels: new ArrayBuffer(20),
offset: 0,
stride: 8,
region: { size: { height: 1, width: 2 }, x: 0, y: 0 },
}
} }
}) })
``` ```
...@@ -330,9 +328,11 @@ Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** obj ...@@ -330,9 +328,11 @@ Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** obj
```js ```js
const color = new ArrayBuffer(96); const color = new ArrayBuffer(96);
const pixelMap = new ArrayBuffer(400);
let bufferArr = new Uint8Array(color); let bufferArr = new Uint8Array(color);
pixelMap.writeBufferToPixels(color).then(() => { for (var i = 0; i < bufferArr.length; i++) {
bufferArr[i] = i + 1;
}
pixelmap.writeBufferToPixels(color).then(() => {
console.log("Succeeded in writing data from a buffer to a PixelMap."); console.log("Succeeded in writing data from a buffer to a PixelMap.");
}).catch((err) => { }).catch((err) => {
console.error("Failed to write data from a buffer to a PixelMap."); console.error("Failed to write data from a buffer to a PixelMap.");
...@@ -358,9 +358,11 @@ Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** obj ...@@ -358,9 +358,11 @@ Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** obj
```js ```js
const color = new ArrayBuffer(96); const color = new ArrayBuffer(96);
const pixelMap = new ArrayBuffer(400);
let bufferArr = new Uint8Array(color); let bufferArr = new Uint8Array(color);
pixelMap.writeBufferToPixels(color, function(err) { for (var i = 0; i < bufferArr.length; i++) {
bufferArr[i] = i + 1;
}
pixelmap.writeBufferToPixels(color, function(err) {
if (err) { if (err) {
console.error("Failed to write data from a buffer to a PixelMap."); console.error("Failed to write data from a buffer to a PixelMap.");
return; return;
...@@ -387,12 +389,22 @@ Obtains pixel map information of this image. This API uses a promise to return t ...@@ -387,12 +389,22 @@ Obtains pixel map information of this image. This API uses a promise to return t
**Example** **Example**
```js ```js
const pixelMap = new ArrayBuffer(400); const color = new ArrayBuffer(96);
pixelMap.getImageInfo().then(function(info) { let opts = { editable: true, pixelFormat: 2, size: { height: 6, width: 8 } }
console.log("Succeeded in obtaining the image pixel map information."); image.createPixelMap(color, opts).then(pixelmap => {
}).catch((err) => { globalpixelmap = pixelmap;
console.error("Failed to obtain the image pixel map information."); if (pixelmap == undefined) {
}); console.error("Failed to obtain the image pixel map information.");
}
pixelmap.getImageInfo().then(imageInfo => {
if (imageInfo == undefined) {
console.error("Failed to obtain the image pixel map information.");
}
if (imageInfo.size.height == 4 && imageInfo.size.width == 6) {
console.log("Succeeded in obtaining the image pixel map information.");
}
})
})
``` ```
### getImageInfo<sup>7+</sup> ### getImageInfo<sup>7+</sup>
...@@ -412,8 +424,21 @@ Obtains pixel map information of this image. This API uses an asynchronous callb ...@@ -412,8 +424,21 @@ Obtains pixel map information of this image. This API uses an asynchronous callb
**Example** **Example**
```js ```js
pixelmap.getImageInfo((imageInfo) => { const color = new ArrayBuffer(96);
console.log("Succeeded in obtaining the image pixel map information."); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts, (err, pixelmap) => {
if (pixelmap == undefined) {
globalpixelmap = pixelmap;
console.error("Failed to obtain the image pixel map information.");
}
pixelmap.getImageInfo((err, imageInfo) => {
if (imageInfo == undefined) {
console.error("Failed to obtain the image pixel map information.");
}
if (imageInfo.size.height == 4 && imageInfo.size.width == 6) {
console.log("Succeeded in obtaining the image pixel map information.");
}
})
}) })
``` ```
...@@ -500,9 +525,15 @@ Sets an opacity rate for this image pixel map. This API uses an asynchronous cal ...@@ -500,9 +525,15 @@ Sets an opacity rate for this image pixel map. This API uses an asynchronous cal
**Example** **Example**
```js ```js
async function () { var rate = 0.5;
await pixelMap.opacity(0.5); pixelmap.opacity(rate, (err) => {
} if (err) {
console.error("Failed to set opacity.");
return;
} else {
console.log("Succeeded in setting opacity.");
}
})
``` ```
### opacity<sup>9+</sup> ### opacity<sup>9+</sup>
...@@ -529,7 +560,8 @@ Sets an opacity rate for this image pixel map. This API uses a promise to return ...@@ -529,7 +560,8 @@ Sets an opacity rate for this image pixel map. This API uses a promise to return
```js ```js
async function () { async function () {
await pixelMap.opacity(0.5); var rate = 0.5;
await pixelmap.opacity(rate);
} }
``` ```
...@@ -550,12 +582,8 @@ Creates a **PixelMap** object that contains only the alpha channel information. ...@@ -550,12 +582,8 @@ Creates a **PixelMap** object that contains only the alpha channel information.
**Example** **Example**
```js ```js
pixelMap.createAlphaPixelmap(async (err, alphaPixelMap) => { async function () {
if (alphaPixelMap == undefined) { await pixelmap.createAlphaPixelmap();
console.info('Failed to obtain new pixel map.');
} else {
console.info('Succeed in obtaining new pixel map.');
}
}) })
``` ```
...@@ -576,14 +604,13 @@ Creates a **PixelMap** object that contains only the alpha channel information. ...@@ -576,14 +604,13 @@ Creates a **PixelMap** object that contains only the alpha channel information.
**Example** **Example**
```js ```js
let pixelMap = await imageSource.createPixelMap(); pixelmap.createAlphaPixelmap((err, alphaPixelMap) => {
if (pixelMap != undefined) { if (alphaPixelMap == undefined) {
pixelMap.createAlphaPixelmap(async (err, alphaPixelMap) => { console.info('Failed to obtain new pixel map.');
console.info('Failed to obtain new pixel map.'); } else {
}) console.info('Succeed in obtaining new pixel map.');
} else { }
console.info('Succeed in obtaining new pixel map.'); })
}
``` ```
### scale<sup>9+</sup> ### scale<sup>9+</sup>
...@@ -606,7 +633,7 @@ Scales this image based on the input width and height. This API uses an asynchro ...@@ -606,7 +633,7 @@ Scales this image based on the input width and height. This API uses an asynchro
```js ```js
async function () { async function () {
await pixelMap.scale(2.0, 1.0); await pixelmap.scale(2.0, 1.0);
} }
``` ```
...@@ -635,7 +662,7 @@ Scales this image based on the input width and height. This API uses a promise t ...@@ -635,7 +662,7 @@ Scales this image based on the input width and height. This API uses a promise t
```js ```js
async function () { async function () {
await pixelMap.scale(2.0, 1.0); await pixelmap.scale(2.0, 1.0);
} }
``` ```
...@@ -659,7 +686,7 @@ Translates this image based on the input coordinates. This API uses an asynchron ...@@ -659,7 +686,7 @@ Translates this image based on the input coordinates. This API uses an asynchron
```js ```js
async function () { async function () {
await pixelMap.translate(3.0, 1.0); await pixelmap.translate(3.0, 1.0);
} }
``` ```
...@@ -688,7 +715,7 @@ Translates this image based on the input coordinates. This API uses a promise to ...@@ -688,7 +715,7 @@ Translates this image based on the input coordinates. This API uses a promise to
```js ```js
async function () { async function () {
await pixelMap.translate(3.0, 1.0); await pixelmap.translate(3.0, 1.0);
} }
``` ```
...@@ -711,7 +738,7 @@ Rotates this image based on the input angle. This API uses an asynchronous callb ...@@ -711,7 +738,7 @@ Rotates this image based on the input angle. This API uses an asynchronous callb
```js ```js
async function () { async function () {
await pixelMap.rotate(90.0); await pixelmap.rotate(90.0);
} }
``` ```
...@@ -739,7 +766,7 @@ Rotates this image based on the input angle. This API uses a promise to return t ...@@ -739,7 +766,7 @@ Rotates this image based on the input angle. This API uses a promise to return t
```js ```js
async function () { async function () {
await pixelMap.rotate(90.0); await pixelmap.rotate(90.0);
} }
``` ```
...@@ -763,7 +790,7 @@ Flips this image horizontally or vertically, or both. This API uses an asynchron ...@@ -763,7 +790,7 @@ Flips this image horizontally or vertically, or both. This API uses an asynchron
```js ```js
async function () { async function () {
await pixelMap.flip(false, true); await pixelmap.flip(false, true);
} }
``` ```
...@@ -792,7 +819,7 @@ Flips this image horizontally or vertically, or both. This API uses a promise to ...@@ -792,7 +819,7 @@ Flips this image horizontally or vertically, or both. This API uses a promise to
```js ```js
async function () { async function () {
await pixelMap.flip(false, true); await pixelmap.flip(false, true);
} }
``` ```
...@@ -815,7 +842,7 @@ Crops this image based on the input size. This API uses an asynchronous callback ...@@ -815,7 +842,7 @@ Crops this image based on the input size. This API uses an asynchronous callback
```js ```js
async function () { async function () {
await pixelMap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); await pixelmap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } });
} }
``` ```
...@@ -843,7 +870,7 @@ Crops this image based on the input size. This API uses a promise to return the ...@@ -843,7 +870,7 @@ Crops this image based on the input size. This API uses a promise to return the
```js ```js
async function () { async function () {
await pixelMap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); await pixelmap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } });
} }
``` ```
...@@ -954,7 +981,8 @@ Creates an **ImageSource** instance based on the URI. ...@@ -954,7 +981,8 @@ Creates an **ImageSource** instance based on the URI.
**Example** **Example**
```js ```js
const imageSourceApi = image.createImageSource('/sdcard/test.jpg'); var sourceOptions = { sourceDensity: 120 };
let imageSource = image.createImageSource('test.png', sourceOptions);
``` ```
## image.createImageSource<sup>7+</sup> ## image.createImageSource<sup>7+</sup>
...@@ -1007,7 +1035,8 @@ Creates an **ImageSource** instance based on the file descriptor. ...@@ -1007,7 +1035,8 @@ Creates an **ImageSource** instance based on the file descriptor.
**Example** **Example**
```js ```js
const imageSourceApi = image.createImageSource(fd); var sourceOptions = { sourceDensity: 120 };
const imageSourceApi = image.createImageSource(0, sourceOptions);
``` ```
## image.createImageSource<sup>9+</sup> ## image.createImageSource<sup>9+</sup>
...@@ -1059,9 +1088,9 @@ const data = new ArrayBuffer(112); ...@@ -1059,9 +1088,9 @@ const data = new ArrayBuffer(112);
const imageSourceApi = image.createImageSource(data); const imageSourceApi = image.createImageSource(data);
``` ```
## image.CreateIncrementalSource<sup>9+</sup> ## image.createIncrementalSource<sup>9+</sup>
CreateIncrementalSource(buf: ArrayBuffer): ImageSource createIncrementalSource(buf: ArrayBuffer): ImageSource
Creates an **ImageSource** instance in incremental mode based on the buffers. Creates an **ImageSource** instance in incremental mode based on the buffers.
...@@ -1083,12 +1112,12 @@ Creates an **ImageSource** instance in incremental mode based on the buffers. ...@@ -1083,12 +1112,12 @@ Creates an **ImageSource** instance in incremental mode based on the buffers.
```js ```js
const buf = new ArrayBuffer(96); const buf = new ArrayBuffer(96);
const imageSourceApi = image.CreateIncrementalSource(buf); const imageSourceIncrementalSApi = image.createIncrementalSource(buf);
``` ```
## image.CreateIncrementalSource<sup>9+</sup> ## image.createIncrementalSource<sup>9+</sup>
CreateIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource createIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource
Creates an **ImageSource** instance in incremental mode based on the buffers. Creates an **ImageSource** instance in incremental mode based on the buffers.
...@@ -1111,7 +1140,7 @@ Creates an **ImageSource** instance in incremental mode based on the buffers. ...@@ -1111,7 +1140,7 @@ Creates an **ImageSource** instance in incremental mode based on the buffers.
```js ```js
const buf = new ArrayBuffer(96); const buf = new ArrayBuffer(96);
const imageSourceApi = image.CreateIncrementalSource(buf); const imageSourceIncrementalSApi = image.createIncrementalSource(buf);
``` ```
## ImageSource ## ImageSource
...@@ -1124,7 +1153,7 @@ Provides APIs to obtain image information. Before calling any API in **ImageSour ...@@ -1124,7 +1153,7 @@ Provides APIs to obtain image information. Before calling any API in **ImageSour
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ---------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | | ---------------- | -------------- | ---- | ---- | ------------------------------------------------------------ |
| supportedFormats | Array\<string> | Yes | No | Supported image formats, including png, jpeg, wbmp, bmp, gif, webp, and heif.| | supportedFormats | Array\<string> | Yes | No | Supported image formats, including PNG, JPEG, BMP, GIF, WebP, and RAW.|
### getImageInfo ### getImageInfo
...@@ -1282,7 +1311,7 @@ Obtains the value of a property in this image. This API uses an asynchronous cal ...@@ -1282,7 +1311,7 @@ Obtains the value of a property in this image. This API uses an asynchronous cal
**Example** **Example**
```js ```js
const property = new ArrayBuffer(400); let property = { index: 0, defaultValue: '9999' }
imageSourceApi.getImageProperty("BitsPerSample",property,(error,data) => { imageSourceApi.getImageProperty("BitsPerSample",property,(error,data) => {
if(error) { if(error) {
console.log('Failed to get the value of the specified attribute key of the image.'); console.log('Failed to get the value of the specified attribute key of the image.');
...@@ -1477,7 +1506,15 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses ...@@ -1477,7 +1506,15 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses
**Example** **Example**
```js ```js
const decodingOptions = new ArrayBuffer(400); let decodingOptions = {
sampleSize: 1,
editable: true,
desiredSize: { width: 1, height: 2 },
rotate: 10,
desiredPixelFormat: 3,
desiredRegion: { size: { height: 1, width: 2 }, x: 0, y: 0 },
index: 0
};
imageSourceApi.createPixelMap(decodingOptions, pixelmap => { imageSourceApi.createPixelMap(decodingOptions, pixelmap => {
console.log('Succeeded in creating pixelmap object.'); console.log('Succeeded in creating pixelmap object.');
}) })
...@@ -1551,7 +1588,7 @@ const imagePackerApi = image.createImagePacker(); ...@@ -1551,7 +1588,7 @@ const imagePackerApi = image.createImagePacker();
## ImagePacker ## ImagePacker
Provide APIs to pack images. Before calling any API in **ImagePacker**, you must use **createImagePacker** to create an **ImagePacker** instance. Provides APIs to pack images. Before calling any API in **ImagePacker**, you must use **createImagePacker** to create an **ImagePacker** instance. The image formats JPEG and WebP are supported.
### Attributes ### Attributes
...@@ -1581,7 +1618,6 @@ Packs an image. This API uses an asynchronous callback to return the result. ...@@ -1581,7 +1618,6 @@ Packs an image. This API uses an asynchronous callback to return the result.
```js ```js
let packOpts = { format:"image/jpeg", quality:98 }; let packOpts = { format:"image/jpeg", quality:98 };
const imageSourceApi = new ArrayBuffer(400);
imagePackerApi.packing(imageSourceApi, packOpts, data => {}) imagePackerApi.packing(imageSourceApi, packOpts, data => {})
``` ```
...@@ -1610,7 +1646,6 @@ Packs an image. This API uses a promise to return the result. ...@@ -1610,7 +1646,6 @@ Packs an image. This API uses a promise to return the result.
```js ```js
let packOpts = { format:"image/jpeg", quality:98 } let packOpts = { format:"image/jpeg", quality:98 }
const imageSourceApi = new ArrayBuffer(400);
imagePackerApi.packing(imageSourceApi, packOpts) imagePackerApi.packing(imageSourceApi, packOpts)
.then( data => { .then( data => {
console.log('packing succeeded.'); console.log('packing succeeded.');
...@@ -2112,7 +2147,7 @@ Describes area information in an image. ...@@ -2112,7 +2147,7 @@ Describes area information in an image.
| ------ | ------------------ | ---- | ---- | ------------------------------------------------------------ | | ------ | ------------------ | ---- | ---- | ------------------------------------------------------------ |
| pixels | ArrayBuffer | Yes | No | Pixels of the image. | | pixels | ArrayBuffer | Yes | No | Pixels of the image. |
| offset | number | Yes | No | Offset for data reading. | | offset | number | Yes | No | Offset for data reading. |
| stride | number | Yes | No | Number of bytes from one row of pixels in memory to the next row of pixels in memory. The value of **stride** must be greater than or equal to the value of **region.size.width** multiplied by 4. | | stride | number | Yes | No | Number of bytes from one row of pixels in memory to the next row of pixels in memory. The value of **stride** must be greater than or equal to the value of **region.size.width** multiplied by 4. |
| region | [Region](#region7) | Yes | No | Region to read or write. The width of the region to write plus the X coordinate cannot be greater than the width of the original image. The height of the region to write plus the Y coordinate cannot be greater than the height of the original image.| | region | [Region](#region7) | Yes | No | Region to read or write. The width of the region to write plus the X coordinate cannot be greater than the width of the original image. The height of the region to write plus the Y coordinate cannot be greater than the height of the original image.|
## ImageInfo ## ImageInfo
...@@ -2146,8 +2181,8 @@ Enumerates the pixel formats of images. ...@@ -2146,8 +2181,8 @@ Enumerates the pixel formats of images.
| ---------------------- | ------ | ----------------- | | ---------------------- | ------ | ----------------- |
| UNKNOWN | 0 | Unknown format. | | UNKNOWN | 0 | Unknown format. |
| RGB_565 | 2 | RGB_565. | | RGB_565 | 2 | RGB_565. |
| RGBA_8888 | 3 | RGBA_8888.| | RGBA_8888 | 3 | RGBA_8888. |
| BGRA_8888<sup>9+</sup> | 4 | BGRA_8888.| | BGRA_8888<sup>9+</sup> | 4 | BGRA_8888. |
## AlphaType<sup>9+</sup> ## AlphaType<sup>9+</sup>
...@@ -2159,8 +2194,8 @@ Enumerates the alpha types of images. ...@@ -2159,8 +2194,8 @@ Enumerates the alpha types of images.
| -------- | ------ | ----------------------- | | -------- | ------ | ----------------------- |
| UNKNOWN | 0 | Unknown alpha type. | | UNKNOWN | 0 | Unknown alpha type. |
| OPAQUE | 1 | There is no alpha or the image is opaque.| | OPAQUE | 1 | There is no alpha or the image is opaque.|
| PREMUL | 2 | Premultiplied alpha. | | PREMUL | 2 | Premultiplied alpha. |
| UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. | | UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. |
## ScaleMode<sup>9+</sup> ## ScaleMode<sup>9+</sup>
...@@ -2236,7 +2271,7 @@ Defines the option for image packing. ...@@ -2236,7 +2271,7 @@ Defines the option for image packing.
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | --------------------------------------------------- | | ------- | ------ | ---- | ---- | --------------------------------------------------- |
| format | string | Yes | Yes | Format of the packed image.<br>Currently, the following raw formats are supported: .jpg, .png, .gif, .bmp, and .webp. | | format | string | Yes | Yes | Format of the packed image.<br>Currently, the JPEG and WebP formats are supported. |
| quality | number | Yes | Yes | Quality of the output image during JPEG encoding. The value ranges from 1 to 100.| | quality | number | Yes | Yes | Quality of the output image during JPEG encoding. The value ranges from 1 to 100.|
## GetImagePropertyOptions<sup>7+</sup> ## GetImagePropertyOptions<sup>7+</sup>
......
...@@ -12,6 +12,10 @@ Compared with **[HashMap](js-apis-hashmap.md)**, which can also store KV pairs, ...@@ -12,6 +12,10 @@ Compared with **[HashMap](js-apis-hashmap.md)**, which can also store KV pairs,
**Recommended use case**: Use LightWeightMap when you need to store and access **KV pairs**. **Recommended use case**: Use LightWeightMap when you need to store and access **KV pairs**.
This topic uses the following to identify the use of generics:
- K: Key
- V: Value
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -92,10 +96,10 @@ Checks whether this container contains all elements of the specified **LightWeig ...@@ -92,10 +96,10 @@ Checks whether this container contains all elements of the specified **LightWeig
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let map = new LightWeightMap(); let map = new LightWeightMap();
map.set("sdfs", 356); map.set("sparrow", 356);
let result = lightWeightMap.hasAll(map); let result = lightWeightMap.hasAll(map);
``` ```
...@@ -125,9 +129,9 @@ Checks whether this container contains the specified key. ...@@ -125,9 +129,9 @@ Checks whether this container contains the specified key.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
let result = lightWeightMap.hasKey; let result = lightWeightMap.hasKey;
lightWeightMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightMap.hasKey("squirrel");
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
let result1 = lightWeightMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result1 = lightWeightMap.hasKey("squirrel");
``` ```
...@@ -156,7 +160,7 @@ Checks whether this container contains the specified value. ...@@ -156,7 +160,7 @@ Checks whether this container contains the specified value.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
let result = lightWeightMap.hasValue(123); let result = lightWeightMap.hasValue(123);
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
let result1 = lightWeightMap.hasValue(123); let result1 = lightWeightMap.hasValue(123);
``` ```
...@@ -207,9 +211,9 @@ Obtains the value of the specified key in this container. ...@@ -207,9 +211,9 @@ Obtains the value of the specified key in this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let result = lightWeightMap.get("sdfs"); let result = lightWeightMap.get("sparrow");
``` ```
...@@ -237,9 +241,9 @@ Obtains the index of the first occurrence of an element with the specified key i ...@@ -237,9 +241,9 @@ Obtains the index of the first occurrence of an element with the specified key i
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let result = lightWeightMap.getIndexOfKey("sdfs"); let result = lightWeightMap.getIndexOfKey("sparrow");
``` ```
...@@ -267,8 +271,8 @@ Obtains the index of the first occurrence of an element with the specified value ...@@ -267,8 +271,8 @@ Obtains the index of the first occurrence of an element with the specified value
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let result = lightWeightMap.getIndexOfValue(123); let result = lightWeightMap.getIndexOfValue(123);
``` ```
...@@ -297,8 +301,8 @@ Obtains the key of an element at the specified position in this container. ...@@ -297,8 +301,8 @@ Obtains the key of an element at the specified position in this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let result = lightWeightMap.getKeyAt(1); let result = lightWeightMap.getKeyAt(1);
``` ```
...@@ -321,8 +325,8 @@ Adds all elements in a **LightWeightMap** instance to this container. ...@@ -321,8 +325,8 @@ Adds all elements in a **LightWeightMap** instance to this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let map = new LightWeightMap(); let map = new LightWeightMap();
lightWeightMap.setAll(map); lightWeightMap.setAll(map);
``` ```
...@@ -352,7 +356,7 @@ Adds an element to this container. ...@@ -352,7 +356,7 @@ Adds an element to this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
let result = lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); let result = lightWeightMap.set("squirrel", 123);
``` ```
...@@ -380,9 +384,9 @@ Removes an element with the specified key from this container. ...@@ -380,9 +384,9 @@ Removes an element with the specified key from this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
lightWeightMap.remove("sdfs"); lightWeightMap.remove("sparrow");
``` ```
...@@ -410,8 +414,8 @@ Removes an element at the specified position from this container. ...@@ -410,8 +414,8 @@ Removes an element at the specified position from this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let result = lightWeightMap.removeAt(1); let result = lightWeightMap.removeAt(1);
``` ```
...@@ -441,8 +445,8 @@ Sets a value for an element at the specified position in this container. ...@@ -441,8 +445,8 @@ Sets a value for an element at the specified position in this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
lightWeightMap.setValueAt(1, 3546); lightWeightMap.setValueAt(1, 3546);
``` ```
...@@ -471,8 +475,8 @@ Obtains the value of an element at the specified position in this container. ...@@ -471,8 +475,8 @@ Obtains the value of an element at the specified position in this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let result = lightWeightMap.getValueAt(1); let result = lightWeightMap.getValueAt(1);
``` ```
...@@ -489,8 +493,8 @@ Clears this container and sets its length to **0**. ...@@ -489,8 +493,8 @@ Clears this container and sets its length to **0**.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
lightWeightMap.clear(); lightWeightMap.clear();
``` ```
...@@ -513,8 +517,8 @@ Obtains an iterator that contains all the keys in this container. ...@@ -513,8 +517,8 @@ Obtains an iterator that contains all the keys in this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let iter = lightWeightMap.keys(); let iter = lightWeightMap.keys();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -542,8 +546,8 @@ Obtains an iterator that contains all the values in this container. ...@@ -542,8 +546,8 @@ Obtains an iterator that contains all the values in this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let iter = lightWeightMap.values(); let iter = lightWeightMap.values();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -579,8 +583,8 @@ callbackfn ...@@ -579,8 +583,8 @@ callbackfn
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("sdfs", 123); lightWeightMap.set("sparrow", 123);
lightWeightMap.set("dfsghsf", 357); lightWeightMap.set("gull", 357);
lightWeightMap.forEach((value, key) => { lightWeightMap.forEach((value, key) => {
console.log("value:" + value, key); console.log("value:" + value, key);
}); });
...@@ -605,8 +609,8 @@ Obtains an iterator that contains all the elements in this container. ...@@ -605,8 +609,8 @@ Obtains an iterator that contains all the elements in this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let iter = lightWeightMap.entries(); let iter = lightWeightMap.entries();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -634,8 +638,8 @@ Concatenates the elements in this container into a string and returns the string ...@@ -634,8 +638,8 @@ Concatenates the elements in this container into a string and returns the string
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("A", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let iter = lightWeightMap.toString(); let iter = lightWeightMap.toString();
``` ```
...@@ -657,8 +661,8 @@ Obtains an iterator, each item of which is a JavaScript object. ...@@ -657,8 +661,8 @@ Obtains an iterator, each item of which is a JavaScript object.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
// Method 1: // Method 1:
for (let item of lightWeightMap) { for (let item of lightWeightMap) {
......
...@@ -14,6 +14,9 @@ Compared with **[HashSet](js-apis-hashset.md)**, which can also store values, ** ...@@ -14,6 +14,9 @@ Compared with **[HashSet](js-apis-hashset.md)**, which can also store values, **
**Recommended use case**: Use **LightWeightSet** when you need a set that has only unique elements or need to deduplicate a set. **Recommended use case**: Use **LightWeightSet** when you need a set that has only unique elements or need to deduplicate a set.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -93,7 +96,7 @@ Adds an element to this container. ...@@ -93,7 +96,7 @@ Adds an element to this container.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
let result = lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result = lightWeightSet.add("squirrel");
``` ```
...@@ -115,10 +118,10 @@ Adds all elements in a **LightWeightSet** instance to this container. ...@@ -115,10 +118,10 @@ Adds all elements in a **LightWeightSet** instance to this container.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let set = new LightWeightSet(); let set = new LightWeightSet();
set.add("sfage"); set.add("gull");
let result = lightWeightSet.addAll(set); let result = lightWeightSet.addAll(set);
``` ```
...@@ -147,10 +150,10 @@ Checks whether this container contains all elements of the specified **LightWeig ...@@ -147,10 +150,10 @@ Checks whether this container contains all elements of the specified **LightWeig
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let set = new LightWeightSet(); let set = new LightWeightSet();
set.add("sdfs"); set.add("sparrow");
let result = lightWeightSet.hasAll(set); let result = lightWeightSet.hasAll(set);
``` ```
...@@ -209,9 +212,9 @@ Checks whether this container contains objects of the same type as the specified ...@@ -209,9 +212,9 @@ Checks whether this container contains objects of the same type as the specified
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let obj = ["Ahfbrgrbgnutfodgorrogorgrogofdfdf", "sdfs"]; let obj = ["squirrel", "sparrow"];
let result = lightWeightSet.equal(obj); let result = lightWeightSet.equal(obj);
``` ```
...@@ -262,9 +265,9 @@ Obtains the position index of the element with the specified key in this contain ...@@ -262,9 +265,9 @@ Obtains the position index of the element with the specified key in this contain
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let result = lightWeightSet.getIndexOf("sdfs"); let result = lightWeightSet.getIndexOf("sparrow");
``` ```
...@@ -292,9 +295,9 @@ Removes an element of the specified key from this container. ...@@ -292,9 +295,9 @@ Removes an element of the specified key from this container.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let result = lightWeightSet.remove("sdfs"); let result = lightWeightSet.remove("sparrow");
``` ```
...@@ -322,8 +325,8 @@ Removes the element at the specified position from this container. ...@@ -322,8 +325,8 @@ Removes the element at the specified position from this container.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let result = lightWeightSet.removeAt(1); let result = lightWeightSet.removeAt(1);
``` ```
...@@ -352,8 +355,8 @@ Obtains the value of the element at the specified position in this container. ...@@ -352,8 +355,8 @@ Obtains the value of the element at the specified position in this container.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let result = lightWeightSet.getValueAt(1); let result = lightWeightSet.getValueAt(1);
``` ```
...@@ -370,8 +373,8 @@ Clears this container and sets its length to **0**. ...@@ -370,8 +373,8 @@ Clears this container and sets its length to **0**.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
lightWeightSet.clear(); lightWeightSet.clear();
``` ```
...@@ -394,8 +397,8 @@ Obtains a string that contains all elements in this container. ...@@ -394,8 +397,8 @@ Obtains a string that contains all elements in this container.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let result = lightWeightSet.toString(); let result = lightWeightSet.toString();
``` ```
...@@ -418,8 +421,8 @@ Obtains an array that contains all objects in this container. ...@@ -418,8 +421,8 @@ Obtains an array that contains all objects in this container.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let result = lightWeightSet.toArray(); let result = lightWeightSet.toArray();
``` ```
...@@ -442,8 +445,8 @@ Obtains an iterator that contains all the values in this container. ...@@ -442,8 +445,8 @@ Obtains an iterator that contains all the values in this container.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let iter = lightWeightSet.values(); let iter = lightWeightSet.values();
let index = 0; let index = 0;
while(index < lightWeightSet.length) { while(index < lightWeightSet.length) {
...@@ -479,8 +482,8 @@ callbackfn ...@@ -479,8 +482,8 @@ callbackfn
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
lightWeightSet.add("dfsghsf"); lightWeightSet.add("gull");
lightWeightSet.forEach((value, key) => { lightWeightSet.forEach((value, key) => {
console.log("value:" + value, key); console.log("value:" + value, key);
}); });
...@@ -505,8 +508,8 @@ Obtains an iterator that contains all the elements in this container. ...@@ -505,8 +508,8 @@ Obtains an iterator that contains all the elements in this container.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let iter = lightWeightSet.entries(); let iter = lightWeightSet.entries();
let index = 0; let index = 0;
while(index < lightWeightSet.length) { while(index < lightWeightSet.length) {
...@@ -534,8 +537,8 @@ Obtains an iterator, each item of which is a JavaScript object. ...@@ -534,8 +537,8 @@ Obtains an iterator, each item of which is a JavaScript object.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
// Method 1: // Method 1:
for (let item of lightWeightSet) { for (let item of lightWeightSet) {
......
...@@ -12,6 +12,9 @@ Unlike **[List](js-apis-list.md)**, which is a singly linked list, **LinkedList* ...@@ -12,6 +12,9 @@ Unlike **[List](js-apis-list.md)**, which is a singly linked list, **LinkedList*
**Recommended use case**: Use **LinkedList** for frequent insertion and removal operations. **Recommended use case**: Use **LinkedList** for frequent insertion and removal operations.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -76,7 +79,7 @@ let result = linkedList.add("a"); ...@@ -76,7 +79,7 @@ let result = linkedList.add("a");
let result1 = linkedList.add(1); let result1 = linkedList.add(1);
let b = [1, 2, 3]; let b = [1, 2, 3];
linkedList.add(b); linkedList.add(b);
let c = {name : "lala", age : "13"}; let c = {name : "Dylon", age : "13"};
let result3 = linkedList.add(false); let result3 = linkedList.add(false);
``` ```
...@@ -102,7 +105,7 @@ linkedList.addFirst("a"); ...@@ -102,7 +105,7 @@ linkedList.addFirst("a");
linkedList.addFirst(1); linkedList.addFirst(1);
let b = [1, 2, 3]; let b = [1, 2, 3];
linkedList.addFirst(b); linkedList.addFirst(b);
let c = {name : "lala", age : "13"}; let c = {name : "Dylon", age : "13"};
linkedList.addFirst(false); linkedList.addFirst(false);
``` ```
...@@ -154,9 +157,9 @@ Checks whether this container has the specified element. ...@@ -154,9 +157,9 @@ Checks whether this container has the specified element.
```ts ```ts
let linkedList = new LinkedList(); let linkedList = new LinkedList();
let result1 = linkedList.has("Ahfbrgrbgnutfodgorrogorg"); let result1 = linkedList.has("squirrel");
linkedList.add("Ahfbrgrbgnutfodgorrogorg"); linkedList.add("squirrel");
let result = linkedList.has("Ahfbrgrbgnutfodgorrogorg"); let result = linkedList.has("squirrel");
``` ```
### get ### get
......
...@@ -10,6 +10,9 @@ Unlike [LinkedList](js-apis-linkedlist.md), which is a doubly linked list, **Lis ...@@ -10,6 +10,9 @@ Unlike [LinkedList](js-apis-linkedlist.md), which is a doubly linked list, **Lis
**Recommended use case**: Use **List** for frequent insertion and removal operations. **Recommended use case**: Use **List** for frequent insertion and removal operations.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -72,7 +75,7 @@ let result = list.add("a"); ...@@ -72,7 +75,7 @@ let result = list.add("a");
let result1 = list.add(1); let result1 = list.add(1);
let b = [1, 2, 3]; let b = [1, 2, 3];
list.add(b); list.add(b);
let c = {name : "lala", age : "13"}; let c = {name : "Dylon", age : "13"};
let result3 = list.add(false); let result3 = list.add(false);
``` ```
...@@ -124,9 +127,9 @@ Checks whether this container has the specified element. ...@@ -124,9 +127,9 @@ Checks whether this container has the specified element.
```ts ```ts
let list = new List(); let list = new List();
let result = list.has("Ahfbrgrbgnutfodgorrogorg"); let result = list.has("squirrel");
list.add("Ahfbrgrbgnutfodgorrogorg"); list.add("squirrel");
let result1 = list.has("Ahfbrgrbgnutfodgorrogorg"); let result1 = list.has("squirrel");
``` ```
### get ### get
...@@ -181,7 +184,7 @@ Obtains the index of the last occurrence of the specified element in this contai ...@@ -181,7 +184,7 @@ Obtains the index of the last occurrence of the specified element in this contai
| Value Type | Description| | Value Type | Description|
| -------- | -------- | | -------- | -------- |
| number | Returns the position index if obtained; returns **-1** otherwise.| | number | Returns the index if obtained; returns **-1** otherwise.|
**Example** **Example**
...@@ -265,7 +268,7 @@ obj1.add(2); ...@@ -265,7 +268,7 @@ obj1.add(2);
obj1.add(4); obj1.add(4);
obj1.add(5); obj1.add(5);
list.equal(obj1); list.equal(obj1);
let obj2 = {name : "lala", age : "13"}; let obj2 = {name : "Dylon", age : "13"};
let result = list.equal(obj2); let result = list.equal(obj2);
``` ```
......
...@@ -53,7 +53,7 @@ Creates a **VideoPlayer** instance. This API uses an asynchronous callback to re ...@@ -53,7 +53,7 @@ Creates a **VideoPlayer** instance. This API uses an asynchronous callback to re
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------- | ---- | ------------------------------ | | -------- | ------------------------------------------- | ---- | ------------------------------ |
| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | Yes | Callback used to return the **VideoPlayer** instance created.| | callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | Yes | Callback used to return the **VideoPlayer** instance, which can be used to manage and play video media.|
**Example** **Example**
...@@ -82,7 +82,7 @@ Creates a **VideoPlayer** instance. This API uses a promise to return the result ...@@ -82,7 +82,7 @@ Creates a **VideoPlayer** instance. This API uses a promise to return the result
| Type | Description | | Type | Description |
| ------------------------------------- | ----------------------------------- | | ------------------------------------- | ----------------------------------- |
| Promise<[VideoPlayer](#videoplayer8)> | Promise used to return the **VideoPlayer** instance created.| | Promise<[VideoPlayer](#videoplayer8)> | Promise used to return the **VideoPlayer** instance, which can be used to manage and play video media.|
**Example** **Example**
...@@ -135,7 +135,7 @@ Only one **AudioRecorder** instance can be created per device. ...@@ -135,7 +135,7 @@ Only one **AudioRecorder** instance can be created per device.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------- | ---- | ------------------------------ | | -------- | ----------------------------------------------- | ---- | ------------------------------ |
| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | Yes | Callback used to return the **VideoRecorder** instance created.| | callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | Yes | Callback used to return the **VideoRecorder** instance, which can be used to record video media.|
**Example** **Example**
...@@ -165,7 +165,7 @@ Only one **AudioRecorder** instance can be created per device. ...@@ -165,7 +165,7 @@ Only one **AudioRecorder** instance can be created per device.
| Type | Description | | Type | Description |
| ----------------------------------------- | ----------------------------------- | | ----------------------------------------- | ----------------------------------- |
| Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the **VideoRecorder** instance created.| | Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the **VideoRecorder** instance, which can be used to record video media.|
**Example** **Example**
...@@ -275,15 +275,15 @@ For details about the audio playback demo, see [Audio Playback Development](../. ...@@ -275,15 +275,15 @@ For details about the audio playback demo, see [Audio Playback Development](../.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer **System capability**: SystemCapability.Multimedia.Media.AudioPlayer
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ------------------------------- | ----------------------------------- | ---- | ---- | ------------------------------------------------------------ | | ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
| src | string | Yes | Yes | Audio file URI. The mainstream audio formats (M4A, AAC, MPEG-3, OGG, and WAV) are supported.<br>**Examples of supported URI schemes**:<br>1. FD: fd://xx<br>![](figures/en-us_image_url.png)<br>2. HTTP: http://xx<br>3. HTTPS: https://xx<br>4. HLS: http://xx or https://xx<br>**Required permissions**: ohos.permission.INTERNET| | src | string | Yes | Yes | Audio file URI. The mainstream audio formats (M4A, AAC, MPEG-3, OGG, and WAV) are supported.<br>**Examples of supported URI schemes**:<br>1. FD: fd://xx<br>![](figures/en-us_image_url.png)<br>2. HTTP: http://xx<br>3. HTTPS: https://xx<br>4. HLS: http://xx or https://xx<br>**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.INTERNET|
| fdSrc<sup>9+</sup> | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | Description of the audio file. This attribute is required when audio resources of an application are continuously stored in a file.<br>**Example:**<br>Assume that a music file that stores continuous music resources consists of the following:<br>Music 1 (address offset: 0, byte length: 100)<br>Music 2 (address offset: 101; byte length: 50)<br>Music 3 (address offset: 151, byte length: 150)<br>1. To play music 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }<br>2. To play music 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }<br>3. To play music 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }<br>If the file is an independent music file, use **src=fd://xx**.<br>| | fdSrc<sup>9+</sup> | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | Description of the audio file. This attribute is required when audio resources of an application are continuously stored in a file.<br>**Example:**<br>Assume that a music file that stores continuous music resources consists of the following:<br>Music 1 (address offset: 0, byte length: 100)<br>Music 2 (address offset: 101; byte length: 50)<br>Music 3 (address offset: 151, byte length: 150)<br>1. To play music 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }<br>2. To play music 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }<br>3. To play music 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }<br>If the file is an independent music file, use **src=fd://xx**.<br>|
| loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. | | loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. |
| audioInterruptMode<sup>9+</sup> | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. | | audioInterruptMode<sup>9+</sup> | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. |
| currentTime | number | Yes | No | Current audio playback position, in ms. | | currentTime | number | Yes | No | Current audio playback position, in ms. |
| duration | number | Yes | No | Audio duration, in ms. | | duration | number | Yes | No | Audio duration, in ms. |
| state | [AudioState](#audiostate) | Yes | No | Audio playback state. This state cannot be used as the condition for triggering the call of **play()**, **pause()**, or **stop()**.| | state | [AudioState](#audiostate) | Yes | No | Audio playback state. This state cannot be used as the condition for triggering the call of **play()**, **pause()**, or **stop()**.|
### play<a name=audioplayer_play></a> ### play<a name=audioplayer_play></a>
play(): void play(): void
...@@ -442,7 +442,7 @@ function printfDescription(obj) { ...@@ -442,7 +442,7 @@ function printfDescription(obj) {
} }
} }
audioPlayer.getTrackDescription((error, ) => { 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]);
...@@ -680,7 +680,7 @@ For details about the video playback demo, see [Video Playback Development](../. ...@@ -680,7 +680,7 @@ For details about the video playback demo, see [Video Playback Development](../.
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ------------------------ | ---------------------------------- | ---- | ---- | ------------------------------------------------------------ | | ------------------------ | ---------------------------------- | ---- | ---- | ------------------------------------------------------------ |
| url<sup>8+</sup> | string | Yes | Yes | Video media URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.<br>**Example of supported URIs**:<br>1. FD: fd://xx<br>![](figures/en-us_image_url.png)<br>2. HTTP: http://xx<br>3. HTTPS: https://xx<br>4. HLS: http://xx or https://xx<br>**Required permissions**: ohos.permission.INTERNET| | url<sup>8+</sup> | string | Yes | Yes | Video media URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.<br>**Example of supported URIs**:<br>1. FD: fd://xx<br>![](figures/en-us_image_url.png)<br>2. HTTP: http://xx<br>3. HTTPS: https://xx<br>4. HLS: http://xx or https://xx<br>|
| fdSrc<sup>9+</sup> | [AVFileDescriptor](#avfiledescriptor9) | Yes| Yes| Description of a video file. This attribute is required when video resources of an application are continuously stored in a file.<br>**Example:**<br>Assume that a music file that stores continuous music resources consists of the following:<br>Video 1 (address offset: 0, byte length: 100)<br>Video 2 (address offset: 101; byte length: 50)<br>Video 3 (address offset: 151, byte length: 150)<br>1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }<br>2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }<br>3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }<br>To play an independent video file, use **src=fd://xx**.<br>| | fdSrc<sup>9+</sup> | [AVFileDescriptor](#avfiledescriptor9) | Yes| Yes| Description of a video file. This attribute is required when video resources of an application are continuously stored in a file.<br>**Example:**<br>Assume that a music file that stores continuous music resources consists of the following:<br>Video 1 (address offset: 0, byte length: 100)<br>Video 2 (address offset: 101; byte length: 50)<br>Video 3 (address offset: 151, byte length: 150)<br>1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }<br>2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }<br>3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }<br>To play an independent video file, use **src=fd://xx**.<br>|
| loop<sup>8+</sup> | boolean | Yes | Yes | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite. | | loop<sup>8+</sup> | boolean | Yes | Yes | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite. |
| videoScaleType<sup>9+</sup> | [VideoScaleType](#videoscaletype9) | Yes | Yes | Video scale type. | | videoScaleType<sup>9+</sup> | [VideoScaleType](#videoscaletype9) | Yes | Yes | Video scale type. |
...@@ -1795,7 +1795,7 @@ Subscribes to the audio recording events. ...@@ -1795,7 +1795,7 @@ Subscribes to the audio recording events.
```js ```js
let audioRecorder = media.createAudioRecorder(); // Create an AudioRecorder instance. let audioRecorder = media.createAudioRecorder(); // Create an AudioRecorder instance.
let audioRecorderConfig = { let audioRecorderConfig = {
audioEncoder : media.AudioEncoder.AAC_LC, , audioEncoder : media.AudioEncoder.AAC_LC,
audioEncodeBitRate : 22050, audioEncodeBitRate : 22050,
audioSampleRate : 22050, audioSampleRate : 22050,
numberOfChannels : 2, numberOfChannels : 2,
...@@ -1850,7 +1850,7 @@ Subscribes to audio recording error events. After an error event is reported, yo ...@@ -1850,7 +1850,7 @@ Subscribes to audio recording error events. After an error event is reported, yo
```js ```js
let audioRecorderConfig = { let audioRecorderConfig = {
audioEncoder : media.AudioEncoder.AAC_LC, , audioEncoder : media.AudioEncoder.AAC_LC,
audioEncodeBitRate : 22050, audioEncodeBitRate : 22050,
audioSampleRate : 22050, audioSampleRate : 22050,
numberOfChannels : 2, numberOfChannels : 2,
...@@ -1974,29 +1974,13 @@ let videoConfig = { ...@@ -1974,29 +1974,13 @@ let videoConfig = {
} }
// asyncallback // asyncallback
let videoRecorder = null; videoRecorder.prepare(videoConfig, (err) => {
let events = require('events'); if (err == null) {
let eventEmitter = new events.EventEmitter(); console.info('prepare success');
eventEmitter.on('prepare', () => {
videoRecorder.prepare(videoConfig, (err) => {
if (err == null) {
console.info('prepare success');
} else {
console.info('prepare failed and error is ' + err.message);
}
});
});
media.createVideoRecorder((err, recorder) => {
if (err == null && recorder != null) {
videoRecorder = recorder;
console.info('createVideoRecorder success');
eventEmitter.emit('prepare'); // Trigger the 'prepare' event.
} else { } else {
console.info('createVideoRecorder failed and error is ' + err.message); console.info('prepare failed and error is ' + err.message);
} }
}); })
``` ```
### prepare<sup>9+</sup><a name=videorecorder_prepare2></a> ### prepare<sup>9+</sup><a name=videorecorder_prepare2></a>
...@@ -2047,21 +2031,10 @@ let videoConfig = { ...@@ -2047,21 +2031,10 @@ let videoConfig = {
} }
// promise // promise
let videoRecorder = null; videoRecorder.prepare(videoConfig).then(() => {
media.createVideoRecorder().then((recorder) => { console.info('prepare success');
if (recorder != null) {
videoRecorder = recorder;
console.info('createVideoRecorder success');
videoRecorder.prepare(videoConfig).then(() => {
console.info('prepare success');
}).catch((err) => {
console.info('prepare failed and catch error is ' + err.message);
});
} else {
console.info('createVideoRecorder failed');
}
}).catch((err) => { }).catch((err) => {
console.info('catch err error message is ' + err.message); console.info('prepare failed and catch error is ' + err.message);
}); });
``` ```
...@@ -2475,11 +2448,10 @@ Subscribes to video recording error events. After an error event is reported, yo ...@@ -2475,11 +2448,10 @@ Subscribes to video recording error events. After an error event is reported, yo
**Example** **Example**
```js ```js
// This event is reported when an error occurs during the retrieval of videoRecordState.
videoRecorder.on('error', (error) => { // Set the 'error' event callback. videoRecorder.on('error', (error) => { // Set the 'error' event callback.
console.info(`audio error called, error: ${error}`); console.info(`audio error called, error: ${error}`);
} })
// This event is reported when an error occurs during the retrieval of videoRecordState.
});
``` ```
## VideoRecordState<sup>9+</sup> ## VideoRecordState<sup>9+</sup>
......
...@@ -2,10 +2,10 @@ ...@@ -2,10 +2,10 @@
> **NOTE** > **NOTE**
> >
> This component is supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
``` ```js
import mediaLibrary from '@ohos.multimedia.mediaLibrary'; import mediaLibrary from '@ohos.multimedia.mediaLibrary';
``` ```
...@@ -33,17 +33,18 @@ This API can be used only in the stage model. ...@@ -33,17 +33,18 @@ This API can be used only in the stage model.
**Example (from API version 9)** **Example (from API version 9)**
``` ```ts
var media = mediaLibrary.getMediaLibrary(this.context); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
``` ```
**Example (API version 8)** **Example (API version 8)**
``` ```js
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext() let context = featureAbility.getContext();
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
``` ```
## mediaLibrary.getMediaLibrary ## mediaLibrary.getMediaLibrary
...@@ -68,7 +69,7 @@ This API can be used only in the FA model. ...@@ -68,7 +69,7 @@ This API can be used only in the FA model.
**Example** **Example**
```js ```js
var media = mediaLibrary.getMediaLibrary(); let media = mediaLibrary.getMediaLibrary();
``` ```
## MediaLibrary ## MediaLibrary
...@@ -93,24 +94,45 @@ Obtains file assets (also called files). This API uses an asynchronous callback ...@@ -93,24 +94,45 @@ Obtains file assets (also called files). This API uses an asynchronous callback
**Example** **Example**
``` ```js
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE let imageType = mediaLibrary.MediaType.IMAGE;
let imagesfetchOp = { let imagesFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
}; };
media.getFileAssets(imagesfetchOp, (error, fetchFileResult) => { media.getFileAssets(imagesFetchOp, (error, fetchFileResult) => {
if (fetchFileResult != undefined) { if (fetchFileResult == undefined) {
console.info('mediaLibraryTest : ASSET_CALLBACK fetchFileResult success'); console.error('Failed to get fetchFileResult: ' + error);
fetchFileResult.getAllObject((err, fileAssetList) => { return;
if (fileAssetList != undefined) {
fileAssetList.forEach(function(getAllObjectInfo){
console.info("getAllObjectInfo.displayName :" + getAllObjectInfo.displayName);
});
}
});
} }
const count = fetchFileResult.getCount();
if (count < 0) {
console.error('Failed to get count from fetchFileResult: count: ' + count);
return;
}
if (count == 0) {
console.info('The count of fetchFileResult is zero');
return;
}
console.info('Get fetchFileResult success, count: ' + count);
fetchFileResult.getFirstObject((err, fileAsset) => {
if (fileAsset == undefined) {
console.error('Failed to get first object: ' + err);
return;
}
console.log('fileAsset.displayName ' + ': ' + fileAsset.displayName);
for (let i = 1; i < count; i++) {
fetchFileResult.getNextObject((err, fileAsset) => {
if (fileAsset == undefined) {
console.error('Failed to get next object: ' + err);
return;
}
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
})
}
});
}); });
``` ```
### getFileAssets<sup>7+</sup> ### getFileAssets<sup>7+</sup>
...@@ -137,17 +159,38 @@ Obtains file assets. This API uses a promise to return the result. ...@@ -137,17 +159,38 @@ Obtains file assets. This API uses a promise to return the result.
**Example** **Example**
``` ```js
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE let imageType = mediaLibrary.MediaType.IMAGE;
let imagesfetchOp = { let imagesFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
}; };
media.getFileAssets(imagesfetchOp).then(function(fetchFileResult){ media.getFileAssets(imagesFetchOp).then(function(fetchFileResult) {
console.info("getFileAssets successfully: image number is "+ fetchFileResult.getCount()); const count = fetchFileResult.getCount();
if (count < 0) {
console.error('Failed to get count from fetchFileResult: count: ' + count);
return;
}
if (count == 0) {
console.info('The count of fetchFileResult is zero');
return;
}
console.info('Get fetchFileResult success, count: ' + count);
fetchFileResult.getFirstObject().then(function(fileAsset) {
console.log('fileAsset.displayName ' + ': ' + fileAsset.displayName);
for (let i = 1; i < count; i++) {
fetchFileResult.getNextObject().then(function(fileAsset) {
console.log('fileAsset.displayName ' + ': ' + fileAsset.displayName);
}).catch(function(err) {
console.error('Failed to get next object: ' + err);
})
}
}).catch(function(err) {
console.error('Failed to get first object: ' + err);
});
}).catch(function(err){ }).catch(function(err){
console.info("getFileAssets failed with error:"+ err); console.error("Failed to get file assets: " + err);
}); });
``` ```
...@@ -168,7 +211,7 @@ Subscribes to the media library changes. This API uses an asynchronous callback ...@@ -168,7 +211,7 @@ Subscribes to the media library changes. This API uses an asynchronous callback
**Example** **Example**
``` ```js
media.on('imageChange', () => { media.on('imageChange', () => {
// image file had changed, do something // image file had changed, do something
}) })
...@@ -190,13 +233,13 @@ Unsubscribes from the media library changes. This API uses an asynchronous callb ...@@ -190,13 +233,13 @@ Unsubscribes from the media library changes. This API uses an asynchronous callb
**Example** **Example**
``` ```js
media.off('imageChange', () => { media.off('imageChange', () => {
// stop listening success // stop listening success
}) })
``` ```
### createAsset <sup>8+</sup> ### createAsset<sup>8+</sup>
createAsset(mediaType: MediaType, displayName: string, relativePath: string, callback: AsyncCallback&lt;FileAsset&gt;): void createAsset(mediaType: MediaType, displayName: string, relativePath: string, callback: AsyncCallback&lt;FileAsset&gt;): void
...@@ -217,7 +260,7 @@ Creates a media asset. This API uses an asynchronous callback to return the resu ...@@ -217,7 +260,7 @@ Creates a media asset. This API uses an asynchronous callback to return the resu
**Example** **Example**
``` ```js
async function example() { async function example() {
// Create an image file in callback mode. // Create an image file in callback mode.
let mediaType = mediaLibrary.MediaType.IMAGE; let mediaType = mediaLibrary.MediaType.IMAGE;
...@@ -259,7 +302,7 @@ Creates a media asset. This API uses a promise to return the result. ...@@ -259,7 +302,7 @@ Creates a media asset. This API uses a promise to return the result.
**Example** **Example**
``` ```js
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
media.getPublicDirectory(DIR_CAMERA).then(function(dicResult){ media.getPublicDirectory(DIR_CAMERA).then(function(dicResult){
console.info("getPublicDirectory successfully:"+ JSON.stringify(dicResult)); console.info("getPublicDirectory successfully:"+ JSON.stringify(dicResult));
...@@ -268,6 +311,101 @@ media.getPublicDirectory(DIR_CAMERA).then(function(dicResult){ ...@@ -268,6 +311,101 @@ media.getPublicDirectory(DIR_CAMERA).then(function(dicResult){
}); });
``` ```
### deleteAsset<sup>8+</sup>
deleteAsset(uri: string): Promise\<void>
Deletes a file asset. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------- | ---- | --------------- |
| uri | string | Yes | URI of the file asset to delete.|
**Return value**
| Type | Description |
| ------------------- | -------------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE;
let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) {
console.error('asset not exist')
return
}
media.deleteAsset(asset.uri).then(() => {
console.info("deleteAsset successfully");
}).catch((err) => {
console.info("deleteAsset failed with error:"+ err);
});
}
```
### deleteAsset<sup>8+</sup>
deleteAsset(uri: string, callback: AsyncCallback\<void>): void
Deletes a file asset. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------- | ---- | --------------- |
| uri | string | Yes | URI of the file asset to delete.|
|callback |AsyncCallback\<void>| Yes |Callback used to return the result.|
**Example**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE;
let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) {
console.error('asset not exist')
return
}
media.deleteAsset(asset.uri, (err) => {
if (err != undefined) {
console.info("deleteAsset successfully");
} else {
console.info("deleteAsset failed with error:"+ err);
}
});
}
```
### getPublicDirectory<sup>8+</sup> ### getPublicDirectory<sup>8+</sup>
getPublicDirectory(type: DirectoryType, callback: AsyncCallback&lt;string&gt;): void getPublicDirectory(type: DirectoryType, callback: AsyncCallback&lt;string&gt;): void
...@@ -285,7 +423,7 @@ Obtains a public directory. This API uses an asynchronous callback to return the ...@@ -285,7 +423,7 @@ Obtains a public directory. This API uses an asynchronous callback to return the
**Example** **Example**
``` ```js
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
media.getPublicDirectory(DIR_CAMERA, (err, dicResult) => { media.getPublicDirectory(DIR_CAMERA, (err, dicResult) => {
if (dicResult == 'Camera/') { if (dicResult == 'Camera/') {
...@@ -318,7 +456,7 @@ Obtains a public directory. This API uses a promise to return the result. ...@@ -318,7 +456,7 @@ Obtains a public directory. This API uses a promise to return the result.
**Example** **Example**
``` ```js
async function example() { async function example() {
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
const dicResult = await media.getPublicDirectory(DIR_CAMERA); const dicResult = await media.getPublicDirectory(DIR_CAMERA);
...@@ -349,7 +487,7 @@ Obtains the albums. This API uses an asynchronous callback to return the result. ...@@ -349,7 +487,7 @@ Obtains the albums. This API uses an asynchronous callback to return the result.
**Example** **Example**
``` ```js
let AlbumNoArgsfetchOp = { let AlbumNoArgsfetchOp = {
selections: '', selections: '',
selectionArgs: [], selectionArgs: [],
...@@ -389,7 +527,7 @@ Obtains the albums. This API uses a promise to return the result. ...@@ -389,7 +527,7 @@ Obtains the albums. This API uses a promise to return the result.
**Example** **Example**
``` ```js
let AlbumNoArgsfetchOp = { let AlbumNoArgsfetchOp = {
selections: '', selections: '',
selectionArgs: [], selectionArgs: [],
...@@ -418,7 +556,7 @@ Call this API when you no longer need to use the APIs in the **MediaLibrary** in ...@@ -418,7 +556,7 @@ Call this API when you no longer need to use the APIs in the **MediaLibrary** in
**Example** **Example**
``` ```js
var media = mediaLibrary.getMediaLibrary(context); var media = mediaLibrary.getMediaLibrary(context);
media.release((err) => { media.release((err) => {
// do something // do something
...@@ -442,7 +580,7 @@ Call this API when you no longer need to use the APIs in the **MediaLibrary** in ...@@ -442,7 +580,7 @@ Call this API when you no longer need to use the APIs in the **MediaLibrary** in
**Example** **Example**
``` ```js
media.release() media.release()
``` ```
...@@ -467,7 +605,7 @@ Stores a media asset. This API uses an asynchronous callback to return the URI t ...@@ -467,7 +605,7 @@ Stores a media asset. This API uses an asynchronous callback to return the URI t
**Example** **Example**
``` ```js
let option = { let option = {
src : "/data/storage/el2/base/haps/entry/image.png", src : "/data/storage/el2/base/haps/entry/image.png",
mimeType : "image/*", mimeType : "image/*",
...@@ -481,7 +619,7 @@ mediaLibrary.getMediaLibrary().storeMediaAsset(option, (err, value) => { ...@@ -481,7 +619,7 @@ mediaLibrary.getMediaLibrary().storeMediaAsset(option, (err, value) => {
console.log("Media asset stored."); console.log("Media asset stored.");
// Obtain the URI that stores the media asset. // Obtain the URI that stores the media asset.
}); });
``` ```
### storeMediaAsset<sup>(deprecated)</sup> ### storeMediaAsset<sup>(deprecated)</sup>
...@@ -510,7 +648,7 @@ Stores a media asset. This API uses a promise to return the URI that stores the ...@@ -510,7 +648,7 @@ Stores a media asset. This API uses a promise to return the URI that stores the
**Example** **Example**
``` ```js
let option = { let option = {
src : "/data/storage/el2/base/haps/entry/image.png", src : "/data/storage/el2/base/haps/entry/image.png",
mimeType : "image/*", mimeType : "image/*",
...@@ -522,7 +660,7 @@ mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => { ...@@ -522,7 +660,7 @@ mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => {
}).catch((err) => { }).catch((err) => {
console.log("An error occurred when storing the media assets."); console.log("An error occurred when storing the media assets.");
}); });
``` ```
### startImagePreview<sup>(deprecated)</sup> ### startImagePreview<sup>(deprecated)</sup>
...@@ -547,7 +685,7 @@ Starts image preview, with the first image to preview specified. This API can be ...@@ -547,7 +685,7 @@ Starts image preview, with the first image to preview specified. This API can be
**Example** **Example**
``` ```js
let images = [ let images = [
"dataability:///media/xxxx/2", "dataability:///media/xxxx/2",
"dataability:///media/xxxx/3" "dataability:///media/xxxx/3"
...@@ -566,7 +704,7 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, index, (err) => { ...@@ -566,7 +704,7 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, index, (err) => {
} }
console.log("Succeeded in previewing the images."); console.log("Succeeded in previewing the images.");
}); });
``` ```
### startImagePreview<sup>(deprecated)</sup> ### startImagePreview<sup>(deprecated)</sup>
...@@ -590,7 +728,7 @@ Starts image preview. This API can be used to preview local images whose URIs st ...@@ -590,7 +728,7 @@ Starts image preview. This API can be used to preview local images whose URIs st
**Example** **Example**
``` ```js
let images = [ let images = [
"dataability:///media/xxxx/2", "dataability:///media/xxxx/2",
"dataability:///media/xxxx/3" "dataability:///media/xxxx/3"
...@@ -608,7 +746,7 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, (err) => { ...@@ -608,7 +746,7 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, (err) => {
} }
console.log("Succeeded in previewing the images."); console.log("Succeeded in previewing the images.");
}); });
``` ```
### startImagePreview<sup>(deprecated)</sup> ### startImagePreview<sup>(deprecated)</sup>
...@@ -638,7 +776,7 @@ Starts image preview, with the first image to preview specified. This API can be ...@@ -638,7 +776,7 @@ Starts image preview, with the first image to preview specified. This API can be
**Example** **Example**
``` ```js
let images = [ let images = [
"dataability:///media/xxxx/2", "dataability:///media/xxxx/2",
"dataability:///media/xxxx/3" "dataability:///media/xxxx/3"
...@@ -655,7 +793,7 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, index).then(() => { ...@@ -655,7 +793,7 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, index).then(() => {
}).catch((err) => { }).catch((err) => {
console.log("An error occurred when previewing the images."); console.log("An error occurred when previewing the images.");
}); });
``` ```
### startMediaSelect<sup>(deprecated)</sup> ### startMediaSelect<sup>(deprecated)</sup>
...@@ -674,13 +812,13 @@ Starts media selection. This API uses an asynchronous callback to return the lis ...@@ -674,13 +812,13 @@ Starts media selection. This API uses an asynchronous callback to return the lis
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------------------------------------ | | -------- | ---------------------------------------- | ---- | ------------------------------------ |
| option | [MediaSelectOption](#mediaselectoption) | Yes | Media selection option. | | option | [MediaSelectOption](#mediaselectoptiondeprecated) | Yes | Media selection option. |
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback used to return the list of URIs (starting with **dataability://**) that store the selected media assets.| | callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback used to return the list of URIs (starting with **dataability://**) that store the selected media assets.|
**Example** **Example**
``` ```js
let option = { let option : mediaLibrary.MediaSelectOption = {
type : "media", type : "media",
count : 2 count : 2
}; };
...@@ -692,7 +830,7 @@ mediaLibrary.getMediaLibrary().startMediaSelect(option, (err, value) => { ...@@ -692,7 +830,7 @@ mediaLibrary.getMediaLibrary().startMediaSelect(option, (err, value) => {
console.log("Media asset selected."); console.log("Media asset selected.");
// Obtain the media selection value. // Obtain the media selection value.
}); });
``` ```
### startMediaSelect<sup>(deprecated)</sup> ### startMediaSelect<sup>(deprecated)</sup>
...@@ -711,7 +849,7 @@ Starts media selection. This API uses a promise to return the list of URIs that ...@@ -711,7 +849,7 @@ Starts media selection. This API uses a promise to return the list of URIs that
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | --------------------------------------- | ---- | ------- | | ------ | --------------------------------------- | ---- | ------- |
| option | [MediaSelectOption](#mediaselectoption) | Yes | Media selection option.| | option | [MediaSelectOption](#mediaselectoptiondeprecated) | Yes | Media selection option.|
**Return value** **Return value**
...@@ -721,8 +859,8 @@ Starts media selection. This API uses a promise to return the list of URIs that ...@@ -721,8 +859,8 @@ Starts media selection. This API uses a promise to return the list of URIs that
**Example** **Example**
``` ```js
let option = { let option : mediaLibrary.MediaSelectOption = {
type : "media", type : "media",
count : 2 count : 2
}; };
...@@ -733,7 +871,155 @@ mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => { ...@@ -733,7 +871,155 @@ mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => {
console.log("An error occurred when selecting the media assets."); console.log("An error occurred when selecting the media assets.");
}); });
``` ```
### getActivePeers<sup>8+</sup>
getActivePeers(): Promise\<Array\<PeerInfo>>;
Obtains information about online peer devices. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.READ_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore
**Return value**
| Type | Description |
| ------------------- | -------------------- |
| Promise\<Array\<PeerInfo>> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.|
**Example**
```js
async function example() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
media.getActivePeers().then((devicesInfo) => {
if (devicesInfo != undefined) {
for (let i = 0; i < devicesInfo.length; i++) {
console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
}
} else {
console.info('get distributed info is undefined!')
}
}).catch((err) => {
console.info("get distributed info failed with error:" + err);
});
}
```
### getActivePeers<sup>8+</sup>
getActivePeers(callback: AsyncCallback\<Array\<PeerInfo>>): void;
Obtains information about online peer devices. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.READ_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore
**Return value**
| Type | Description |
| ------------------- | -------------------- |
| callback: AsyncCallback\<Array\<PeerInfo>> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.|
**Example**
```js
async function example() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
media.getActivePeers((err, devicesInfo) => {
if (devicesInfo != undefined) {
for (let i = 0; i < devicesInfo.length; i++) {
console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
}
} else {
console.info('get distributed fail, message = ' + err)
}
})
}
```
### getAllPeers<sup>8+</sup>
getAllPeers(): Promise\<Array\<PeerInfo>>;
Obtains information about all peer devices. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.READ_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore
**Return value**
| Type | Description |
| ------------------- | -------------------- |
| Promise\<Array\<PeerInfo>> | Promise used to return all peer devices, in an array of **PeerInfo** objects.|
**Example**
```js
async function example() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
media.getAllPeers().then((devicesInfo) => {
if (devicesInfo != undefined) {
for (let i = 0; i < devicesInfo.length; i++) {
console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
}
} else {
console.info('get distributed info is undefined!')
}
}).catch((err) => {
console.info("get distributed info failed with error:" + err);
});
}
```
### getAllPeers<sup>8+</sup>
getAllPeers(callback: AsyncCallback\<Array\<PeerInfo>>): void;
Obtains information about online peer devices. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.READ_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore
**Return value**
| Type | Description |
| ------------------- | -------------------- |
| callback: AsyncCallback\<Array\<PeerInfo>> | Promise used to return all peer devices, in an array of **PeerInfo** objects.|
**Example**
```js
async function example() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
media.getAllPeers((err, devicesInfo) => {
if (devicesInfo != undefined) {
for (let i = 0; i < devicesInfo.length; i++) {
console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
}
} else {
console.info('get distributed fail, message = ' + err)
}
})
}
```
## FileAsset<sup>7+</sup> ## FileAsset<sup>7+</sup>
...@@ -786,7 +1072,7 @@ Checks whether this file asset is a directory. This API uses an asynchronous cal ...@@ -786,7 +1072,7 @@ Checks whether this file asset is a directory. This API uses an asynchronous cal
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
...@@ -822,7 +1108,7 @@ Checks whether this file asset is a directory. This API uses a promise to return ...@@ -822,7 +1108,7 @@ Checks whether this file asset is a directory. This API uses a promise to return
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
...@@ -860,7 +1146,7 @@ Commits the modification in this file asset to the database. This API uses an as ...@@ -860,7 +1146,7 @@ Commits the modification in this file asset to the database. This API uses an as
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
...@@ -897,7 +1183,7 @@ Commits the modification in this file asset to the database. This API uses a pro ...@@ -897,7 +1183,7 @@ Commits the modification in this file asset to the database. This API uses a pro
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
...@@ -937,7 +1223,7 @@ Opens this file asset. This API uses an asynchronous callback to return the resu ...@@ -937,7 +1223,7 @@ Opens this file asset. This API uses an asynchronous callback to return the resu
**Example** **Example**
``` ```js
async function example() { async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE; let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
...@@ -981,7 +1267,7 @@ Opens this file asset. This API uses a promise to return the result. ...@@ -981,7 +1267,7 @@ Opens this file asset. This API uses a promise to return the result.
**Example** **Example**
``` ```js
async function example() { async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE; let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
...@@ -1016,7 +1302,7 @@ Closes this file asset. This API uses an asynchronous callback to return the res ...@@ -1016,7 +1302,7 @@ Closes this file asset. This API uses an asynchronous callback to return the res
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
...@@ -1032,7 +1318,7 @@ async function example() { ...@@ -1032,7 +1318,7 @@ async function example() {
console.info('File fd!' + fd); console.info('File fd!' + fd);
asset.close(fd, (closeErr) => { asset.close(fd, (closeErr) => {
if (closeErr != undefined) { if (closeErr != undefined) {
console.info('mediaLibraryTest : close : FAIL ' + closeErr.message); console.info('mediaLibraryTest : close : FAIL ' + closeErr);
console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL');
} else { } else {
console.info("=======asset.close success====>"); console.info("=======asset.close success====>");
...@@ -1069,7 +1355,7 @@ Closes this file asset. This API uses a promise to return the result. ...@@ -1069,7 +1355,7 @@ Closes this file asset. This API uses a promise to return the result.
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
...@@ -1085,7 +1371,7 @@ async function example() { ...@@ -1085,7 +1371,7 @@ async function example() {
console.info('File fd!' + fd); console.info('File fd!' + fd);
asset.close(fd).then((closeErr) => { asset.close(fd).then((closeErr) => {
if (closeErr != undefined) { if (closeErr != undefined) {
console.info('mediaLibraryTest : close : FAIL ' + closeErr.message); console.info('mediaLibraryTest : close : FAIL ' + closeErr);
console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL');
} else { } else {
...@@ -1117,7 +1403,7 @@ Obtains the thumbnail of this file asset. This API uses an asynchronous callback ...@@ -1117,7 +1403,7 @@ Obtains the thumbnail of this file asset. This API uses an asynchronous callback
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
...@@ -1130,7 +1416,7 @@ async function example() { ...@@ -1130,7 +1416,7 @@ async function example() {
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.getThumbnail((err, pixelmap) => { asset.getThumbnail((err, pixelmap) => {
console.info('mediaLibraryTest : getThumbnail successful '+ pixelmap); console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap);
}); });
} }
``` ```
...@@ -1154,9 +1440,9 @@ Obtains the thumbnail of this file asset, with the thumbnail size passed. This A ...@@ -1154,9 +1440,9 @@ Obtains the thumbnail of this file asset, with the thumbnail size passed. This A
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1168,7 +1454,7 @@ async function example() { ...@@ -1168,7 +1454,7 @@ async function example() {
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.getThumbnail(size, (err, pixelmap) => { asset.getThumbnail(size, (err, pixelmap) => {
console.info('mediaLibraryTest : getThumbnail successful '+ pixelmap); console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap);
}); });
} }
``` ```
...@@ -1197,9 +1483,9 @@ Obtains the thumbnail of this file asset, with the thumbnail size passed. This A ...@@ -1197,9 +1483,9 @@ Obtains the thumbnail of this file asset, with the thumbnail size passed. This A
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1212,7 +1498,7 @@ async function example() { ...@@ -1212,7 +1498,7 @@ async function example() {
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.getThumbnail(size) asset.getThumbnail(size)
.then((pixelmap) => { .then((pixelmap) => {
console.info('mediaLibraryTest : getThumbnail successful '+ pixelmap); console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap);
}) })
.catch((err) => { .catch((err) => {
console.info('mediaLibraryTest : getThumbnail fail'+ err); console.info('mediaLibraryTest : getThumbnail fail'+ err);
...@@ -1239,9 +1525,9 @@ Favorites or unfavorites this file asset. This API uses an asynchronous callback ...@@ -1239,9 +1525,9 @@ Favorites or unfavorites this file asset. This API uses an asynchronous callback
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1281,9 +1567,9 @@ Favorites or unfavorites this file asset. This API uses a promise to return the ...@@ -1281,9 +1567,9 @@ Favorites or unfavorites this file asset. This API uses a promise to return the
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1319,9 +1605,9 @@ Checks whether this file asset is favorited. This API uses an asynchronous callb ...@@ -1319,9 +1605,9 @@ Checks whether this file asset is favorited. This API uses an asynchronous callb
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1359,9 +1645,9 @@ Checks whether this file asset is favorited. This API uses a promise to return t ...@@ -1359,9 +1645,9 @@ Checks whether this file asset is favorited. This API uses a promise to return t
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1400,9 +1686,9 @@ Files in the trash are not actually deleted. You can set **isTrash** to **false* ...@@ -1400,9 +1686,9 @@ Files in the trash are not actually deleted. You can set **isTrash** to **false*
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1445,9 +1731,9 @@ Files in the trash are not actually deleted. You can set **isTrash** to **false* ...@@ -1445,9 +1731,9 @@ Files in the trash are not actually deleted. You can set **isTrash** to **false*
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1483,9 +1769,9 @@ Checks whether this file asset is in the trash. This API uses an asynchronous ca ...@@ -1483,9 +1769,9 @@ Checks whether this file asset is in the trash. This API uses an asynchronous ca
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1495,18 +1781,13 @@ async function example() { ...@@ -1495,18 +1781,13 @@ async function example() {
}; };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.isTrash(isTrashCallBack); asset.isTrash((err, isTrash) => {
function isTrashCallBack(err, isTrash) { if (isTrash == undefined) {
if (isTrash == true) { console.error('Failed to get trash state: ' + err);
console.info('mediaLibraryTest : ASSET_CALLBACK ASSET_CALLBACK isTrash = ' + isTrash); return;
asset.trash(true, istrashCallBack); }
console.info('Get trash state success: ' + isTrash);
} else { });
console.info('mediaLibraryTest : ASSET_CALLBACK isTrash Unsuccessful = ' + err);
console.info('mediaLibraryTest : ASSET_CALLBACK isTrash : FAIL');
}
}
} }
``` ```
...@@ -1528,22 +1809,21 @@ Checks whether this file asset is in the trash. This API uses a promise to retur ...@@ -1528,22 +1809,21 @@ Checks whether this file asset is in the trash. This API uses a promise to retur
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.isTrash().then(function(isTrash){ asset.isTrash().then(function(isTrash){
console.info("isTrash result:"+ isTrash); console.info("isTrash result: " + isTrash);
}).catch(function(err){ }).catch(function(err){
console.info("isTrash failed with error:"+ err); console.error("isTrash failed with error: " + err);
}); });
} }
``` ```
...@@ -1568,9 +1848,9 @@ Obtains the total number of files in the result set. ...@@ -1568,9 +1848,9 @@ Obtains the total number of files in the result set.
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE; let fileType = mediaLibrary.MediaType.FILE;
let getFileCountOneOp = { let getFileCountOneOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1599,9 +1879,9 @@ Checks whether the cursor is in the last row of the result set. ...@@ -1599,9 +1879,9 @@ Checks whether the cursor is in the last row of the result set.
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1637,9 +1917,9 @@ Releases and invalidates this **FetchFileResult** instance. Other APIs in this i ...@@ -1637,9 +1917,9 @@ Releases and invalidates this **FetchFileResult** instance. Other APIs in this i
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1668,9 +1948,9 @@ Obtains the first file asset in the result set. This API uses an asynchronous ca ...@@ -1668,9 +1948,9 @@ Obtains the first file asset in the result set. This API uses an asynchronous ca
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1705,9 +1985,9 @@ Obtains the first file asset in the result set. This API uses a promise to retur ...@@ -1705,9 +1985,9 @@ Obtains the first file asset in the result set. This API uses a promise to retur
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1740,9 +2020,9 @@ Obtains the next file asset in the result set. This API uses an asynchronous cal ...@@ -1740,9 +2020,9 @@ Obtains the next file asset in the result set. This API uses an asynchronous cal
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1777,9 +2057,9 @@ Obtains the next file asset in the result set. This API uses a promise to return ...@@ -1777,9 +2057,9 @@ Obtains the next file asset in the result set. This API uses a promise to return
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1810,9 +2090,9 @@ Obtains the last file asset in the result set. This API uses an asynchronous cal ...@@ -1810,9 +2090,9 @@ Obtains the last file asset in the result set. This API uses an asynchronous cal
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1847,9 +2127,9 @@ Obtains the last file asset in the result set. This API uses a promise to return ...@@ -1847,9 +2127,9 @@ Obtains the last file asset in the result set. This API uses a promise to return
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1879,9 +2159,9 @@ Obtains a file asset with the specified index in the result set. This API uses a ...@@ -1879,9 +2159,9 @@ Obtains a file asset with the specified index in the result set. This API uses a
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1922,9 +2202,9 @@ Obtains a file asset with the specified index in the result set. This API uses a ...@@ -1922,9 +2202,9 @@ Obtains a file asset with the specified index in the result set. This API uses a
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1934,9 +2214,9 @@ async function example() { ...@@ -1934,9 +2214,9 @@ async function example() {
}; };
let fetchFileResult = await media.getFileAssets(getImageOp); let fetchFileResult = await media.getFileAssets(getImageOp);
fetchFileResult.getPositionObject(1) .then(function (fileAsset){ fetchFileResult.getPositionObject(1) .then(function (fileAsset){
console.log('[Demo] fileAsset.displayName : ' + fileAsset.displayName); console.log('fileAsset.displayName : ' + fileAsset.displayName);
}).catch(function (err) { }).catch(function (err) {
console.info("[Demo] getFileAssets failed with error:" + err); console.info("getFileAssets failed with error:" + err);
}); });
} }
``` ```
...@@ -1957,9 +2237,9 @@ Obtains all the file assets in the result set. This API uses an asynchronous cal ...@@ -1957,9 +2237,9 @@ Obtains all the file assets in the result set. This API uses an asynchronous cal
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -1969,11 +2249,13 @@ async function example() { ...@@ -1969,11 +2249,13 @@ async function example() {
}; };
let fetchFileResult = await media.getFileAssets(getImageOp); let fetchFileResult = await media.getFileAssets(getImageOp);
fetchFileResult.getAllObject((err, fileAsset) => { fetchFileResult.getAllObject((err, fileAsset) => {
if (err) { if (err) {
console.error('Failed '); console.error('Failed ');
return; return;
} }
console.log('fileAsset.displayName : ' + fileAsset.displayName); for (let i = 0; i < fetchFileResult.getCount(); i++) {
console.log('fileAsset.displayName : ' + fileAsset[i].displayName);
}
}) })
} }
``` ```
...@@ -1994,9 +2276,9 @@ Obtains all the file assets in the result set. This API uses a promise to return ...@@ -1994,9 +2276,9 @@ Obtains all the file assets in the result set. This API uses a promise to return
**Example** **Example**
``` ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
...@@ -2045,7 +2327,7 @@ Commits the modification in the album attributes to the database. This API uses ...@@ -2045,7 +2327,7 @@ Commits the modification in the album attributes to the database. This API uses
**Example** **Example**
``` ```js
async function example() { async function example() {
let AlbumNoArgsfetchOp = { let AlbumNoArgsfetchOp = {
selections: '', selections: '',
...@@ -2082,7 +2364,7 @@ Commits the modification in the album attributes to the database. This API uses ...@@ -2082,7 +2364,7 @@ Commits the modification in the album attributes to the database. This API uses
**Example** **Example**
``` ```js
async function example() { async function example() {
let AlbumNoArgsfetchOp = { let AlbumNoArgsfetchOp = {
selections: '', selections: '',
...@@ -2118,7 +2400,7 @@ Obtains the file assets in this album. This API uses an asynchronous callback to ...@@ -2118,7 +2400,7 @@ Obtains the file assets in this album. This API uses an asynchronous callback to
**Example** **Example**
``` ```js
async function example() { async function example() {
let AlbumNoArgsfetchOp = { let AlbumNoArgsfetchOp = {
selections: '', selections: '',
...@@ -2161,7 +2443,7 @@ Obtains the file assets in this album. This API uses a promise to return the res ...@@ -2161,7 +2443,7 @@ Obtains the file assets in this album. This API uses a promise to return the res
**Example** **Example**
``` ```js
async function example() { async function example() {
let AlbumNoArgsfetchOp = { let AlbumNoArgsfetchOp = {
selections: '', selections: '',
...@@ -2170,7 +2452,7 @@ async function example() { ...@@ -2170,7 +2452,7 @@ async function example() {
let fileNoArgsfetchOp = { let fileNoArgsfetchOp = {
selections: '', selections: '',
selectionArgs: [], selectionArgs: [],
} };
const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
const album = albumList[0]; const album = albumList[0];
album.getFileAssets(fileNoArgsfetchOp).then(function(albumFetchFileResult){ album.getFileAssets(fileNoArgsfetchOp).then(function(albumFetchFileResult){
...@@ -2184,7 +2466,8 @@ async function example() { ...@@ -2184,7 +2466,8 @@ async function example() {
## PeerInfo<sup>8+</sup> ## PeerInfo<sup>8+</sup>
Describes information about a registered device. Describes information about a registered device.
This is a system API.
**System API**: This is a system API.
**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore **System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore
...@@ -2256,7 +2539,8 @@ Enumerates directory types. ...@@ -2256,7 +2539,8 @@ Enumerates directory types.
## DeviceType<sup>8+</sup> ## DeviceType<sup>8+</sup>
Enumerates device types. Enumerates device types.
This is a system API.
**System API**: This is a system API.
**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore **System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore
...@@ -2280,7 +2564,7 @@ Describes options for fetching media files. ...@@ -2280,7 +2564,7 @@ Describes options for fetching media files.
| ----------------------- | ------------------- | ---- | ---- | ---- | ------------------------------------------------------------ | | ----------------------- | ------------------- | ---- | ---- | ---- | ------------------------------------------------------------ |
| selections | string | Yes | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example:<br>selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?', | | selections | string | Yes | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example:<br>selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?', |
| selectionArgs | Array&lt;string&gt; | Yes | Yes | Yes | Value of the condition, which corresponds to the value of the condition column in **selections**.<br>Example:<br>selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | | selectionArgs | Array&lt;string&gt; | Yes | Yes | Yes | Value of the condition, which corresponds to the value of the condition column in **selections**.<br>Example:<br>selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], |
| order | string | Yes | Yes | No | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example:<br>Ascending: order: mediaLibrary.FileKey.DATE_ADDED + " ASC"<br>Descending: order: mediaLibrary.FileKey.DATE_ADDED + " DESC" | | order | string | Yes | Yes | No | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example:<br>Ascending: order: mediaLibrary.FileKey.DATE_ADDED + " ASC"<br>Descending: order: mediaLibrary.FileKey.DATE_ADDED + " DESC"|
| uri<sup>8+</sup> | string | Yes | Yes | No | File URI. | | uri<sup>8+</sup> | string | Yes | Yes | No | File URI. |
| networkId<sup>8+</sup> | string | Yes | Yes | No | Network ID of the registered device. | | networkId<sup>8+</sup> | string | Yes | Yes | No | Network ID of the registered device. |
| extendArgs<sup>8+</sup> | string | Yes | Yes | No | Extended parameters for fetching the files. Currently, no extended parameters are available. | | extendArgs<sup>8+</sup> | string | Yes | Yes | No | Extended parameters for fetching the files. Currently, no extended parameters are available. |
...@@ -2288,6 +2572,7 @@ Describes options for fetching media files. ...@@ -2288,6 +2572,7 @@ Describes options for fetching media files.
## Size<sup>8+</sup> ## Size<sup>8+</sup>
Describes the image size. Describes the image size.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
| Name | Type | Readable | Writable | Description | | Name | Type | Readable | Writable | Description |
......
...@@ -12,6 +12,9 @@ Both **PlainArray** and **[LightWeightMap](js-apis-lightweightmap.md)** are used ...@@ -12,6 +12,9 @@ Both **PlainArray** and **[LightWeightMap](js-apis-lightweightmap.md)** are used
**Recommended use case**: Use **PlainArray** when you need to store KV pairs whose keys are of the **number** type. **Recommended use case**: Use **PlainArray** when you need to store KV pairs whose keys are of the **number** type.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -93,7 +96,7 @@ Checks whether this container contains the specified key. ...@@ -93,7 +96,7 @@ Checks whether this container contains the specified key.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.has(1); plainArray.has(1);
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
let result1 = plainArray.has(1); let result1 = plainArray.has(1);
``` ```
...@@ -122,8 +125,8 @@ Obtains the value of the specified key in this container. ...@@ -122,8 +125,8 @@ Obtains the value of the specified key in this container.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
let result = plainArray.get(1); let result = plainArray.get(1);
``` ```
...@@ -152,8 +155,8 @@ Obtains the index of the first occurrence of an element with the specified key i ...@@ -152,8 +155,8 @@ Obtains the index of the first occurrence of an element with the specified key i
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
let result = plainArray.getIndexOfKey(2); let result = plainArray.getIndexOfKey(2);
``` ```
...@@ -182,9 +185,9 @@ Obtains the index of the first occurrence of an element with the specified value ...@@ -182,9 +185,9 @@ Obtains the index of the first occurrence of an element with the specified value
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
let result = plainArray.getIndexOfValue("sddfhf"); let result = plainArray.getIndexOfValue("squirrel");
``` ```
...@@ -212,8 +215,8 @@ Obtains the key of the element at the specified position in this container. ...@@ -212,8 +215,8 @@ Obtains the key of the element at the specified position in this container.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
let result = plainArray.getKeyAt(1); let result = plainArray.getKeyAt(1);
``` ```
...@@ -241,8 +244,8 @@ Obtains the value of an element at the specified position in this container. ...@@ -241,8 +244,8 @@ Obtains the value of an element at the specified position in this container.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
let result = plainArray.getKeyAt(1); let result = plainArray.getKeyAt(1);
``` ```
...@@ -264,8 +267,8 @@ Clones this container and returns a copy. The modification to the copy does not ...@@ -264,8 +267,8 @@ Clones this container and returns a copy. The modification to the copy does not
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
let newPlainArray = plainArray.clone(); let newPlainArray = plainArray.clone();
``` ```
...@@ -289,7 +292,7 @@ Adds an element to this container. ...@@ -289,7 +292,7 @@ Adds an element to this container.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
``` ```
...@@ -317,8 +320,8 @@ Removes an element with the specified key from this container. ...@@ -317,8 +320,8 @@ Removes an element with the specified key from this container.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
plainArray.remove(2); plainArray.remove(2);
let result = plainArray.remove(2); let result = plainArray.remove(2);
``` ```
...@@ -348,8 +351,8 @@ Removes an element at the specified position from this container. ...@@ -348,8 +351,8 @@ Removes an element at the specified position from this container.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
plainArray.removeAt(1); plainArray.removeAt(1);
let result = plainArray.removeAt(1); let result = plainArray.removeAt(1);
``` ```
...@@ -380,8 +383,8 @@ Removes elements in a specified range from this container. ...@@ -380,8 +383,8 @@ Removes elements in a specified range from this container.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
let result = plainArray.removeRangeFrom(1, 3); let result = plainArray.removeRangeFrom(1, 3);
``` ```
...@@ -405,8 +408,8 @@ Sets a value for an element at the specified position in this container. ...@@ -405,8 +408,8 @@ Sets a value for an element at the specified position in this container.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
plainArray.setValueAt(1, 3546); plainArray.setValueAt(1, 3546);
``` ```
...@@ -429,8 +432,8 @@ Obtains a string that contains all elements in this container. ...@@ -429,8 +432,8 @@ Obtains a string that contains all elements in this container.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
let result = plainArray.toString(); let result = plainArray.toString();
``` ```
...@@ -447,8 +450,8 @@ Clears this container and sets its length to **0**. ...@@ -447,8 +450,8 @@ Clears this container and sets its length to **0**.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
plainArray.clear(); plainArray.clear();
``` ```
...@@ -479,8 +482,8 @@ callbackfn ...@@ -479,8 +482,8 @@ callbackfn
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
plainArray.forEach((value, index) => { plainArray.forEach((value, index) => {
console.log("value:" + value, index); console.log("value:" + value, index);
}); });
...@@ -505,8 +508,8 @@ Obtains an iterator object that contains key-value pairs, where the key is of th ...@@ -505,8 +508,8 @@ Obtains an iterator object that contains key-value pairs, where the key is of th
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
// Method 1: // Method 1:
for (let item of plainArray) { for (let item of plainArray) {
......
# ProcessRunningInfo # ProcessRunningInfo<sup>(deprecated)</sup>
The **ProcessRunningInfo** module provides process running information. The **ProcessRunningInfo** module provides process running information.
> **NOTE** > **NOTE**
> > - The APIs provided by this module are deprecated since API version 9. You are advised to use [ProcessRunningInformation<sup>9+</sup>](js-apis-processrunninginformation.md) instead.
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 8.
## Usage ## Usage
...@@ -19,9 +19,9 @@ appManager.getProcessRunningInfos((error,data) => { ...@@ -19,9 +19,9 @@ appManager.getProcessRunningInfos((error,data) => {
## Attributes ## Attributes
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Mission
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| pid | number | Yes| No| Process ID.| | pid | number | Yes| No| Process ID.|
| uid | number | Yes| No| User ID.| | uid | number | Yes| No| User ID.|
......
# ProcessRunningInformation<sup>9+</sup>
The **ProcessRunningInformation** module provides process running information.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Usage Guidelines
The process running information is obtained through [appManager](js-apis-appmanager.md#appmanagergetprocessrunninginformation9).
```js
import appManager from '@ohos.application.appManager';
appManager.getProcessRunningInformation((error,data) => {
console.log("getProcessRunningInformation error: " + error.code + " data: " + JSON.stringify(data));
});
```
## Attributes
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| pid | number | Yes| No| Process ID.|
| uid | number | Yes| No| User ID.|
| processName | string | Yes| No| Process name.|
| bundleNames | Array&lt;string&gt; | Yes| No| Names of all running bundles in the process.|
...@@ -10,6 +10,9 @@ Unlike **[Deque](js-apis-deque.md)**, which supports insertion and removal at bo ...@@ -10,6 +10,9 @@ Unlike **[Deque](js-apis-deque.md)**, which supports insertion and removal at bo
**Recommended use case**: Use **Queue** in FIFO scenarios. **Recommended use case**: Use **Queue** in FIFO scenarios.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -72,7 +75,7 @@ let result1 = queue.add(1); ...@@ -72,7 +75,7 @@ let result1 = queue.add(1);
queue.add(1); queue.add(1);
let b = [1, 2, 3]; let b = [1, 2, 3];
queue.add(b); queue.add(b);
let c = {name : "lala", age : "13"}; let c = {name : "Dylon", age : "13"};
let result3 = queue.add(c); let result3 = queue.add(c);
``` ```
...@@ -180,6 +183,7 @@ Obtains an iterator, each item of which is a JavaScript object. ...@@ -180,6 +183,7 @@ Obtains an iterator, each item of which is a JavaScript object.
| IterableIterator&lt;T&gt; | Iterator obtained.| | IterableIterator&lt;T&gt; | Iterator obtained.|
**Example** **Example**
```ts ```ts
let queue = new Queue(); let queue = new Queue();
queue.add(2); queue.add(2);
......
...@@ -55,7 +55,7 @@ Describes the size of the screen region to capture. ...@@ -55,7 +55,7 @@ Describes the size of the screen region to capture.
## screenshot.save ## screenshot.save
save(options?: ScreenshotOptions, callback: AsyncCallback&lt;image.PixelMap&gt;): void save(options: ScreenshotOptions, callback: AsyncCallback&lt;image.PixelMap&gt;): void
Takes a screenshot and saves it as a **PixelMap** object. This API uses an asynchronous callback to return the result. Takes a screenshot and saves it as a **PixelMap** object. This API uses an asynchronous callback to return the result.
...@@ -67,7 +67,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async ...@@ -67,7 +67,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [ScreenshotOptions](#screenshotoptions) | No | Screenshot settings consist of **screenRect**, **imageSize**, **rotation**, and **displayId**. You can set the parameters separately.| | options | [ScreenshotOptions](#screenshotoptions) | Yes | Screenshot settings consist of **screenRect**, **imageSize**, **rotation**, and **displayId**. You can set the parameters separately.|
| callback | AsyncCallback&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Yes | Callback used to return a **PixelMap** object. | | callback | AsyncCallback&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Yes | Callback used to return a **PixelMap** object. |
**Example** **Example**
...@@ -97,6 +97,35 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async ...@@ -97,6 +97,35 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async
## screenshot.save ## screenshot.save
save(callback: AsyncCallback&lt;image.PixelMap&gt;): void
Takes a screenshot and saves it as a **PixelMap** object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
**Required permissions**: ohos.permission.CAPTURE_SCREEN (available only to system applications)
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Yes | Callback used to return a **PixelMap** object. |
**Example**
```js
screenshot.save((err, pixelMap) => {
if (err) {
console.log('Failed to save screenshot: ' + JSON.stringify(err));
return;
}
console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber());
pixelMap.release(); // Release the memory in time after the PixelMap is used.
});
```
## screenshot.save
save(options?: ScreenshotOptions): Promise&lt;image.PixelMap&gt; save(options?: ScreenshotOptions): Promise&lt;image.PixelMap&gt;
Takes a screenshot and saves it as a **PixelMap** object. This API uses a promise to return the result. Takes a screenshot and saves it as a **PixelMap** object. This API uses a promise to return the result.
......
...@@ -10,6 +10,9 @@ Unlike **[Queue](js-apis-queue.md)**, which is implemented based on the queue da ...@@ -10,6 +10,9 @@ Unlike **[Queue](js-apis-queue.md)**, which is implemented based on the queue da
**Recommended use case**: Use **Stack** in LOFI scenarios. **Recommended use case**: Use **Stack** in LOFI scenarios.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -73,7 +76,7 @@ let result = stack.push("a"); ...@@ -73,7 +76,7 @@ let result = stack.push("a");
let result1 = stack.push(1); let result1 = stack.push(1);
let b = [1, 2, 3]; let b = [1, 2, 3];
stack.push(b); stack.push(b);
let c = {name : "lala", age : "13"}; let c = {name : "Dylon", age : "13"};
let result3 = stack.push(c); let result3 = stack.push(c);
``` ```
......
...@@ -29,7 +29,7 @@ export default class UserTestRunner implements TestRunner { ...@@ -29,7 +29,7 @@ export default class UserTestRunner implements TestRunner {
onPrepare() { onPrepare() {
console.log("Trigger onPrepare") console.log("Trigger onPrepare")
} }
onRun(){} onRun(){}
}; };
``` ```
...@@ -50,6 +50,6 @@ export default class UserTestRunner implements TestRunner { ...@@ -50,6 +50,6 @@ export default class UserTestRunner implements TestRunner {
onPrepare() { onPrepare() {
console.log("Trigger onRun") console.log("Trigger onRun")
} }
onRun(){} onRun(){}
}; };
``` ```
...@@ -12,6 +12,10 @@ ...@@ -12,6 +12,10 @@
Recommended use case: Use **TreeMap** when you need to store KV pairs in sorted order. Recommended use case: Use **TreeMap** when you need to store KV pairs in sorted order.
This topic uses the following to identify the use of generics:
- K: Key
- V: Value
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -96,9 +100,9 @@ Checks whether this container has the specified key. ...@@ -96,9 +100,9 @@ Checks whether this container has the specified key.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
let result = treeMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result = treeMap.hasKey("squirrel");
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
let result1 = treeMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result1 = treeMap.hasKey("squirrel");
``` ```
...@@ -127,7 +131,7 @@ Checks whether this container has the specified value. ...@@ -127,7 +131,7 @@ Checks whether this container has the specified value.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
let result = treeMap.hasValue(123); let result = treeMap.hasValue(123);
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
let result1 = treeMap.hasValue(123); let result1 = treeMap.hasValue(123);
``` ```
...@@ -156,9 +160,9 @@ Obtains the value of the specified key in this container. ...@@ -156,9 +160,9 @@ Obtains the value of the specified key in this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
let result = treeMap.get("sdfs"); let result = treeMap.get("sparrow");
``` ```
...@@ -180,8 +184,8 @@ Obtains the first key in this container. ...@@ -180,8 +184,8 @@ Obtains the first key in this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
let result = treeMap.getFirstKey(); let result = treeMap.getFirstKey();
``` ```
...@@ -204,8 +208,8 @@ Obtains the last key in this container. ...@@ -204,8 +208,8 @@ Obtains the last key in this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
let result = treeMap.getLastKey(); let result = treeMap.getLastKey();
``` ```
...@@ -228,8 +232,8 @@ Adds all elements in a **TreeMap** instance to this container. ...@@ -228,8 +232,8 @@ Adds all elements in a **TreeMap** instance to this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
let map = new TreeMap(); let map = new TreeMap();
treeMap.setAll(map); treeMap.setAll(map);
``` ```
...@@ -260,7 +264,7 @@ Adds an element to this container. ...@@ -260,7 +264,7 @@ Adds an element to this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
``` ```
...@@ -288,9 +292,9 @@ Removes the element with the specified key from this container. ...@@ -288,9 +292,9 @@ Removes the element with the specified key from this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
treeMap.remove("sdfs"); treeMap.remove("sparrow");
``` ```
...@@ -318,10 +322,10 @@ Obtains the key that is placed in front of the input key in this container. ...@@ -318,10 +322,10 @@ Obtains the key that is placed in front of the input key in this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
treeMap.set("zdfgsd", 356); treeMap.set("gander", 356);
let result = treeMap.getLowerKey("sdfs"); let result = treeMap.getLowerKey("sparrow");
``` ```
...@@ -349,10 +353,10 @@ Obtains the key that is placed next to the input key in this container. ...@@ -349,10 +353,10 @@ Obtains the key that is placed next to the input key in this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
treeMap.set("zdfgsd", 356); treeMap.set("gander", 356);
let result = treeMap.getHigherKey("sdfs"); let result = treeMap.getHigherKey("sparrow");
``` ```
### replace ### replace
...@@ -380,8 +384,8 @@ Replaces an element in this container. ...@@ -380,8 +384,8 @@ Replaces an element in this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("sdfs", 123); treeMap.set("sparrow", 123);
let result = treeMap.replace("sdfs", 357); let result = treeMap.replace("sparrow", 357);
``` ```
...@@ -397,8 +401,8 @@ Clears this container and sets its length to **0**. ...@@ -397,8 +401,8 @@ Clears this container and sets its length to **0**.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
treeMap.clear(); treeMap.clear();
``` ```
...@@ -421,8 +425,8 @@ Obtains an iterator that contains all the keys in this container. ...@@ -421,8 +425,8 @@ Obtains an iterator that contains all the keys in this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
let iter = treeMap.keys(); let iter = treeMap.keys();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -450,8 +454,8 @@ Obtains an iterator that contains all the values in this container. ...@@ -450,8 +454,8 @@ Obtains an iterator that contains all the values in this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
let iter = treeMap.values(); let iter = treeMap.values();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -487,8 +491,8 @@ callbackfn ...@@ -487,8 +491,8 @@ callbackfn
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("sdfs", 123); treeMap.set("sparrow", 123);
treeMap.set("dfsghsf", 357); treeMap.set("gull", 357);
treeMap.forEach((value, key) => { treeMap.forEach((value, key) => {
console.log("value:" + value, key); console.log("value:" + value, key);
}); });
...@@ -513,8 +517,8 @@ Obtains an iterator that contains all the elements in this container. ...@@ -513,8 +517,8 @@ Obtains an iterator that contains all the elements in this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
let iter = treeMap.entries(); let iter = treeMap.entries();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -542,8 +546,8 @@ Obtains an iterator, each item of which is a JavaScript object. ...@@ -542,8 +546,8 @@ Obtains an iterator, each item of which is a JavaScript object.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
// Method 1: // Method 1:
for (let item of treeMap) { for (let item of treeMap) {
......
...@@ -10,6 +10,9 @@ ...@@ -10,6 +10,9 @@
Recommended use case: Use **TreeSet** when you need to store data in sorted order. Recommended use case: Use **TreeSet** when you need to store data in sorted order.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -29,7 +32,7 @@ import TreeSet from '@ohos.util.TreeSet'; ...@@ -29,7 +32,7 @@ import TreeSet from '@ohos.util.TreeSet';
### constructor ### constructor
constructor(comparator?:(firstValue: T, secondValue: T) => boolean) constructor(comparator?: (firstValue: T, secondValue: T) => boolean)
A constructor used to create a **TreeSet** instance. A constructor used to create a **TreeSet** instance.
...@@ -118,8 +121,8 @@ Obtains the value of the first element in this container. ...@@ -118,8 +121,8 @@ Obtains the value of the first element in this container.
```ts ```ts
let treeSet = new TreeSet(); let treeSet = new TreeSet();
treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); treeSet.add("squirrel");
treeSet.add("sdfs"); treeSet.add("sparrow");
let result = treeSet.getFirstValue(); let result = treeSet.getFirstValue();
``` ```
...@@ -142,8 +145,8 @@ Obtains the value of the last element in this container. ...@@ -142,8 +145,8 @@ Obtains the value of the last element in this container.
```ts ```ts
let treeSet = new TreeSet(); let treeSet = new TreeSet();
treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); treeSet.add("squirrel");
treeSet.add("sdfs"); treeSet.add("sparrow");
let result = treeSet.getLastValue(); let result = treeSet.getLastValue();
``` ```
...@@ -172,7 +175,7 @@ Adds an element to this container. ...@@ -172,7 +175,7 @@ Adds an element to this container.
```ts ```ts
let treeSet = new TreeSet(); let treeSet = new TreeSet();
let result = treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result = treeSet.add("squirrel");
``` ```
...@@ -200,9 +203,9 @@ Removes the element with the specified key from this container. ...@@ -200,9 +203,9 @@ Removes the element with the specified key from this container.
```ts ```ts
let treeSet = new TreeSet(); let treeSet = new TreeSet();
treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); treeSet.add("squirrel");
treeSet.add("sdfs"); treeSet.add("sparrow");
let result = treeSet.remove("sdfs"); let result = treeSet.remove("sparrow");
``` ```
...@@ -230,10 +233,10 @@ Obtains the value that is placed in front of the input key in this container. ...@@ -230,10 +233,10 @@ Obtains the value that is placed in front of the input key in this container.
```ts ```ts
let treeSet = new TreeSet(); let treeSet = new TreeSet();
treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); treeSet.add("squirrel");
treeSet.add("sdfs"); treeSet.add("sparrow");
treeSet.add("zdfgsd"); treeSet.add("gander");
let result = treeSet.getLowerValue("sdfs"); let result = treeSet.getLowerValue("sparrow");
``` ```
...@@ -261,10 +264,10 @@ Obtains the value that is placed next to the input key in this container. ...@@ -261,10 +264,10 @@ Obtains the value that is placed next to the input key in this container.
```ts ```ts
let treeSet = new TreeSet(); let treeSet = new TreeSet();
treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); treeSet.add("squirrel");
treeSet.add("sdfs"); treeSet.add("sparrow");
treeSet.add("zdfgsd"); treeSet.add("gander");
let result = treeSet.getHigherValue("sdfs"); let result = treeSet.getHigherValue("sparrow");
``` ```
...@@ -286,8 +289,8 @@ Removes the first element in this container. ...@@ -286,8 +289,8 @@ Removes the first element in this container.
```ts ```ts
let treeSet = new TreeSet(); let treeSet = new TreeSet();
treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); treeSet.add("squirrel");
treeSet.add("sdfs"); treeSet.add("sparrow");
let result = treeSet.popFirst(); let result = treeSet.popFirst();
``` ```
...@@ -310,8 +313,8 @@ Removes the last element in this container. ...@@ -310,8 +313,8 @@ Removes the last element in this container.
```ts ```ts
let treeSet = new TreeSet(); let treeSet = new TreeSet();
treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); treeSet.add("squirrel");
treeSet.add("sdfs"); treeSet.add("sparrow");
let result = treeSet.popLast(); let result = treeSet.popLast();
``` ```
...@@ -328,8 +331,8 @@ Clears this container and sets its length to **0**. ...@@ -328,8 +331,8 @@ Clears this container and sets its length to **0**.
```ts ```ts
let treeSet = new TreeSet(); let treeSet = new TreeSet();
treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); treeSet.add("squirrel");
treeSet.add("sdfs"); treeSet.add("sparrow");
treeSet.clear(); treeSet.clear();
``` ```
...@@ -352,8 +355,8 @@ Obtains an iterator that contains all the values in this container. ...@@ -352,8 +355,8 @@ Obtains an iterator that contains all the values in this container.
```ts ```ts
let treeSet = new TreeSet(); let treeSet = new TreeSet();
treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); treeSet.add("squirrel");
treeSet.add("sdfs"); treeSet.add("sparrow");
let iter = treeSet.values(); let iter = treeSet.values();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -389,8 +392,8 @@ callbackfn ...@@ -389,8 +392,8 @@ callbackfn
```ts ```ts
let treeSet = new TreeSet(); let treeSet = new TreeSet();
treeSet.add("sdfs"); treeSet.add("sparrow");
treeSet.add("dfsghsf"); treeSet.add("gull");
treeSet.forEach((value, key) => { treeSet.forEach((value, key) => {
console.log("value:" + value, key) console.log("value:" + value, key)
}); });
...@@ -415,8 +418,8 @@ Obtains an iterator that contains all the elements in this container. ...@@ -415,8 +418,8 @@ Obtains an iterator that contains all the elements in this container.
```ts ```ts
let treeSet = new TreeSet(); let treeSet = new TreeSet();
treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); treeSet.add("squirrel");
treeSet.add("sdfs"); treeSet.add("sparrow");
let iter = treeSet.entries(); let iter = treeSet.entries();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -445,8 +448,8 @@ Obtains an iterator, each item of which is a JavaScript object. ...@@ -445,8 +448,8 @@ Obtains an iterator, each item of which is a JavaScript object.
```ts ```ts
let treeSet = new TreeSet(); let treeSet = new TreeSet();
treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); treeSet.add("squirrel");
treeSet.add("sdfs"); treeSet.add("sparrow");
// Method 1: // Method 1:
for (let item of treeSet) { for (let item of treeSet) {
......
...@@ -10,6 +10,9 @@ Both **Vector** and **[ArrayList](js-apis-arraylist.md)** are implemented based ...@@ -10,6 +10,9 @@ Both **Vector** and **[ArrayList](js-apis-arraylist.md)** are implemented based
**Recommended use case**: Use **Vector** when the data volume is large. **Recommended use case**: Use **Vector** when the data volume is large.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -71,7 +74,7 @@ let result = vector.add("a"); ...@@ -71,7 +74,7 @@ let result = vector.add("a");
let result1 = vector.add(1); let result1 = vector.add(1);
let b = [1, 2, 3]; let b = [1, 2, 3];
vector.add(b); vector.add(b);
let c = {name : "lala", age : "13"}; let c = {name : "Dylon", age : "13"};
let result3 = vector.add(c); let result3 = vector.add(c);
``` ```
...@@ -123,9 +126,9 @@ Checks whether this container has the specified element. ...@@ -123,9 +126,9 @@ Checks whether this container has the specified element.
```ts ```ts
let vector = new Vector(); let vector = new Vector();
let result = vector.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result = vector.has("squirrel");
vector.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); vector.add("squirrel");
let result1 = vector.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result1 = vector.has("squirrel");
``` ```
### getIndexOf ### getIndexOf
...@@ -862,7 +865,6 @@ Obtains an iterator. Each item of the iterator is a JavaScript object. ...@@ -862,7 +865,6 @@ Obtains an iterator. Each item of the iterator is a JavaScript object.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| IterableIterator&lt;T&gt; | Iterator obtained.| | IterableIterator&lt;T&gt; | Iterator obtained.|
......
...@@ -303,8 +303,8 @@ Creates a subwindow. This API uses an asynchronous callback to return the result ...@@ -303,8 +303,8 @@ Creates a subwindow. This API uses an asynchronous callback to return the result
**Example** **Example**
```js ```js
var windowClass = null; let windowClass = null;
window.create("first", window.WindowType.TYPE_APP,(err,data) => { window.create('first', window.WindowType.TYPE_APP,(err,data) => {
if(err.code){ if(err.code){
console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err));
return; return;
...@@ -340,8 +340,8 @@ Creates a subwindow. This API uses a promise to return the result. ...@@ -340,8 +340,8 @@ Creates a subwindow. This API uses a promise to return the result.
**Example** **Example**
```js ```js
var windowClass = null; let windowClass = null;
let promise = window.create("first", window.WindowType.TYPE_APP); let promise = window.create('first', window.WindowType.TYPE_APP);
promise.then((data)=> { promise.then((data)=> {
windowClass = data; windowClass = data;
console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data)); console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data));
...@@ -370,8 +370,8 @@ Creates a subwindow (in API version 8) or a system window (from API version 9). ...@@ -370,8 +370,8 @@ Creates a subwindow (in API version 8) or a system window (from API version 9).
**Example** **Example**
```js ```js
var windowClass = null; let windowClass = null;
window.create(this.context, "alertWindow", window.WindowType.TYPE_SYSTEM_ALERT, (err, data) => { window.create(this.context, 'alertWindow', window.WindowType.TYPE_SYSTEM_ALERT, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to create the window. Cause: ' + JSON.stringify(err)); console.error('Failed to create the window. Cause: ' + JSON.stringify(err));
return; return;
...@@ -407,8 +407,8 @@ Creates a subwindow (in API version 8) or a system window (from API version 9). ...@@ -407,8 +407,8 @@ Creates a subwindow (in API version 8) or a system window (from API version 9).
**Example** **Example**
```js ```js
var windowClass = null; let windowClass = null;
let promise = window.create(this.context, "alertWindow", window.WindowType.TYPE_SYSTEM_ALERT); let promise = window.create(this.context, 'alertWindow', window.WindowType.TYPE_SYSTEM_ALERT);
promise.then((data)=> { promise.then((data)=> {
windowClass = data; windowClass = data;
console.info('Succeeded in creating the window. Data:' + JSON.stringify(data)); console.info('Succeeded in creating the window. Data:' + JSON.stringify(data));
...@@ -435,8 +435,8 @@ Finds a window based on the ID. This API uses an asynchronous callback to return ...@@ -435,8 +435,8 @@ Finds a window based on the ID. This API uses an asynchronous callback to return
**Example** **Example**
```js ```js
var windowClass = null; let windowClass = null;
window.find("alertWindow", (err, data) => { window.find('alertWindow', (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to find the Window. Cause: ' + JSON.stringify(err)); console.error('Failed to find the Window. Cause: ' + JSON.stringify(err));
return; return;
...@@ -469,8 +469,8 @@ Finds a window based on the ID. This API uses a promise to return the result. ...@@ -469,8 +469,8 @@ Finds a window based on the ID. This API uses a promise to return the result.
**Example** **Example**
```js ```js
var windowClass = null; let windowClass = null;
let promise = window.find("alertWindow"); let promise = window.find('alertWindow');
promise.then((data)=> { promise.then((data)=> {
windowClass = data; windowClass = data;
console.info('Succeeded in finding the window. Data: ' + JSON.stringify(data)); console.info('Succeeded in finding the window. Data: ' + JSON.stringify(data));
...@@ -498,7 +498,7 @@ Obtains the top window of the current application. This API uses an asynchronous ...@@ -498,7 +498,7 @@ Obtains the top window of the current application. This API uses an asynchronous
**Example** **Example**
```js ```js
var windowClass = null; let windowClass = null;
window.getTopWindow((err, data) => { window.getTopWindow((err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err));
...@@ -528,7 +528,7 @@ Obtains the top window of the current application. This API uses a promise to re ...@@ -528,7 +528,7 @@ Obtains the top window of the current application. This API uses a promise to re
**Example** **Example**
```js ```js
var windowClass = null; let windowClass = null;
let promise = window.getTopWindow(); let promise = window.getTopWindow();
promise.then((data)=> { promise.then((data)=> {
windowClass = data; windowClass = data;
...@@ -556,7 +556,7 @@ Obtains the top window of the current application. This API uses an asynchronous ...@@ -556,7 +556,7 @@ Obtains the top window of the current application. This API uses an asynchronous
**Example** **Example**
```js ```js
var windowClass = null; let windowClass = null;
window.getTopWindow(this.context, (err, data) => { window.getTopWindow(this.context, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err));
...@@ -590,7 +590,7 @@ Obtains the top window of the current application. This API uses a promise to re ...@@ -590,7 +590,7 @@ Obtains the top window of the current application. This API uses a promise to re
**Example** **Example**
```js ```js
var windowClass = null; let windowClass = null;
let promise = window.getTopWindow(this.context); let promise = window.getTopWindow(this.context);
promise.then((data)=> { promise.then((data)=> {
windowClass = data; windowClass = data;
...@@ -622,7 +622,7 @@ Minimizes all windows on a display. This API uses an asynchronous callback to re ...@@ -622,7 +622,7 @@ Minimizes all windows on a display. This API uses an asynchronous callback to re
import display from '@ohos.display' import display from '@ohos.display'
import window from '@ohos.window' import window from '@ohos.window'
var displayClass = null; let displayClass = null;
display.getDefaultDisplay((err, data) => { display.getDefaultDisplay((err, data) => {
if(err.code) { if(err.code) {
return; return;
...@@ -665,7 +665,7 @@ Minimizes all windows on a display. This API uses a promise to return the result ...@@ -665,7 +665,7 @@ Minimizes all windows on a display. This API uses a promise to return the result
import display from '@ohos.display' import display from '@ohos.display'
import window from '@ohos.window' import window from '@ohos.window'
var displayClass = null; let displayClass = null;
display.getDefaultDisplay((err, data) => { display.getDefaultDisplay((err, data) => {
if(err.code) { if(err.code) {
return; return;
...@@ -1255,7 +1255,7 @@ Sets the type of this window. This API uses an asynchronous callback to return t ...@@ -1255,7 +1255,7 @@ Sets the type of this window. This API uses an asynchronous callback to return t
**Example** **Example**
```js ```js
var type = window.WindowType.TYPE_APP; let type = window.WindowType.TYPE_APP;
windowClass.setWindowType(type, (err, data) => { windowClass.setWindowType(type, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to set the window type. Cause: ' + JSON.stringify(err)); console.error('Failed to set the window type. Cause: ' + JSON.stringify(err));
...@@ -1294,7 +1294,7 @@ Sets the type of this window. This API uses a promise to return the result. ...@@ -1294,7 +1294,7 @@ Sets the type of this window. This API uses a promise to return the result.
**Example** **Example**
```js ```js
var type = window.WindowType.TYPE_APP; let type = window.WindowType.TYPE_APP;
let promise = windowClass.setWindowType(type); let promise = windowClass.setWindowType(type);
promise.then((data)=> { promise.then((data)=> {
console.info('Succeeded in setting the window type. Data: ' + JSON.stringify(data)); console.info('Succeeded in setting the window type. Data: ' + JSON.stringify(data));
...@@ -1372,7 +1372,7 @@ Obtains the area where this window cannot be displayed, for example, the system ...@@ -1372,7 +1372,7 @@ Obtains the area where this window cannot be displayed, for example, the system
**Example** **Example**
```js ```js
var type = window.AvoidAreaType.TYPE_SYSTEM; let type = window.AvoidAreaType.TYPE_SYSTEM;
windowClass.getAvoidArea(type, (err, data) => { windowClass.getAvoidArea(type, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to obtain the area. Cause:' + JSON.stringify(err)); console.error('Failed to obtain the area. Cause:' + JSON.stringify(err));
...@@ -1405,7 +1405,7 @@ Obtains the area where this window cannot be displayed, for example, the system ...@@ -1405,7 +1405,7 @@ Obtains the area where this window cannot be displayed, for example, the system
**Example** **Example**
```js ```js
var type = window.AvoidAreaType.TYPE_SYSTEM; let type = window.AvoidAreaType.TYPE_SYSTEM;
let promise = windowClass.getAvoidArea(type); let promise = windowClass.getAvoidArea(type);
promise.then((data)=> { promise.then((data)=> {
console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)); console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data));
...@@ -1432,7 +1432,7 @@ Sets whether to enable the full-screen mode for this window. This API uses an as ...@@ -1432,7 +1432,7 @@ Sets whether to enable the full-screen mode for this window. This API uses an as
**Example** **Example**
```js ```js
var isFullScreen = true; let isFullScreen = true;
windowClass.setFullScreen(isFullScreen, (err, data) => { windowClass.setFullScreen(isFullScreen, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to enable the full-screen mode. Cause: ' + JSON.stringify(err)); console.error('Failed to enable the full-screen mode. Cause: ' + JSON.stringify(err));
...@@ -1465,7 +1465,7 @@ Sets whether to enable the full-screen mode for this window. This API uses a pro ...@@ -1465,7 +1465,7 @@ Sets whether to enable the full-screen mode for this window. This API uses a pro
**Example** **Example**
```js ```js
var isFullScreen = true; let isFullScreen = true;
let promise = windowClass.setFullScreen(isFullScreen); let promise = windowClass.setFullScreen(isFullScreen);
promise.then((data)=> { promise.then((data)=> {
console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data));
...@@ -1492,7 +1492,7 @@ Sets whether to enable the full-screen mode for the window layout. This API uses ...@@ -1492,7 +1492,7 @@ Sets whether to enable the full-screen mode for the window layout. This API uses
**Example** **Example**
```js ```js
var isLayoutFullScreen= true; let isLayoutFullScreen= true;
windowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => { windowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err));
...@@ -1525,7 +1525,7 @@ Sets whether to enable the full-screen mode for the window layout. This API uses ...@@ -1525,7 +1525,7 @@ Sets whether to enable the full-screen mode for the window layout. This API uses
**Example** **Example**
```js ```js
var isLayoutFullScreen = true; let isLayoutFullScreen = true;
let promise = windowClass.setLayoutFullScreen(isLayoutFullScreen); let promise = windowClass.setLayoutFullScreen(isLayoutFullScreen);
promise.then((data)=> { promise.then((data)=> {
console.info('Succeeded in setting the window layout to full-screen mode. Data: ' + JSON.stringify(data)); console.info('Succeeded in setting the window layout to full-screen mode. Data: ' + JSON.stringify(data));
...@@ -1546,14 +1546,14 @@ Sets whether to display the status bar and navigation bar in this window. This A ...@@ -1546,14 +1546,14 @@ Sets whether to display the status bar and navigation bar in this window. This A
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------------------------------------------ | | -------- | ------------------------- | ---- | ------------------------------------------------------------ |
| names | Array | Yes | Whether to display the status bar and navigation bar.<br>For example, to display the status bar and navigation bar, set this parameter to `["status", "navigation"]`. By default, they are not displayed.| | names | Array | Yes | Whether to display the status bar and navigation bar.<br>For example, to display the status bar and navigation bar, set this parameter to `['status', 'navigation']`. By default, they are not displayed.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
**Example** **Example**
```js ```js
// In this example, the status bar and navigation bar are not displayed. // In this example, the status bar and navigation bar are not displayed.
var names = []; let names = [];
windowClass.setSystemBarEnable(names, (err, data) => { windowClass.setSystemBarEnable(names, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err));
...@@ -1575,7 +1575,7 @@ Sets whether to display the status bar and navigation bar in this window. This A ...@@ -1575,7 +1575,7 @@ Sets whether to display the status bar and navigation bar in this window. This A
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ----- | ---- | ------------------------------------------------------------ | | ------ | ----- | ---- | ------------------------------------------------------------ |
| names | Array | Yes | Whether to display the status bar and navigation bar.<br>For example, to display the status bar and navigation bar, set this parameter to `["status", "navigation"]`. By default, they are not displayed.| | names | Array | Yes | Whether to display the status bar and navigation bar.<br>For example, to display the status bar and navigation bar, set this parameter to `['status', 'navigation']`. By default, they are not displayed.|
**Return value** **Return value**
...@@ -1587,7 +1587,7 @@ Sets whether to display the status bar and navigation bar in this window. This A ...@@ -1587,7 +1587,7 @@ Sets whether to display the status bar and navigation bar in this window. This A
```js ```js
// In this example, the status bar and navigation bar are not displayed. // In this example, the status bar and navigation bar are not displayed.
var names = []; let names = [];
let promise = windowClass.setSystemBarEnable(names); let promise = windowClass.setSystemBarEnable(names);
promise.then((data)=> { promise.then((data)=> {
console.info('Succeeded in setting the system bar to be invisible. Data: ' + JSON.stringify(data)); console.info('Succeeded in setting the system bar to be invisible. Data: ' + JSON.stringify(data));
...@@ -1614,7 +1614,7 @@ Sets the properties of the status bar and navigation bar in this window. This AP ...@@ -1614,7 +1614,7 @@ Sets the properties of the status bar and navigation bar in this window. This AP
**Example** **Example**
```js ```js
var SystemBarProperties={ let SystemBarProperties={
statusBarColor: '#ff00ff', statusBarColor: '#ff00ff',
navigationBarColor: '#00ff00', navigationBarColor: '#00ff00',
// The following properties are supported since API version 7. // The following properties are supported since API version 7.
...@@ -1656,7 +1656,7 @@ Sets the properties of the status bar and navigation bar in this window. This AP ...@@ -1656,7 +1656,7 @@ Sets the properties of the status bar and navigation bar in this window. This AP
**Example** **Example**
```js ```js
var SystemBarProperties={ let SystemBarProperties={
statusBarColor: '#ff00ff', statusBarColor: '#ff00ff',
navigationBarColor: '#00ff00', navigationBarColor: '#00ff00',
// The following properties are supported since API version 7. // The following properties are supported since API version 7.
...@@ -1692,7 +1692,7 @@ Sets the preferred orientation for this window. This API uses an asynchronous ca ...@@ -1692,7 +1692,7 @@ Sets the preferred orientation for this window. This API uses an asynchronous ca
**Example** **Example**
```js ```js
var orientation = window.Orientation.AUTO_ROTATION; let orientation = window.Orientation.AUTO_ROTATION;
windowClass.setPreferredOrientation(orientation, (err, data) => { windowClass.setPreferredOrientation(orientation, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to set window orientation. Cause: ' + JSON.stringify(err)); console.error('Failed to set window orientation. Cause: ' + JSON.stringify(err));
...@@ -1725,7 +1725,7 @@ Sets the preferred orientation for this window. This API uses a promise to retur ...@@ -1725,7 +1725,7 @@ Sets the preferred orientation for this window. This API uses a promise to retur
**Example** **Example**
```js ```js
var orientation = window.Orientation.AUTO_ROTATION; let orientation = window.Orientation.AUTO_ROTATION;
let promise = windowClass.setPreferredOrientation(orientation); let promise = windowClass.setPreferredOrientation(orientation);
promise.then((data)=> { promise.then((data)=> {
console.info('Succeeded in setting the window orientation. Data: ' + JSON.stringify(data)); console.info('Succeeded in setting the window orientation. Data: ' + JSON.stringify(data));
...@@ -1752,7 +1752,7 @@ Loads content from a page to this window. This API uses an asynchronous callback ...@@ -1752,7 +1752,7 @@ Loads content from a page to this window. This API uses an asynchronous callback
**Example** **Example**
```js ```js
windowClass.loadContent("pages/page2/page2", (err, data) => { windowClass.loadContent('pages/page2/page2', (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to load the content. Cause:' + JSON.stringify(err)); console.error('Failed to load the content. Cause:' + JSON.stringify(err));
return; return;
...@@ -1784,7 +1784,7 @@ Loads content from a page to this window. This API uses a promise to return the ...@@ -1784,7 +1784,7 @@ Loads content from a page to this window. This API uses a promise to return the
**Example** **Example**
```js ```js
let promise = windowClass.loadContent("pages/page2/page2"); let promise = windowClass.loadContent('pages/page2/page2');
promise.then((data)=> { promise.then((data)=> {
console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data));
}).catch((err)=>{ }).catch((err)=>{
...@@ -1816,9 +1816,9 @@ class myAbility extends Ability { ...@@ -1816,9 +1816,9 @@ class myAbility extends Ability {
storage : LocalStorage storage : LocalStorage
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
this.storage = new LocalStorage(); this.storage = new LocalStorage();
this.storage.setOrCreate("storageSimpleProp",121); this.storage.setOrCreate('storageSimpleProp',121);
console.log('onWindowStageCreate'); console.log('onWindowStageCreate');
windowStage.loadContent("pages/page2",this.storage,(err, data) => { windowStage.loadContent('pages/page2',this.storage,(err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to load the content. Cause:' + JSON.stringify(err)); console.error('Failed to load the content. Cause:' + JSON.stringify(err));
return; return;
...@@ -1859,10 +1859,10 @@ class myAbility extends Ability { ...@@ -1859,10 +1859,10 @@ class myAbility extends Ability {
storage : LocalStorage storage : LocalStorage
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
this.storage = new LocalStorage(); this.storage = new LocalStorage();
this.storage.setOrCreate("storageSimpleProp",121); this.storage.setOrCreate('storageSimpleProp',121);
console.log('onWindowStageCreate'); console.log('onWindowStageCreate');
var windowClass = null; let windowClass = null;
let promise = windowStage.loadContent("pages/page2",this.storage); let promise = windowStage.loadContent('pages/page2',this.storage);
promise.then((data)=> { promise.then((data)=> {
windowClass = data; windowClass = data;
console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data));
...@@ -2195,7 +2195,7 @@ Unsubscribes from screenshot events. ...@@ -2195,7 +2195,7 @@ Unsubscribes from screenshot events.
**Example** **Example**
```js ```js
var callback = ()=>{ let callback = ()=>{
console.info('screenshot happened'); console.info('screenshot happened');
} }
windowClass.on('screenshot', callback) windowClass.on('screenshot', callback)
...@@ -2272,7 +2272,7 @@ Binds the modal window to the target window, and adds a callback to listen for m ...@@ -2272,7 +2272,7 @@ Binds the modal window to the target window, and adds a callback to listen for m
```js ```js
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log('server died');
} }
} }
class TestRemoteObject extends rpc.RemoteObject { class TestRemoteObject extends rpc.RemoteObject {
...@@ -2289,7 +2289,7 @@ class TestRemoteObject extends rpc.RemoteObject { ...@@ -2289,7 +2289,7 @@ class TestRemoteObject extends rpc.RemoteObject {
return false; return false;
} }
} }
let token = new TestRemoteObject("testObject"); let token = new TestRemoteObject('testObject');
windowClass.bindDialogTarget(token, () => { windowClass.bindDialogTarget(token, () => {
console.info('Dialog Window Need Destroy.'); console.info('Dialog Window Need Destroy.');
}, (err, data) => { }, (err, data) => {
...@@ -2329,7 +2329,7 @@ Binds the modal window to the target window, and adds a callback to listen for m ...@@ -2329,7 +2329,7 @@ Binds the modal window to the target window, and adds a callback to listen for m
```js ```js
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log('server died');
} }
} }
class TestRemoteObject extends rpc.RemoteObject { class TestRemoteObject extends rpc.RemoteObject {
...@@ -2346,7 +2346,7 @@ class TestRemoteObject extends rpc.RemoteObject { ...@@ -2346,7 +2346,7 @@ class TestRemoteObject extends rpc.RemoteObject {
return false; return false;
} }
} }
let token = new TestRemoteObject("testObject"); let token = new TestRemoteObject('testObject');
let promise = windowClass.bindDialogTarget(token, () => { let promise = windowClass.bindDialogTarget(token, () => {
console.info('Dialog Window Need Destroy.'); console.info('Dialog Window Need Destroy.');
}); });
...@@ -2535,7 +2535,7 @@ Sets the background color for this window. This API uses an asynchronous callbac ...@@ -2535,7 +2535,7 @@ Sets the background color for this window. This API uses an asynchronous callbac
**Example** **Example**
```js ```js
var color = '#00ff33'; let color = '#00ff33';
windowClass.setBackgroundColor(color, (err, data) => { windowClass.setBackgroundColor(color, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to set the background color. Cause: ' + JSON.stringify(err)); console.error('Failed to set the background color. Cause: ' + JSON.stringify(err));
...@@ -2568,7 +2568,7 @@ Sets the background color for this window. This API uses a promise to return the ...@@ -2568,7 +2568,7 @@ Sets the background color for this window. This API uses a promise to return the
**Example** **Example**
```js ```js
var color = '#00ff33'; let color = '#00ff33';
let promise = windowClass.setBackgroundColor(color); let promise = windowClass.setBackgroundColor(color);
promise.then((data)=> { promise.then((data)=> {
console.info('Succeeded in setting the background color. Data: ' + JSON.stringify(data)); console.info('Succeeded in setting the background color. Data: ' + JSON.stringify(data));
...@@ -2596,7 +2596,7 @@ Wakes up the screen. ...@@ -2596,7 +2596,7 @@ Wakes up the screen.
**Example** **Example**
```js ```js
var wakeUp = true; let wakeUp = true;
windowClass.setWakeUpScreen(wakeUp); windowClass.setWakeUpScreen(wakeUp);
``` ```
...@@ -2618,7 +2618,7 @@ Sets the screen brightness for this window. This API uses an asynchronous callba ...@@ -2618,7 +2618,7 @@ Sets the screen brightness for this window. This API uses an asynchronous callba
**Example** **Example**
```js ```js
var brightness = 1; let brightness = 1;
windowClass.setBrightness(brightness, (err, data) => { windowClass.setBrightness(brightness, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err));
...@@ -2651,7 +2651,7 @@ Sets the screen brightness for this window. This API uses a promise to return th ...@@ -2651,7 +2651,7 @@ Sets the screen brightness for this window. This API uses a promise to return th
**Example** **Example**
```js ```js
var brightness = 1; let brightness = 1;
let promise = windowClass.setBrightness(brightness); let promise = windowClass.setBrightness(brightness);
promise.then((data)=> { promise.then((data)=> {
console.info('Succeeded in setting the brightness. Data: ' + JSON.stringify(data)); console.info('Succeeded in setting the brightness. Data: ' + JSON.stringify(data));
...@@ -2748,7 +2748,7 @@ Sets whether this window can gain focus. This API uses an asynchronous callback ...@@ -2748,7 +2748,7 @@ Sets whether this window can gain focus. This API uses an asynchronous callback
**Example** **Example**
```js ```js
var isFocusable= true; let isFocusable= true;
windowClass.setFocusable(isFocusable, (err, data) => { windowClass.setFocusable(isFocusable, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to set the window to be focusable. Cause:' + JSON.stringify(err)); console.error('Failed to set the window to be focusable. Cause:' + JSON.stringify(err));
...@@ -2781,7 +2781,7 @@ Sets whether this window can gain focus. This API uses a promise to return the r ...@@ -2781,7 +2781,7 @@ Sets whether this window can gain focus. This API uses a promise to return the r
**Example** **Example**
```js ```js
var isFocusable= true; let isFocusable= true;
let promise = windowClass.setFocusable(isFocusable); let promise = windowClass.setFocusable(isFocusable);
promise.then((data)=> { promise.then((data)=> {
console.info('Succeeded in setting the window to be focusable. Data: ' + JSON.stringify(data)); console.info('Succeeded in setting the window to be focusable. Data: ' + JSON.stringify(data));
...@@ -2808,7 +2808,7 @@ Sets whether to keep the screen always on. This API uses an asynchronous callbac ...@@ -2808,7 +2808,7 @@ Sets whether to keep the screen always on. This API uses an asynchronous callbac
**Example** **Example**
```js ```js
var isKeepScreenOn = true; let isKeepScreenOn = true;
windowClass.setKeepScreenOn(isKeepScreenOn, (err, data) => { windowClass.setKeepScreenOn(isKeepScreenOn, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err));
...@@ -2841,7 +2841,7 @@ Sets whether to keep the screen always on. This API uses a promise to return the ...@@ -2841,7 +2841,7 @@ Sets whether to keep the screen always on. This API uses a promise to return the
**Example** **Example**
```js ```js
var isKeepScreenOn = true; let isKeepScreenOn = true;
let promise = windowClass.setKeepScreenOn(isKeepScreenOn); let promise = windowClass.setKeepScreenOn(isKeepScreenOn);
promise.then((data) => { promise.then((data) => {
console.info('Succeeded in setting the screen to be always on. Data: ' + JSON.stringify(data)); console.info('Succeeded in setting the screen to be always on. Data: ' + JSON.stringify(data));
...@@ -2938,7 +2938,7 @@ Sets whether this window is in privacy mode. This API uses an asynchronous callb ...@@ -2938,7 +2938,7 @@ Sets whether this window is in privacy mode. This API uses an asynchronous callb
**Example** **Example**
```js ```js
var isPrivacyMode = true; let isPrivacyMode = true;
windowClass.setPrivacyMode(isPrivacyMode, (err, data) => { windowClass.setPrivacyMode(isPrivacyMode, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(err)); console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(err));
...@@ -2972,7 +2972,7 @@ Sets whether this window is in privacy mode. This API uses a promise to return t ...@@ -2972,7 +2972,7 @@ Sets whether this window is in privacy mode. This API uses a promise to return t
**Example** **Example**
```js ```js
var isPrivacyMode = true; let isPrivacyMode = true;
let promise = windowClass.setPrivacyMode(isPrivacyMode); let promise = windowClass.setPrivacyMode(isPrivacyMode);
promise.then((data)=> { promise.then((data)=> {
console.info('Succeeded in setting the window to privacy mode. Data: ' + JSON.stringify(data)); console.info('Succeeded in setting the window to privacy mode. Data: ' + JSON.stringify(data));
...@@ -2996,7 +2996,7 @@ Sets whether to ignore this window during screen capturing or recording. ...@@ -2996,7 +2996,7 @@ Sets whether to ignore this window during screen capturing or recording.
| ------------- | ------- | ---- | -------------------- | | ------------- | ------- | ---- | -------------------- |
| isSkip | boolean | Yes | Whether to ignore the window. The default value is `false`.<br>The value `true` means that the window is ignored, and `false` means the opposite.<br>| | isSkip | boolean | Yes | Whether to ignore the window. The default value is `false`.<br>The value `true` means that the window is ignored, and `false` means the opposite.<br>|
```js ```js
var isSkip = true; let isSkip = true;
windowClass.setSnapshotSkip(isSkip); windowClass.setSnapshotSkip(isSkip);
``` ```
...@@ -3018,7 +3018,7 @@ Sets whether this window is touchable. This API uses an asynchronous callback to ...@@ -3018,7 +3018,7 @@ Sets whether this window is touchable. This API uses an asynchronous callback to
**Example** **Example**
```js ```js
var isTouchable = true; let isTouchable = true;
windowClass.setTouchable(isTouchable, (err, data) => { windowClass.setTouchable(isTouchable, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(err)); console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(err));
...@@ -3052,7 +3052,7 @@ Sets whether this window is touchable. This API uses a promise to return the res ...@@ -3052,7 +3052,7 @@ Sets whether this window is touchable. This API uses a promise to return the res
**Example** **Example**
```js ```js
var isTouchable = true; let isTouchable = true;
let promise = windowClass.setTouchable(isTouchable); let promise = windowClass.setTouchable(isTouchable);
promise.then((data)=> { promise.then((data)=> {
console.info('Succeeded in setting the window to be touchable. Data: ' + JSON.stringify(data)); console.info('Succeeded in setting the window to be touchable. Data: ' + JSON.stringify(data));
...@@ -3081,7 +3081,7 @@ Sets whether this window is forbidden to move in split-screen mode. This API use ...@@ -3081,7 +3081,7 @@ Sets whether this window is forbidden to move in split-screen mode. This API use
**Example** **Example**
```js ```js
var isForbidSplitMove = true; let isForbidSplitMove = true;
windowClass.setForbidSplitMove(isForbidSplitMove, (err, data) => { windowClass.setForbidSplitMove(isForbidSplitMove, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to forbid window moving in split screen mode. Cause:' + JSON.stringify(err)); console.error('Failed to forbid window moving in split screen mode. Cause:' + JSON.stringify(err));
...@@ -3117,7 +3117,7 @@ Sets whether this window is forbidden to move in split-screen mode. This API use ...@@ -3117,7 +3117,7 @@ Sets whether this window is forbidden to move in split-screen mode. This API use
**Example** **Example**
```js ```js
var isForbidSplitMove = true; let isForbidSplitMove = true;
let promise = windowClass.setForbidSplitMove(isForbidSplitMove); let promise = windowClass.setForbidSplitMove(isForbidSplitMove);
promise.then((data)=> { promise.then((data)=> {
console.info('Succeeded in forbidding window moving in split screen mode. Data: ' + JSON.stringify(data)); console.info('Succeeded in forbidding window moving in split screen mode. Data: ' + JSON.stringify(data));
...@@ -3333,7 +3333,7 @@ Sets the scale parameters for this window. ...@@ -3333,7 +3333,7 @@ Sets the scale parameters for this window.
**Example** **Example**
```js ```js
var obj : window.ScaleOptions = { let obj : window.ScaleOptions = {
x : 2.0, x : 2.0,
y : 1.0, y : 1.0,
pivotX = 0.5; pivotX = 0.5;
...@@ -3361,7 +3361,7 @@ Sets the rotation parameters for this window. ...@@ -3361,7 +3361,7 @@ Sets the rotation parameters for this window.
**Example** **Example**
```js ```js
var obj : window.RotateOptions = { let obj : window.RotateOptions = {
x : 1.0, x : 1.0,
y : 1.0, y : 1.0,
z : 45.0, z : 45.0,
...@@ -3390,7 +3390,7 @@ Sets the translation parameters for this window. ...@@ -3390,7 +3390,7 @@ Sets the translation parameters for this window.
**Example** **Example**
```js ```js
var obj : window.TranslateOptions = { let obj : window.TranslateOptions = {
x : 100.0, x : 100.0,
y : 0.0, y : 0.0,
z : 0.0 z : 0.0
...@@ -3431,7 +3431,7 @@ controller.animationForHidden = (context : window.TransitionContext) => { ...@@ -3431,7 +3431,7 @@ controller.animationForHidden = (context : window.TransitionContext) => {
context.completeTransition(true) context.completeTransition(true)
} }
}, () => { }, () => {
var obj : window.TranslateOptions = { let obj : window.TranslateOptions = {
x : 100.0, x : 100.0,
y : 0.0, y : 0.0,
z : 0.0 z : 0.0
...@@ -3495,7 +3495,7 @@ import Ability from '@ohos.application.Ability'; ...@@ -3495,7 +3495,7 @@ import Ability from '@ohos.application.Ability';
class myAbility extends Ability { class myAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
console.log('onWindowStageCreate'); console.log('onWindowStageCreate');
var windowClass = null; let windowClass = null;
windowStage.getMainWindow((err, data) => { windowStage.getMainWindow((err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err)); console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err));
...@@ -3530,7 +3530,7 @@ import Ability from '@ohos.application.Ability'; ...@@ -3530,7 +3530,7 @@ import Ability from '@ohos.application.Ability';
class myAbility extends Ability { class myAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
console.log('onWindowStageCreate'); console.log('onWindowStageCreate');
var windowClass = null; let windowClass = null;
let promise = windowStage.getMainWindow(); let promise = windowStage.getMainWindow();
promise.then((data)=> { promise.then((data)=> {
windowClass = data; windowClass = data;
...@@ -3565,8 +3565,8 @@ import Ability from '@ohos.application.Ability'; ...@@ -3565,8 +3565,8 @@ import Ability from '@ohos.application.Ability';
class myAbility extends Ability { class myAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
console.log('onWindowStageCreate'); console.log('onWindowStageCreate');
var windowClass = null; let windowClass = null;
windowStage.createSubWindow("mySubWindow", (err, data) => { windowStage.createSubWindow('mySubWindow', (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err)); console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err));
return; return;
...@@ -3607,8 +3607,8 @@ import Ability from '@ohos.application.Ability'; ...@@ -3607,8 +3607,8 @@ import Ability from '@ohos.application.Ability';
class myAbility extends Ability { class myAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
console.log('onWindowStageCreate'); console.log('onWindowStageCreate');
var windowClass = null; let windowClass = null;
let promise = windowStage.createSubWindow("mySubWindow"); let promise = windowStage.createSubWindow('mySubWindow');
promise.then((data)=> { promise.then((data)=> {
windowClass = data; windowClass = data;
console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data)); console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data));
...@@ -3641,7 +3641,7 @@ import Ability from '@ohos.application.Ability'; ...@@ -3641,7 +3641,7 @@ import Ability from '@ohos.application.Ability';
class myAbility extends Ability { class myAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
console.log('onWindowStageCreate'); console.log('onWindowStageCreate');
var windowClass = null; let windowClass = null;
windowStage.getSubWindow((err, data) => { windowStage.getSubWindow((err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to obtain the subwindow. Cause: ' + JSON.stringify(err)); console.error('Failed to obtain the subwindow. Cause: ' + JSON.stringify(err));
...@@ -3676,7 +3676,7 @@ import Ability from '@ohos.application.Ability'; ...@@ -3676,7 +3676,7 @@ import Ability from '@ohos.application.Ability';
class myAbility extends Ability { class myAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
console.log('onWindowStageCreate'); console.log('onWindowStageCreate');
var windowClass = null; let windowClass = null;
let promise = windowStage.getSubWindow(); let promise = windowStage.getSubWindow();
promise.then((data)=> { promise.then((data)=> {
windowClass = data; windowClass = data;
...@@ -3713,9 +3713,9 @@ class myAbility extends Ability { ...@@ -3713,9 +3713,9 @@ class myAbility extends Ability {
storage : LocalStorage storage : LocalStorage
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
this.storage = new LocalStorage(); this.storage = new LocalStorage();
this.storage.setOrCreate("storageSimpleProp",121); this.storage.setOrCreate('storageSimpleProp',121);
console.log('onWindowStageCreate'); console.log('onWindowStageCreate');
windowStage.loadContent("pages/page2",this.storage,(err, data) => { windowStage.loadContent('pages/page2',this.storage,(err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to load the content. Cause:' + JSON.stringify(err)); console.error('Failed to load the content. Cause:' + JSON.stringify(err));
return; return;
...@@ -3757,10 +3757,10 @@ class myAbility extends Ability { ...@@ -3757,10 +3757,10 @@ class myAbility extends Ability {
storage : LocalStorage storage : LocalStorage
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
this.storage = new LocalStorage(); this.storage = new LocalStorage();
this.storage.setOrCreate("storageSimpleProp",121); this.storage.setOrCreate('storageSimpleProp',121);
console.log('onWindowStageCreate'); console.log('onWindowStageCreate');
var windowClass = null; let windowClass = null;
let promise = windowStage.loadContent("pages/page2",this.storage); let promise = windowStage.loadContent('pages/page2',this.storage);
promise.then((data)=> { promise.then((data)=> {
windowClass = data; windowClass = data;
console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data));
...@@ -3795,7 +3795,7 @@ import Ability from '@ohos.application.Ability'; ...@@ -3795,7 +3795,7 @@ import Ability from '@ohos.application.Ability';
class myAbility extends Ability { class myAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
console.log('onWindowStageCreate'); console.log('onWindowStageCreate');
windowStage.loadContent("pages/page2", (err, data) => { windowStage.loadContent('pages/page2', (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to load the content. Cause:' + JSON.stringify(err)); console.error('Failed to load the content. Cause:' + JSON.stringify(err));
return; return;
...@@ -3963,7 +3963,7 @@ controller.animationForShown = (context : window.TransitionContext) => { ...@@ -3963,7 +3963,7 @@ controller.animationForShown = (context : window.TransitionContext) => {
iterations: 1, // Number of playback times. iterations: 1, // Number of playback times.
playMode: PlayMode.Normal // Animation playback mode. playMode: PlayMode.Normal // Animation playback mode.
}, () => { }, () => {
var obj : window.TranslateOptions = { let obj : window.TranslateOptions = {
x : 100.0, x : 100.0,
y : 0.0, y : 0.0,
z : 0.0 z : 0.0
...@@ -4014,7 +4014,7 @@ controller.animationForShown = (context : window.TransitionContext) => { ...@@ -4014,7 +4014,7 @@ controller.animationForShown = (context : window.TransitionContext) => {
context.completeTransition(true) context.completeTransition(true)
} }
}, () => { }, () => {
var obj : window.TranslateOptions = { let obj : window.TranslateOptions = {
x : 100.0, x : 100.0,
y : 0.0, y : 0.0,
z : 0.0 z : 0.0
...@@ -4060,7 +4060,7 @@ controller.animationForHidden = (context : window.TransitionContext) => { ...@@ -4060,7 +4060,7 @@ controller.animationForHidden = (context : window.TransitionContext) => {
context.completeTransition(true) context.completeTransition(true)
} }
}, () => { }, () => {
var obj : window.TranslateOptions = { let obj : window.TranslateOptions = {
x : 100.0, x : 100.0,
y : 0.0, y : 0.0,
z : 0.0 z : 0.0
......
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
The **WindowAnimationManager** module provides APIs to listen for application start/exit events and window minimization/maximization events and associate animations with these events. The **WindowAnimationManager** module provides APIs to listen for application start/exit events and window minimization/maximization events and associate animations with these events.
> **NOTE** > **NOTE**
>
> The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
> >
> The APIs provided by this module are system APIs. > The APIs provided by this module are system APIs.
...@@ -32,7 +31,7 @@ Before using other APIs of **windowAnimationManager**, you must call this API to ...@@ -32,7 +31,7 @@ Before using other APIs of **windowAnimationManager**, you must call this API to
**Example** **Example**
```js ```js
var controller = { let controller = {
onStartAppFromLauncher(startingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { onStartAppFromLauncher(startingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void {
console.log('onStartAppFromLauncher, the startingWindowTarget is: ' + startingWindowTarget); console.log('onStartAppFromLauncher, the startingWindowTarget is: ' + startingWindowTarget);
finishCallback.onAnimationFinish(); finishCallback.onAnimationFinish();
...@@ -89,8 +88,8 @@ Minimizes the window that displays the animation. This API uses an asynchronous ...@@ -89,8 +88,8 @@ Minimizes the window that displays the animation. This API uses an asynchronous
**Example** **Example**
```js ```js
var target: WindowAnimationTarget = undefined; let target: WindowAnimationTarget = undefined;
var controller = { let controller = {
onStartAppFromLauncher(startingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { onStartAppFromLauncher(startingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void {
console.log('onStartAppFromLauncher, the startingWindowTarget is: ' + startingWindowTarget); console.log('onStartAppFromLauncher, the startingWindowTarget is: ' + startingWindowTarget);
finishCallback.onAnimationFinish(); finishCallback.onAnimationFinish();
...@@ -128,7 +127,7 @@ var controller = { ...@@ -128,7 +127,7 @@ var controller = {
windowAnimationManager.setController(controller) windowAnimationManager.setController(controller)
var finishedCallback = null; let finishedCallback = null;
windowAnimationManager.minimizeWindowWithAnimation(target, (err, data) => { windowAnimationManager.minimizeWindowWithAnimation(target, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to minimize the window target. Cause: ' + JSON.stringify(err)); console.error('Failed to minimize the window target. Cause: ' + JSON.stringify(err));
...@@ -165,8 +164,8 @@ Minimizes the window that displays the animation. This API uses a promise to ret ...@@ -165,8 +164,8 @@ Minimizes the window that displays the animation. This API uses a promise to ret
**Example** **Example**
```js ```js
var target: WindowAnimationTarget = undefined; let target: WindowAnimationTarget = undefined;
var controller = { let controller = {
onStartAppFromLauncher(startingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { onStartAppFromLauncher(startingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void {
console.log('onStartAppFromLauncher, the startingWindowTarget is: ' + startingWindowTarget); console.log('onStartAppFromLauncher, the startingWindowTarget is: ' + startingWindowTarget);
finishCallback.onAnimationFinish(); finishCallback.onAnimationFinish();
......
...@@ -339,8 +339,8 @@ let strXml = ...@@ -339,8 +339,8 @@ let strXml =
let arrayBuffer = new ArrayBuffer(strXml.length); let arrayBuffer = new ArrayBuffer(strXml.length);
let bufView = new Uint8Array(arrayBuffer); let bufView = new Uint8Array(arrayBuffer);
let strLen = strXml.length; let strLen = strXml.length;
for (var i = 0; i < strLen; ++i) { for (var tmp = 0; tmp < strLen; ++tmp) {
bufView[i] = strXml.charCodeAt(i); bufView[tmp] = strXml.charCodeAt(tmp);
} }
let that = new xml.XmlPullParser(arrayBuffer); let that = new xml.XmlPullParser(arrayBuffer);
let arrTag = {}; let arrTag = {};
......
...@@ -54,7 +54,7 @@ You can create a subwindow, such as a dialog box, and set its properties. ...@@ -54,7 +54,7 @@ You can create a subwindow, such as a dialog box, and set its properties.
import window from '@ohos.window'; import window from '@ohos.window';
let windowClass = null; let windowClass = null;
// 1. Method 1: Create a subwindow. // Method 1: Create a subwindow.
window.create("subWindow", window.WindowType.TYPE_APP, (err, data) => { window.create("subWindow", window.WindowType.TYPE_APP, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err));
...@@ -63,7 +63,7 @@ You can create a subwindow, such as a dialog box, and set its properties. ...@@ -63,7 +63,7 @@ You can create a subwindow, such as a dialog box, and set its properties.
console.info('Succeeded in creating subWindow. Data: ' + JSON.stringify(data)); console.info('Succeeded in creating subWindow. Data: ' + JSON.stringify(data));
windowClass = data; windowClass = data;
}); });
// 1. Method 2: Obtain a subwindow. // Method 2: Obtain a subwindow.
window.getTopWindow((err, data) => { window.getTopWindow((err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to get the subWindow. Cause: ' + JSON.stringify(err)); console.error('Failed to get the subWindow. Cause: ' + JSON.stringify(err));
...@@ -72,7 +72,7 @@ You can create a subwindow, such as a dialog box, and set its properties. ...@@ -72,7 +72,7 @@ You can create a subwindow, such as a dialog box, and set its properties.
console.info('Succeeded in getting subWindow. Data: ' + JSON.stringify(data)); console.info('Succeeded in getting subWindow. Data: ' + JSON.stringify(data));
windowClass = data; windowClass = data;
}); });
// 1. Method 3: Find a subwindow. // Method 3: Find a subwindow.
window.find("subWindow", (err, data) => { window.find("subWindow", (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to find the subWindow. Cause: ' + JSON.stringify(err)); console.error('Failed to find the subWindow. Cause: ' + JSON.stringify(err));
...@@ -88,7 +88,7 @@ You can create a subwindow, such as a dialog box, and set its properties. ...@@ -88,7 +88,7 @@ You can create a subwindow, such as a dialog box, and set its properties.
After the subwindow is created, you can set its properties, such as the size, position, background color, and brightness. After the subwindow is created, you can set its properties, such as the size, position, background color, and brightness.
```js ```js
// 2. Move the subwindow. // Move the subwindow.
windowClass.moveTo(300, 300, (err, data) => { windowClass.moveTo(300, 300, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to move the window. Cause:' + JSON.stringify(err)); console.error('Failed to move the window. Cause:' + JSON.stringify(err));
...@@ -96,7 +96,7 @@ You can create a subwindow, such as a dialog box, and set its properties. ...@@ -96,7 +96,7 @@ You can create a subwindow, such as a dialog box, and set its properties.
} }
console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data));
}); });
// 2. Change the size of the subwindow. // Change the size of the subwindow.
windowClass.resetSize(500, 1000, (err, data) => { windowClass.resetSize(500, 1000, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); console.error('Failed to change the window size. Cause:' + JSON.stringify(err));
...@@ -111,14 +111,14 @@ You can create a subwindow, such as a dialog box, and set its properties. ...@@ -111,14 +111,14 @@ You can create a subwindow, such as a dialog box, and set its properties.
Call `loadContent` and `show` to load and display the content in the subwindow. Call `loadContent` and `show` to load and display the content in the subwindow.
```js ```js
// 3. Load the page content to the subwindow. // Load the page content to the subwindow.
windowClass.loadContent("pages/page2", (err, data) => { windowClass.loadContent("pages/page2", (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to load the content. Cause: ' + JSON.stringify(err)); console.error('Failed to load the content. Cause: ' + JSON.stringify(err));
return; return;
} }
console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data));
// 3. Show the subwindow. // Show the subwindow.
windowClass.show((err, data) => { windowClass.show((err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); console.error('Failed to show the window. Cause: ' + JSON.stringify(err));
...@@ -134,7 +134,7 @@ You can create a subwindow, such as a dialog box, and set its properties. ...@@ -134,7 +134,7 @@ You can create a subwindow, such as a dialog box, and set its properties.
When the subwindow is no longer needed, you can call `destroy` to destroy it. When the subwindow is no longer needed, you can call `destroy` to destroy it.
```js ```js
// 4. Destroy the subwindow when a click event outside the window is detected. // Destroy the subwindow when a click event outside the window is detected.
windowClass.on('touchOutside', () => { windowClass.on('touchOutside', () => {
console.info('touch outside'); console.info('touch outside');
windowClass.destroy((err, data) => { windowClass.destroy((err, data) => {
...@@ -167,7 +167,7 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -167,7 +167,7 @@ To create a better video watching and gaming experience, you can use the immersi
import window from '@ohos.window'; import window from '@ohos.window';
let mainWindowClass = null; let mainWindowClass = null;
// 1. Obtain the main window. // Obtain the main window.
window.getTopWindow((err, data) => { window.getTopWindow((err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to get the subWindow. Cause: ' + JSON.stringify(err)); console.error('Failed to get the subWindow. Cause: ' + JSON.stringify(err));
...@@ -185,7 +185,7 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -185,7 +185,7 @@ To create a better video watching and gaming experience, you can use the immersi
- Method 3: Call `setLayoutFullScreen` to enable the full-screen mode for the main window layout. Call `setSystemProperties` to set the opacity, background color, text color, and highlighted icon of the navigation bar and status bar to ensure that their display effect is consistent with that of the main window. - Method 3: Call `setLayoutFullScreen` to enable the full-screen mode for the main window layout. Call `setSystemProperties` to set the opacity, background color, text color, and highlighted icon of the navigation bar and status bar to ensure that their display effect is consistent with that of the main window.
```js ```js
// 2. Use method 1 to implement the immersive effect. // Use method 1 to implement the immersive effect.
let isFullScreen = true; let isFullScreen = true;
mainWindowClass.setFullScreen(isFullScreen, (err, data) => { mainWindowClass.setFullScreen(isFullScreen, (err, data) => {
if (err.code) { if (err.code) {
...@@ -194,7 +194,7 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -194,7 +194,7 @@ To create a better video watching and gaming experience, you can use the immersi
} }
console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data));
}); });
// 2. Use method 2 to implement the immersive effect. // Use method 2 to implement the immersive effect.
let names = []; let names = [];
mainWindowClass.setSystemBarEnable(names, (err, data) => { mainWindowClass.setSystemBarEnable(names, (err, data) => {
if (err.code) { if (err.code) {
...@@ -203,7 +203,7 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -203,7 +203,7 @@ To create a better video watching and gaming experience, you can use the immersi
} }
console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)); console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data));
}); });
// 2. Use method 3 to implement the immersive effect. // Use method 3 to implement the immersive effect.
let isLayoutFullScreen = true; let isLayoutFullScreen = true;
mainWindowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => { mainWindowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => {
if (err.code) { if (err.code) {
...@@ -236,14 +236,14 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -236,14 +236,14 @@ To create a better video watching and gaming experience, you can use the immersi
Call `loadContent` and `show` to load and display the content in the immersive window. Call `loadContent` and `show` to load and display the content in the immersive window.
```js ```js
// 3. Load the page content to the immersive window. // Load the page content to the immersive window.
mainWindowClass.loadContent("pages/page3", (err, data) => { mainWindowClass.loadContent("pages/page3", (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to load the content. Cause: ' + JSON.stringify(err)); console.error('Failed to load the content. Cause: ' + JSON.stringify(err));
return; return;
} }
console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data));
// 3. Show the immersive window. // Show the immersive window.
mainWindowClass.show((err, data) => { mainWindowClass.show((err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); console.error('Failed to show the window. Cause: ' + JSON.stringify(err));
......
...@@ -29,14 +29,17 @@ For easier maintenance and evolution, comply with the following principles when ...@@ -29,14 +29,17 @@ For easier maintenance and evolution, comply with the following principles when
1. Make sure the software comes from a clearly defined upstream community. 1. Make sure the software comes from a clearly defined upstream community.
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 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.
5. Place the software in an independent code repository or directory 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 PMC will deny the introduction of a piece of software without the confirmation of the SIG QA 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 law@openatom.org.
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".
- The inter-component dependencies between software introduction and dependency software are resolved via external_deps.
### Software Introduction Process ### Software Introduction Process
......
# Writing Instructions<a name="EN-US_TOPIC_0000001053707964"></a> # Writing Instructions
This document describes the writing specifications for contributing OpenHarmony documents. This document describes the writing specifications for contributing OpenHarmony documents.
## Naming Specifications<a name="section6823246189"></a> ## Naming Specifications
To submit a new document, create a new **.md** file in the **doc** directory of the project code on Gitee. The file name must be in the _xxx-xxx_**.md** format. To submit a new document, create a new **.md** file in the **doc** directory of the project code on Gitee. The file name must be in the _xxx-xxx_**.md** format.
For example, a document that describes writing specifications can be named **write-standard.md**. For example, a document that describes writing specifications can be named **write-standard.md**.
## Content Specifications<a name="section650663210183"></a> ## Content Specifications
The content should be concise and intuitive. Introductory documents describe principles, architecture, and design ideas in a concise manner, and operation documents describe key steps to help other developers. Chinese is preferred. It is recommended that both Chinese and English be supported. The OpenHarmony will be updated continuously to ensure the synchronization between Chinese and English. The content should be concise and intuitive. Introductory documents describe principles, architecture, and design ideas in a concise manner, and operation documents describe key steps to help other developers. Chinese is preferred. It is recommended that both Chinese and English be supported. The OpenHarmony will be updated continuously to ensure the synchronization between Chinese and English.
...@@ -73,7 +73,8 @@ Pictures used in **OpenHarmony\_DOCUMENTS/docs/quick-start/write-standard.md** ...@@ -73,7 +73,8 @@ Pictures used in **OpenHarmony\_DOCUMENTS/docs/quick-start/write-standard.md**
If a self-made picture is used, refer to the following figure to configure the color. The format can be **png**, **jpg**, **gif**, and so on. If a self-made picture is used, refer to the following figure to configure the color. The format can be **png**, **jpg**, **gif**, and so on.
**Figure 1** Example<a name="fig952595173513"></a> **Figure 1** Example
![](figures/example.png "example") ![](figures/example.png "example")
For screenshots, see the requirements below. If you need to highlight key information in the figure, add a red box or text remarks. For screenshots, see the requirements below. If you need to highlight key information in the figure, add a red box or text remarks.
...@@ -88,7 +89,7 @@ English font: Arial ...@@ -88,7 +89,7 @@ English font: Arial
Font size: 10 pt Font size: 10 pt
**Figure 2** <a name="fig1472123913217"></a> **Figure 2**
**Table** **Table**
...@@ -109,38 +110,11 @@ Output ...@@ -109,38 +110,11 @@ Output
**Table 1** Parameters **Table 1** Parameters
<a name="table163931041183019"></a> | Tables | Type | Note |
<table><thead align="left"><tr id="row1393134183014"><th class="cellrowborder" valign="top" width="33.33333333333333%" id="mcps1.2.4.1.1"><p id="p1539314418307"><a name="p1539314418307"></a><a name="p1539314418307"></a>Table</p> | ------ | :---------: | ---: |
</th> | first | standard | None |
<th class="cellrowborder" valign="top" width="33.33333333333333%" id="mcps1.2.4.1.2"><p id="p1339324120303"><a name="p1339324120303"></a><a name="p1339324120303"></a>Type</p> | second | outstanding | 5 |
</th> | third | inside | with |
<th class="cellrowborder" valign="top" width="33.33333333333333%" id="mcps1.2.4.1.3"><p id="p13932041133012"><a name="p13932041133012"></a><a name="p13932041133012"></a>Note</p>
</th>
</tr>
</thead>
<tbody><tr id="row1839304110309"><td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.1 "><p id="p4393174143014"><a name="p4393174143014"></a><a name="p4393174143014"></a>first</p>
</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.2 "><p id="p6393141133013"><a name="p6393141133013"></a><a name="p6393141133013"></a>standard</p>
</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.3 "><p id="p17393184112307"><a name="p17393184112307"></a><a name="p17393184112307"></a>None</p>
</td>
</tr>
<tr id="row1039318412306"><td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.1 "><p id="p113941541103012"><a name="p113941541103012"></a><a name="p113941541103012"></a>second</p>
</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.2 "><p id="p83941841153016"><a name="p83941841153016"></a><a name="p83941841153016"></a>outstanding</p>
</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.3 "><p id="p1539404114305"><a name="p1539404114305"></a><a name="p1539404114305"></a>5</p>
</td>
</tr>
<tr id="row6547101813118"><td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.1 "><p id="p35483184313"><a name="p35483184313"></a><a name="p35483184313"></a>third</p>
</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.2 "><p id="p1554821817318"><a name="p1554821817318"></a><a name="p1554821817318"></a>inside</p>
</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.3 "><p id="p15548201819310"><a name="p15548201819310"></a><a name="p15548201819310"></a>with</p>
</td>
</tr>
</tbody>
</table>
**Code** **Code**
......
...@@ -94,7 +94,7 @@ The Face_auth driver provides basic facial authentication capabilities for the U ...@@ -94,7 +94,7 @@ The Face_auth driver provides basic facial authentication capabilities for the U
| API | Description | | API | Description |
| ------------------------------------------------------------ | ------------------------ | | ------------------------------------------------------------ | ------------------------ |
| IExecutorCallback::OnResult(int32_t code, const std::vector<uint8_t>& extraInfo) | Called to return the operation result. | | IExecutorCallback::OnResult(int32_t code, const std::vector<uint8_t>& extraInfo) | Called to return the operation result. |
| IExecutorCallback::OnAcquireInfo(int32_t code, const std::vector<uint8_t>& extraInfo) | Called to return the interaction information about the operation process.| | IExecutorCallback::OnTip(int32_t code, const std::vector<uint8_t>& extraInfo) | Called to return the interaction information about the operation process.|
### How to Develop ### How to Develop
......
...@@ -108,7 +108,7 @@ The fingerprint_auth driver provides stable basic fingerprint authentication cap ...@@ -108,7 +108,7 @@ The fingerprint_auth driver provides stable basic fingerprint authentication cap
| API | Description | | API | Description |
| ------------------------------------------------------------ | ------------------------ | | ------------------------------------------------------------ | ------------------------ |
| IExecutorCallback::OnResult(int32_t code, const std::vector<uint8_t>& extraInfo) | Called to return the operation result. | | IExecutorCallback::OnResult(int32_t code, const std::vector<uint8_t>& extraInfo) | Called to return the operation result. |
| IExecutorCallback::OnAcquireInfo(int32_t code, const std::vector<uint8_t>& extraInfo) | Called to return the interaction information about the operation process.| | IExecutorCallback::OnTip(int32_t code, const std::vector<uint8_t>& extraInfo) | Called to return the interaction information about the operation process.|
### How to Develop ### How to Develop
......
...@@ -342,8 +342,8 @@ The development procedure is as follows: ...@@ -342,8 +342,8 @@ The development procedure is as follows:
} }
info.executorType = EXECUTOR_TYPE; info.executorType = EXECUTOR_TYPE;
info.remainTimes = infoRet.remainTimes; info.remainAttempts = infoRet.remainTimes;
info.freezingTime = infoRet.freezingTime; info.lockoutDuration = infoRet.freezingTime;
return HDF_SUCCESS; return HDF_SUCCESS;
} }
......
...@@ -53,7 +53,7 @@ The following uses the RTL8720 development board provided by Realtek as an examp ...@@ -53,7 +53,7 @@ The following uses the RTL8720 development board provided by Realtek as an examp
2. Create a directory for kernel adaptation and configure the **config.gni** file of the development board. 2. Create a directory for kernel adaptation and configure the **config.gni** file of the development board.
For example, to adapt the LiteOS-A kernel to the RTL8720 development board, configure the **device/board/realtek/rtl8720/liteo_a/config.gni** file as follows: For example, to adapt the LiteOS-A kernel to the RTL8720 development board, configure the **device/board/realtek/rtl8720/liteos_a/config.gni** file as follows:
```shell ```shell
# Kernel type, e.g. "linux", "liteos_a", "liteos_m". # Kernel type, e.g. "linux", "liteos_a", "liteos_m".
......
# Programming Language Runtime<a name="EN-US_TOPIC_0000001124628397"></a> # Programming Language Runtime
## Introduction<a name="section15963162310012"></a> ## Introduction
This subsystem provides the compilation and execution environment for programs developed with JavaScript, and C/C++, basic libraries that support the runtime, and the runtime-associated APIs, compilers, and auxiliary tools. Modules in this subsystem are classified based on the currently supported programming languages: JavaScript, and C/C++. Each module can be compiled independently and can be combined and separated based on development scenarios. The programming language runtime subsystem provides the compilation and execution environment for programs developed with JavaScript and C/C++. It also provides basic libraries that support the runtime, and runtime-associated APIs, compilers, and auxiliary tools. Modules in this subsystem are classified based on the currently supported programming languages: JavaScript and C/C++. Each module can be compiled independently and can be combined and separated based on development scenarios.
**Figure 1** Subsystem architecture<a name="fig4166312527"></a> This subsystem consists of the runtime, libraries, and compilers that support the running of JavaScript and C/C++ programs, and provides the basic libraries, APIs, JavaScript engine, and a toolchain that supports language compilation.
![](figures/subsystem-architecture-1.png "subsystem-architecture-1")
**Figure 1** Subsystem architecture
This subsystem consists of the runtime, libraries, and compilers that support the running of JavaScript, and C/C++ programs, and provides the basic libraries, API , JavaScript engine capability, and a toolchain that supports language compilation. ![](figures/subsystem-architecture-1.png "subsystem-architecture-1")
## Directory Structure<a name="section971210485617"></a> ## Directory Structure
``` ```
/prebuilts/mingw-w64/ohos/linux-x86_64 # cross-compilation toolchain for Linux platform /prebuilts/mingw-w64/ohos/linux-x86_64 # Cross-compilation toolchain for Linux platform
└── clang-mingw └── clang-mingw
├── bin ├── bin
├── lib ├── lib
...@@ -22,16 +23,18 @@ This subsystem consists of the runtime, libraries, and compilers that support th ...@@ -22,16 +23,18 @@ This subsystem consists of the runtime, libraries, and compilers that support th
└── x86_64-w64-mingw32 └── x86_64-w64-mingw32
``` ```
## Constraints<a name="section119744591305"></a> ## Constraints
1. You are not allowed to add or modify the APIs without permission. 1. You are not allowed to add or modify the APIs without permission.
2. The implementation of the JavaScript engine is restricted by the subsystem. There is no configuration item for external systems. 2. The implementation of the JavaScript engine is restricted by the subsystem. There is no configuration item for external systems.
## Usage<a name="section1312121216216"></a> ## Usage
Basic language capabilities are supported through library files. Some capabilities are integrated into Native, and JavaScript SDKs and integrated into DevEco Studio releases. For details about the usage, see the readme file of each module. Basic language capabilities are supported through library files. Some capabilities are integrated into Native, and JavaScript SDKs and integrated into DevEco Studio releases. For details about the usage, see the readme file of each module.
The following list shows the repositories of third-party software and precompilation toolchains that are referenced. ## Repositories Involved
The following list shows the repositories of third-party software and precompilation toolchains that are referenced:
[/third\_party/boost](https://gitee.com/openharmony/third_party_boost) [/third\_party/boost](https://gitee.com/openharmony/third_party_boost)
...@@ -39,8 +42,4 @@ The following list shows the repositories of third-party software and precompila ...@@ -39,8 +42,4 @@ The following list shows the repositories of third-party software and precompila
[/third\_party/jerryscript](https://gitee.com/openharmony/third_party_jerryscript) [/third\_party/jerryscript](https://gitee.com/openharmony/third_party_jerryscript)
[/third\_party/mingw-w64](https://gitee.com/openharmony/third_party_mingw-w64) [/third\_party/mingw-w64](https://gitee.com/openharmony/third_party_mingw-w64)
\ No newline at end of file
## Repositories Involved<a name="section1371113476307"></a>
**Programming language runtime subsystem**
...@@ -186,31 +186,29 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op ...@@ -186,31 +186,29 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op
| Subsystem| Sample| Introduction| Programming Language| | Subsystem| Sample| Introduction| Programming Language|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| ArkUI | MouseEvent | This sample simulates a minesweeper game that calls mouse event-related APIs.| eTS | | ArkUI | [MouseEvent](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/MouseEvent) | This sample simulates a minesweeper game that calls mouse event-related APIs.| eTS |
| ArkUI | Vibrator | This sample simulates the countdown scenario to show the use of the vibrator APIs.| eTS | | ArkUI | [Vibrator](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Vibrator) | This sample simulates the countdown scenario to show the use of the vibrator APIs.| eTS |
| DFX | FaultLogger | This sample illustrates how to obtain fault information of an application in eTS.| eTS | | DFX | [FaultLogger](https://gitee.com/openharmony/applications_app_samples/tree/master/DFX/FaultLogger) | This sample illustrates how to obtain fault information of an application in eTS.| eTS |
| ArkUI | Gallery | This sample demonstrates the functions of different components such as universal events, universal attributes, and gestures.| eTS | | ArkUI | [Gallery](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Gallery) | This sample demonstrates the functions of different components such as universal events, universal attributes, and gestures.| eTS |
| Graphics| JsWebGL | This sample shows how to use WebGL APIs to draw pentagrams and rectangles by invoking GPU resources.| JS | | Graphics| [JsWebGL](https://gitee.com/openharmony/applications_app_samples/tree/master/Graphics/JsWebGL) | This sample shows how to use WebGL APIs to draw pentagrams and rectangles by invoking GPU resources.| JS |
| ArkUI | Clock | This sample exemplifies how to implement a simple clock application using the eTS UI capability.| eTS | | ArkUI | [Clock](https://gitee.com/openharmony/applications_app_samples/tree/master/Preset/Clock) | This sample exemplifies how to implement a simple clock application using the eTS UI capability.| eTS |
| Network management| Http | This sample simulates Postman, which requires the input of an API address and outputs the data obtained, to show the use of the data request APIs.| eTS | | Network management| [Http](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Http) | This sample simulates Postman, which requires the input of an API address and outputs the data obtained, to show the use of the data request APIs.| eTS |
| ArkUI | FlishLight | This sample simulates a flashlight by changing the screen brightness. If the screen becomes brighter, the flashlight is turned on. If the screen becomes darker, the flashlight is turned off.| eTS | | Network management| [Socket](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket) | This sample demonstrates the application of Socket in network communication, including connection authentication and chat communication between two devices.| eTS |
| Network management| Socket | This sample demonstrates the application of Socket in network communication, including connection authentication and chat communication between two devices.| eTS | | Distributed data management| [DistributedRdb](https://gitee.com/openharmony/applications_app_samples/tree/master/data/DistributedRdb) | This sample shows how to add, delete, modify, query, and synchronize data in the distributed relational database with eTS.| eTS |
| Distributed data management| DistributedRdb | This sample shows how to add, delete, modify, query, and synchronize data in the distributed relational database with eTS.| eTS | | Ability| [BackgroundTaskManager](https://gitee.com/openharmony/applications_app_samples/tree/master/ResourcesSchedule/BackgroundTaskManager) | This sample simulates the download function. Being processed by the background task management, a download task can continue after the application exits. It stops until the download is complete.| eTS |
| Ability| BackgroundTaskManager | This sample simulates the download function. Being processed by the background task management, a download task can continue after the application exits. It stops until the download is complete.| eTS | | Ability| [BringApp](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/BringApp) | This sample uses the **FeatureAbility** APIs to start a system application based on the application's bundle name and ability name.| eTS |
| Ability| BringApp | This sample uses the **FeatureAbility** APIs to start a system application based on the application's bundle name and ability name.| eTS | | Media| [VideoPlayer](https://gitee.com/openharmony/applications_app_samples/tree/master/media/VideoPlayer) | This sample shows how to play a video using the **VideoPlayer** APIs in eTS. It also provides an ability that can be invoked by other applications to play the video.| eTS |
| Media| VideoPlayer | This sample shows how to play a video using the **VideoPlayer** APIs in eTS. It also provides an ability that can be invoked by other applications to play the video.| eTS | | Ability| [DistributeCalc](https://gitee.com/openharmony/applications_app_samples/tree/master/Preset/DistributeCalc) | This sample implements a simple calculator application using JS distributed features. The calculator can perform simple numerical calculations and start a remote calculator FA to perform collaborative calculation.| eTS |
| Ability| DistributeCalc | This sample implements a simple calculator application using JS distributed features. The calculator can perform simple numerical calculations and start a remote calculator FA to perform collaborative calculation.| eTS | | Web | [Browser](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Browser) | This sample uses the stage model and related APIs to show a simple browser.| eTS |
| Multimedia| JSRecorder | This sample shows how to implement audio recording and playback by calling media-related APIs.| eTS | | Ability| [DeviceUsageStatistics](https://gitee.com/openharmony/applications_app_samples/tree/master/device/DeviceUsageStatistics) | This sample shows the device usage statistics.| eTS |
| Web | Browser | This sample uses the stage model and related APIs to show a simple browser.| eTS | | ArkUI | [AdaptiveCapabilities](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/AdaptiveCapabilities) | This sample shows multi-device adaptation in eTS, including resource qualifiers, atomic layouts, and responsive layouts.| eTS |
| Ability| DeviceUsageStatistics | This sample shows the device usage statistics.| eTS | | ArkUI | [Game2048](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Game2048) | This sample shows how to develop a 2048 game using the **\<Grid>** component.| eTS |
| ArkUI | AdaptiveCapabilities | This sample shows multi-device adaptation in eTS, including resource qualifiers, atomic layouts, and responsive layouts.| eTS | | Window Manager| [Window](https://gitee.com/openharmony/applications_app_samples/tree/master/Graphics/Window) | This sample shows how to create a window, display an application over another application in the form of a floating window, and display an application on split screens.| eTS |
| ArkUI | Game2048 | This sample shows how to develop a 2048 game using the **\<Grid>** component.| eTS | | Distributed data management| [Preference](https://gitee.com/openharmony/applications_app_samples/tree/master/data/Preferences) | This sample shows the theme switching function of preferences.| eTS |
| Window Manager| Window | This sample shows how to create a window, display an application over another application in the form of a floating window, and display an application on split screens.| eTS | | ArkUI | [NativeAPI](https://gitee.com/openharmony/applications_app_samples/tree/master/Native/NativeAPI) | This sample shows how to call C++ APIs in eTS and how C++ APIs call back JS APIs to play the Gomoku game. The native APIs implement the calculation logic, and eTS implements UI rendering and re-rendering.| eTS/C++ |
| Distributed data management| Preference | This sample shows the theme switching function of preferences.| eTS | | Globalization| [International](https://gitee.com/openharmony/applications_app_samples/tree/master/common/International) | This sample shows how to use APIs related to i18n, intl, and resourceManager in eTS to set the system language, region, time, and time zone. It also provides locale setting examples.| eTS |
| ArkUI | NativeAPI | This sample shows how to call C++ APIs in eTS and how C++ APIs call back JS APIs to play the Gomoku game. The native APIs implement the calculation logic, and eTS implements UI rendering and re-rendering.| eTS/C++ |
| Globalization| International | This sample shows how to use APIs related to i18n, intl, and resourceManager in eTS to set the system language, region, time, and time zone. It also provides locale setting examples.| eTS | For more information, visit [Samples](https://gitee.com/openharmony/applications_app_samples).
For more information, visit [Samples](https://gitee.com/openharmony/app_samples).
## Resolved Issues ## Resolved Issues
...@@ -229,4 +227,3 @@ For more information, visit [Samples](https://gitee.com/openharmony/app_samples) ...@@ -229,4 +227,3 @@ For more information, visit [Samples](https://gitee.com/openharmony/app_samples)
| ------------------------------------------------------------ | ---------------------------------------------------------- | ------------------------------------------------------------ | ------------ | | ------------------------------------------------------------ | ---------------------------------------------------------- | ------------------------------------------------------------ | ------------ |
| [I4Z3G9](https://gitee.com/openharmony/graphic_graphic_2d/issues/I4Z3G9) | [RK3568] Screen flickering occurs when the secondary window is opened in the immersive primary window.| Developer experience is affected. | 2022-06-15 | | [I4Z3G9](https://gitee.com/openharmony/graphic_graphic_2d/issues/I4Z3G9) | [RK3568] Screen flickering occurs when the secondary window is opened in the immersive primary window.| Developer experience is affected. | 2022-06-15 |
| [I59M4Q](https://gitee.com/openharmony/developtools_hdc/issues/I59M4Q) | There is a low probability that the device is disconnected when hdc_std of API version 9 is used to connect to the device. | This issue occurs at a low probability (less than 1/30). It can be resolved by restarting the IDE or hdc_std.| 2022-06-30 | | [I59M4Q](https://gitee.com/openharmony/developtools_hdc/issues/I59M4Q) | There is a low probability that the device is disconnected when hdc_std of API version 9 is used to connect to the device. | This issue occurs at a low probability (less than 1/30). It can be resolved by restarting the IDE or hdc_std.| 2022-06-30 |
| [I54D32](https://gitee.com/openharmony/multimedia_camera_standard/issues/I54D32) | [RK3568] A black screen is displayed when the camera has been recording videos for multiple consecutive times. | Developer experience is affected. | 2022-06-15 |
# JS API Changes of the Distributed Scheduler Subsystem
The table below lists the APIs changes of the distributed scheduler subsystem in OpenHarmony 3.2 Beta1 over OpenHarmony 3.1 Release.
## API Changes
| Module| Class| Method/Attribute/Enumeration/Constant| Change Type|
|---|---|---|---|
| ohos.continuation.continuationManager | continuationManager | on(type: "deviceConnect", token: number, callback: Callback\<Array\<ContinuationResult>>): void; | Added|
| ohos.continuation.continuationManager | continuationManager | off(type: "deviceConnect", token: number): void; | Added|
| ohos.continuation.continuationManager | continuationManager | on(type: "deviceDisconnect", token: number, callback: Callback\<Array\<string>>): void; | Added|
| ohos.continuation.continuationManager | continuationManager | off(type: "deviceDisconnect", token: number): void; | Added|
| ohos.continuation.continuationManager | continuationManager | on(type: "deviceConnect", callback: Callback\<ContinuationResult>): void; | Deprecated|
| ohos.continuation.continuationManager | continuationManager | off(type: "deviceConnect", callback?: Callback\<ContinuationResult>): void; | Deprecated|
| ohos.continuation.continuationManager | continuationManager | on(type: "deviceDisconnect", callback: Callback\<string>): void; | Deprecated|
| ohos.continuation.continuationManager | continuationManager | off(type: "deviceDisconnect", callback?: Callback\<string>): void; | Deprecated|
...@@ -6,9 +6,10 @@ The table below lists the APIs changes of the web subsystem in OpenHarmony 3.2 B ...@@ -6,9 +6,10 @@ The table below lists the APIs changes of the web subsystem in OpenHarmony 3.2 B
| Module| Class| Function| Change Type| | Module| Class| Function| Change Type|
|---|---|---|---| |---|---|---|---|
| web | WebAttribute | "onShowFileSelector(callback: (event?: { result: FileSelectorResult, fileSelector: FileSelectorParam }) => boolean): WebAttribute;" | Added| | web | WebAttribute | onShowFileSelector(callback: (event?: { result: FileSelectorResult, fileSelector: FileSelectorParam }) => boolean): WebAttribute; | Added|
| web | WebAttribute | webDebuggingAccess(webDebuggingAccess: boolean): WebAttribute; | Added| | web | WebAttribute | webDebuggingAccess(webDebuggingAccess: boolean): WebAttribute; | Added|
| web | WebAttribute | fileFromUrlAccess(fileFromUrlAccess: boolean): WebAttribute; | Added| | web | WebAttribute | fileFromUrlAccess(fileFromUrlAccess: boolean): WebAttribute; | Added|
| web | WebAttribute | onRenderExited(callback: (event?: { renderExitReason: RenderExitReason }) => void): WebAttribute; | Added|
| web | WebController | getCookieManager() : WebCookie | Added| | web | WebController | getCookieManager() : WebCookie | Added|
| web | WebCookie | deleteExpiredCookie(): void; | Added| | web | WebCookie | deleteExpiredCookie(): void; | Added|
| web | WebCookie | deleteSessionCookie(): void; | Added| | web | WebCookie | deleteSessionCookie(): void; | Added|
...@@ -22,6 +23,7 @@ The table below lists the APIs changes of the web subsystem in OpenHarmony 3.2 B ...@@ -22,6 +23,7 @@ The table below lists the APIs changes of the web subsystem in OpenHarmony 3.2 B
| web | WebCookie | isFileURICookieAllowed(): boolean; | Added| | web | WebCookie | isFileURICookieAllowed(): boolean; | Added|
| web | WebCookie | isThirdPartyCookieAllowed(): boolean; | Added| | web | WebCookie | isThirdPartyCookieAllowed(): boolean; | Added|
| web | WebCookie | isCookieAllowed(): boolean; | Added| | web | WebCookie | isCookieAllowed(): boolean; | Added|
| web | WebCookie | setCookie(url: string, value: string): boolean; | Added|
| web | FileSelectorResult | handleFileList(fileList: Array\<string>): void; | Added| | web | FileSelectorResult | handleFileList(fileList: Array\<string>): void; | Added|
| web | FileSelectorResult | constructor(); | Added| | web | FileSelectorResult | constructor(); | Added|
| web | FileSelectorParam | isCapture(): boolean; | Added| | web | FileSelectorParam | isCapture(): boolean; | Added|
......
...@@ -12,4 +12,4 @@ ...@@ -12,4 +12,4 @@
- [三四方库使用常见问题](faqs-third-party-library.md) - [三四方库使用常见问题](faqs-third-party-library.md)
- [IDE使用常见问题](faqs-ide.md) - [IDE使用常见问题](faqs-ide.md)
- [hdc_std命令使用常见问题](faqs-hdc-std.md) - [hdc_std命令使用常见问题](faqs-hdc-std.md)
- [开发板](faqs-development-board.md) - [开发板使用常见问题](faqs-development-board.md)
...@@ -789,7 +789,7 @@ definePermission仅支持系统应用配置,三方应用配置不生效。 ...@@ -789,7 +789,7 @@ definePermission仅支持系统应用配置,三方应用配置不生效。
| 属性名称 | 含义 | 数据类型 | 是否可缺省 | | 属性名称 | 含义 | 数据类型 | 是否可缺省 |
| ----------------------- | ------------------------------------------------------------ | -------- | ---------- | | ----------------------- | ------------------------------------------------------------ | -------- | ---------- |
| name | 标识权限的名称 | 字符串 | 不可缺省 | | name | 标识权限的名称 | 字符串 | 不可缺省 |
| grantMode | 标识权限的授予方式,该标签可缺省,缺省值为system_grant。<br />授予模式如下:<br />system_grant:安装后系统自动授予该权限。<br />user_grant:使用时动态申请,用户授权后才可使用。 | 字符串 | 可缺省 | | grantMode | 标识权限的授予方式,该标签可缺省,缺省值为system_grant。<br />授予模式如下:<br />system_grant:安装后系统自动授予该权限。<br />user_grant:使用时动态申请,用户授权后才可使用。 | 字符串 | 可缺省 |
| availableLevel | 标识权限限制门限。可选值为"system_code","system_basic","normal",该标签有缺省值,缺省值为normal。权限范围如下:<br />system_core:系统核心权限。<br />system_basic:系统基础权限。<br />normal:普通权限。所有应用允许申请的权限 | 字符串 | 可缺省 | | availableLevel | 标识权限限制门限。可选值为"system_code","system_basic","normal",该标签有缺省值,缺省值为normal。权限范围如下:<br />system_core:系统核心权限。<br />system_basic:系统基础权限。<br />normal:普通权限。所有应用允许申请的权限 | 字符串 | 可缺省 |
| provisionEnable | 标识权限是否支持证书方式申请权限,包括高级别的权限,该标签有缺省值,缺省值为true。配置为true标识需要开发者可以通过provision方式申请权限。 | 布尔值 | 可缺省 | | provisionEnable | 标识权限是否支持证书方式申请权限,包括高级别的权限,该标签有缺省值,缺省值为true。配置为true标识需要开发者可以通过provision方式申请权限。 | 布尔值 | 可缺省 |
| distributedSceneEnabled | 标识权限是否支持分布式场景下使用该权限,该标签有缺省值,缺省值为false。 | 布尔值 | 可缺省 | | distributedSceneEnabled | 标识权限是否支持分布式场景下使用该权限,该标签有缺省值,缺省值为false。 | 布尔值 | 可缺省 |
......
# 接口 # 接口
- [开发说明](development-intro.md) - [开发说明](development-intro.md)
- Ability框架 - Ability框架
- FA模型 - FA模型
- [@ohos.ability.featureAbility (FeatureAbility模块)](js-apis-featureAbility.md) - [@ohos.ability.featureAbility (FeatureAbility模块)](js-apis-featureAbility.md)
- [@ohos.ability.particleAbility (particleAbility模块)](js-apis-particleAbility.md) - [@ohos.ability.particleAbility (particleAbility模块)](js-apis-particleAbility.md)
...@@ -28,8 +25,6 @@ ...@@ -28,8 +25,6 @@
- application/[FormExtensionContext (FormExtensionContext)](js-apis-formextensioncontext.md) - application/[FormExtensionContext (FormExtensionContext)](js-apis-formextensioncontext.md)
- application/[PermissionRequestResult (PermissionRequestResult)](js-apis-permissionrequestresult.md) - application/[PermissionRequestResult (PermissionRequestResult)](js-apis-permissionrequestresult.md)
- application/[ServiceExtensionContext (ServiceExtensionContext)](js-apis-service-extension-context.md) - application/[ServiceExtensionContext (ServiceExtensionContext)](js-apis-service-extension-context.md)
- [InputMethodExtensionAbility (InputMethodExtensionAbility)](js-apis-inputmethod-extension-ability.md)
- [InputMethodExtensionContext (InputMethodExtensionContext)](js-apis-inputmethod-extension-context.md)
- 通用 - 通用
- [@ohos.ability.dataUriUtils (DataUriUtils模块)](js-apis-DataUriUtils.md) - [@ohos.ability.dataUriUtils (DataUriUtils模块)](js-apis-DataUriUtils.md)
- [@ohos.ability.errorCode (ErrorCode)](js-apis-ability-errorCode.md) - [@ohos.ability.errorCode (ErrorCode)](js-apis-ability-errorCode.md)
...@@ -65,14 +60,12 @@ ...@@ -65,14 +60,12 @@
- application/[shellCmdResult (ShellCmdResult)](js-apis-application-shellCmdResult.md) - application/[shellCmdResult (ShellCmdResult)](js-apis-application-shellCmdResult.md)
- continuation/[ContinuationResult (ContinuationResult)](js-apis-continuation-continuationResult.md) - continuation/[ContinuationResult (ContinuationResult)](js-apis-continuation-continuationResult.md)
- 公共事件与通知 - 公共事件与通知
- [@ohos.commonEvent (公共事件模块)](js-apis-commonEvent.md) - [@ohos.commonEvent (公共事件模块)](js-apis-commonEvent.md)
- [@ohos.events.emitter (Emitter)](js-apis-emitter.md) - [@ohos.events.emitter (Emitter)](js-apis-emitter.md)
- [@ohos.notification (Notification模块)](js-apis-notification.md) - [@ohos.notification (Notification模块)](js-apis-notification.md)
- [@ohos.reminderAgent (后台代理提醒)](js-apis-reminderAgent.md) - [@ohos.reminderAgent (后台代理提醒)](js-apis-reminderAgent.md)
- application/[EventHub (EventHub)](js-apis-eventhub.md) - application/[EventHub (EventHub)](js-apis-eventhub.md)
- 应用程序包管理 - 应用程序包管理
- [@ohos.bundle (Bundle模块)](js-apis-Bundle.md) - [@ohos.bundle (Bundle模块)](js-apis-Bundle.md)
- [@ohos.bundle.defaultAppManager (Bundle模块)](js-apis-bundle-defaultAppManager.md) - [@ohos.bundle.defaultAppManager (Bundle模块)](js-apis-bundle-defaultAppManager.md)
- [@ohos.bundle.innerBundleManager (innerBundleManager模块(JS端SDK接口))](js-apis-Bundle-InnerBundleManager.md) - [@ohos.bundle.innerBundleManager (innerBundleManager模块(JS端SDK接口))](js-apis-Bundle-InnerBundleManager.md)
...@@ -97,14 +90,12 @@ ...@@ -97,14 +90,12 @@
- bundle/[ShortcutInfo (ShortcutInfo)](js-apis-bundle-ShortcutInfo.md) - bundle/[ShortcutInfo (ShortcutInfo)](js-apis-bundle-ShortcutInfo.md)
- bundle/[PackInfo (PackInfo)](js-apis-bundle-PackInfo.md) - bundle/[PackInfo (PackInfo)](js-apis-bundle-PackInfo.md)
- UI界面 - UI界面
- [@ohos.animator (动画)](js-apis-animator.md) - [@ohos.animator (动画)](js-apis-animator.md)
- [@ohos.mediaquery (媒体查询)](js-apis-mediaquery.md) - [@ohos.mediaquery (媒体查询)](js-apis-mediaquery.md)
- [@ohos.prompt (弹窗)](js-apis-prompt.md) - [@ohos.prompt (弹窗)](js-apis-prompt.md)
- [@ohos.router (页面路由)](js-apis-router.md) - [@ohos.router (页面路由)](js-apis-router.md)
- [@ohos.uiAppearance(用户界面外观)](js-apis-uiappearance.md) - [@ohos.uiAppearance(用户界面外观)](js-apis-uiappearance.md)
- 图形图像 - 图形图像
- [@ohos.animation.windowAnimationManager (窗口动画管理)](js-apis-windowAnimationManager.md) - [@ohos.animation.windowAnimationManager (窗口动画管理)](js-apis-windowAnimationManager.md)
- [@ohos.display (屏幕属性)](js-apis-display.md) - [@ohos.display (屏幕属性)](js-apis-display.md)
- [@ohos.effectKit (图像效果)](js-apis-effectKit.md) - [@ohos.effectKit (图像效果)](js-apis-effectKit.md)
...@@ -115,38 +106,33 @@ ...@@ -115,38 +106,33 @@
- [webgl (WebGL)](js-apis-webgl.md) - [webgl (WebGL)](js-apis-webgl.md)
- [webgl2 (WebGL2)](js-apis-webgl2.md) - [webgl2 (WebGL2)](js-apis-webgl2.md)
- 媒体 - 媒体
- [@ohos.multimedia.audio (音频管理)](js-apis-audio.md) - [@ohos.multimedia.audio (音频管理)](js-apis-audio.md)
- [@ohos.multimedia.camera (相机管理)](js-apis-camera.md) - [@ohos.multimedia.camera (相机管理)](js-apis-camera.md)
- [@ohos.multimedia.image (图片处理)](js-apis-image.md) - [@ohos.multimedia.image (图片处理)](js-apis-image.md)
- [@ohos.multimedia.media (媒体服务)](js-apis-media.md) - [@ohos.multimedia.media (媒体服务)](js-apis-media.md)
- [@ohos.multimedia.medialibrary (媒体库管理)](js-apis-medialibrary.md)
- 资源管理 - 资源管理
- [@ohos.i18n (国际化-I18n)](js-apis-i18n.md) - [@ohos.i18n (国际化-I18n)](js-apis-i18n.md)
- [@ohos.intl (国际化-Intl)](js-apis-intl.md) - [@ohos.intl (国际化-Intl)](js-apis-intl.md)
- [@ohos.resourceManager (资源管理)](js-apis-resource-manager.md) - [@ohos.resourceManager (资源管理)](js-apis-resource-manager.md)
- 资源调度 - 资源调度
- [@ohos.backgroundTaskManager (后台任务管理)](js-apis-backgroundTaskManager.md) - [@ohos.backgroundTaskManager (后台任务管理)](js-apis-backgroundTaskManager.md)
- [@ohos.distributedMissionManager (分布式任务管理)](js-apis-distributedMissionManager.md) - [@ohos.distributedMissionManager (分布式任务管理)](js-apis-distributedMissionManager.md)
- [@ohos.workScheduler (延迟任务调度)](js-apis-workScheduler.md) - [@ohos.workScheduler (延迟任务调度)](js-apis-workScheduler.md)
- [@ohos.WorkSchedulerExtensionAbility (延迟任务调度回调)](js-apis-WorkSchedulerExtensionAbility.md) - [@ohos.WorkSchedulerExtensionAbility (延迟任务调度回调)](js-apis-WorkSchedulerExtensionAbility.md)
- 定制管理 - 定制管理
- [@ohos.configPolicy (配置策略)](js-apis-config-policy.md) - [@ohos.configPolicy (配置策略)](js-apis-config-policy.md)
- [@ohos.enterpriseDeviceManager (企业设备管理)](js-apis-enterprise-device-manager.md)
- [@ohos.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)](js-apis-EnterpriseAdminExtensionAbility.md) - [@ohos.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)](js-apis-EnterpriseAdminExtensionAbility.md)
- [@ohos.enterpriseDeviceManager (企业设备管理)](js-apis-enterprise-device-manager.md)
- enterpriseDeviceManager/[DeviceSettingsManager(设备设置管理)](js-apis-enterpriseDeviceManager-DeviceSettingsManager.md) - enterpriseDeviceManager/[DeviceSettingsManager(设备设置管理)](js-apis-enterpriseDeviceManager-DeviceSettingsManager.md)
- 安全 - 安全
- [@ohos.abilityAccessCtrl (访问控制管理)](js-apis-abilityAccessCtrl.md) - [@ohos.abilityAccessCtrl (访问控制管理)](js-apis-abilityAccessCtrl.md)
- [@ohos.privacyManager (隐私管理)](js-apis-privacyManager.md) - [@ohos.privacyManager (隐私管理)](js-apis-privacyManager.md)
- [@ohos.security.cryptoFramework (加解密算法库框架)](js-apis-cryptoFramework.md)
- [@ohos.security.huks (通用密钥库系统)](js-apis-huks.md) - [@ohos.security.huks (通用密钥库系统)](js-apis-huks.md)
- [@ohos.userIAM.userAuth (用户认证)](js-apis-useriam-userauth.md)
- [@ohos.userIAM.faceAuth (人脸认证)](js-apis-useriam-faceauth.md) - [@ohos.userIAM.faceAuth (人脸认证)](js-apis-useriam-faceauth.md)
- [@ohos.userIAM.userAuth (用户认证)](js-apis-useriam-userauth.md)
- [@system.cipher (加密算法)](js-apis-system-cipher.md) - [@system.cipher (加密算法)](js-apis-system-cipher.md)
- 数据管理 - 数据管理
- [@ohos.data.dataAbility (DataAbility谓词)](js-apis-data-ability.md) - [@ohos.data.dataAbility (DataAbility谓词)](js-apis-data-ability.md)
- [@ohos.data.dataShare (数据共享)](js-apis-data-dataShare.md) - [@ohos.data.dataShare (数据共享)](js-apis-data-dataShare.md)
- [@ohos.data.dataSharePredicates (数据共享谓词)](js-apis-data-dataSharePredicates.md) - [@ohos.data.dataSharePredicates (数据共享谓词)](js-apis-data-dataSharePredicates.md)
...@@ -158,49 +144,47 @@ ...@@ -158,49 +144,47 @@
- [@ohos.data.ValuesBucket (数据集)](js-apis-data-ValuesBucket.md) - [@ohos.data.ValuesBucket (数据集)](js-apis-data-ValuesBucket.md)
- data/rdb/[resultSet (结果集)](js-apis-data-resultset.md) - data/rdb/[resultSet (结果集)](js-apis-data-resultset.md)
- 文件管理 - 文件管理
- [@ohos.document (文件交互)](js-apis-document.md) - [@ohos.document (文件交互)](js-apis-document.md)
- [@ohos.environment (目录环境能力)](js-apis-environment.md) - [@ohos.environment (目录环境能力)](js-apis-environment.md)
- [@ohos.fileio (文件管理)](js-apis-fileio.md) - [@ohos.fileio (文件管理)](js-apis-fileio.md)
- [@ohos.fileManager (公共文件访问与管理)](js-apis-filemanager.md) - [@ohos.fileManager (公共文件访问与管理)](js-apis-filemanager.md)
- [@ohos.filemanagement.userfile_manager (用户数据管理)](js-apis-userfilemanager.md)
- [@ohos.multimedia.medialibrary (媒体库管理)](js-apis-medialibrary.md)
- [@ohos.securityLabel (数据标签)](js-apis-securityLabel.md)
- [@ohos.statfs (statfs)](js-apis-statfs.md) - [@ohos.statfs (statfs)](js-apis-statfs.md)
- [@ohos.storageStatistics (应用空间统计)](js-apis-storage-statistics.md) - [@ohos.storageStatistics (应用空间统计)](js-apis-storage-statistics.md)
- [@ohos.volumeManager (卷管理)](js-apis-volumemanager.md) - [@ohos.volumeManager (卷管理)](js-apis-volumemanager.md)
- [@ohos.securityLabel (数据标签)](js-apis-securityLabel.md)
- 电话服务 - 电话服务
- [@ohos.contact (联系人)](js-apis-contact.md) - [@ohos.contact (联系人)](js-apis-contact.md)
- [@ohos.telephony.call (拨打电话)](js-apis-call.md) - [@ohos.telephony.call (拨打电话)](js-apis-call.md)
- [@ohos.telephony.data (蜂窝数据)](js-apis-telephony-data.md)
- [@ohos.telephony.observer (observer)](js-apis-observer.md) - [@ohos.telephony.observer (observer)](js-apis-observer.md)
- [@ohos.telephony.radio (网络搜索)](js-apis-radio.md) - [@ohos.telephony.radio (网络搜索)](js-apis-radio.md)
- [@ohos.telephony.sim (SIM卡管理)](js-apis-sim.md) - [@ohos.telephony.sim (SIM卡管理)](js-apis-sim.md)
- [@ohos.telephony.sms (短信服务)](js-apis-sms.md) - [@ohos.telephony.sms (短信服务)](js-apis-sms.md)
- [@ohos.telephony.data (蜂窝数据)](js-apis-telephony-data.md)
- 网络管理 - 网络管理
- [@ohos.net.connection (网络连接管理)](js-apis-net-connection.md) - [@ohos.net.connection (网络连接管理)](js-apis-net-connection.md)
- [@ohos.net.statistics (网络流量管理)](js-apis-net-statistics.md)
- [@ohos.net.policy (网络策略管理)](js-apis-net-policy.md)
- [@ohos.net.ethernet (以太网连接管理)](js-apis-net-ethernet.md) - [@ohos.net.ethernet (以太网连接管理)](js-apis-net-ethernet.md)
- [@ohos.net.sharing (网络共享管理)](js-apis-net-sharing.md)
- [@ohos.net.http (数据请求)](js-apis-http.md) - [@ohos.net.http (数据请求)](js-apis-http.md)
- [@ohos.request (上传下载)](js-apis-request.md) - [@ohos.net.policy (网络策略管理)](js-apis-net-policy.md)
- [@ohos.net.sharing (网络共享管理)](js-apis-net-sharing.md)
- [@ohos.net.socket (Socket连接)](js-apis-socket.md) - [@ohos.net.socket (Socket连接)](js-apis-socket.md)
- [@ohos.net.webSocket (WebSocket连接)](js-apis-webSocket.md) - [@ohos.net.statistics (网络流量管理)](js-apis-net-statistics.md)
- [@ohos.net.tlsSocket (TLSSocket连接)](js-apis-tlsSocket.md) - [@ohos.net.tlsSocket (TLSSocket连接)](js-apis-tlsSocket.md)
- [@ohos.net.webSocket (WebSocket连接)](js-apis-webSocket.md)
- [@ohos.request (上传下载)](js-apis-request.md)
- 通信与连接 - 通信与连接
- [@ohos.bluetooth (蓝牙)](js-apis-bluetooth.md) - [@ohos.bluetooth (蓝牙)](js-apis-bluetooth.md)
- [@ohos.connectedTag (有源标签)](js-apis-connectedTag.md) - [@ohos.connectedTag (有源标签)](js-apis-connectedTag.md)
- [@ohos.nfc.cardEmulation (标准NFC-cardEmulation)](js-apis-cardEmulation.md) - [@ohos.nfc.cardEmulation (标准NFC-cardEmulation)](js-apis-cardEmulation.md)
- [@ohos.nfc.controller (标准NFC)](js-apis-nfcController.md) - [@ohos.nfc.controller (标准NFC)](js-apis-nfcController.md)
- [@ohos.nfc.tag (标准NFC-Tag)](js-apis-nfcTag.md) - [@ohos.nfc.tag (标准NFC-Tag)](js-apis-nfcTag.md)
- [@ohos.nfc.tag (标准NFC-Tag Nfc 技术)](js-apis-nfctech.md)
- [@ohos.nfc.tag (标准NFC-Tag TagSession)](js-apis-tagSession.md)
- [@ohos.rpc (RPC通信)](js-apis-rpc.md) - [@ohos.rpc (RPC通信)](js-apis-rpc.md)
- [@ohos.wifi (WLAN)](js-apis-wifi.md) - [@ohos.wifi (WLAN)](js-apis-wifi.md)
- [@ohos.wifiext (WLAN)](js-apis-wifiext.md) - [@ohos.wifiext (WLAN)](js-apis-wifiext.md)
- tag/[nfctech (标准NFC-Tag Nfc 技术)](js-apis-nfctech.md)
- tag/[tagSession (标准NFC-Tag TagSession)](js-apis-tagSession.md)
- 系统基础能力 - 系统基础能力
- [@ohos.accessibility (辅助功能)](js-apis-accessibility.md) - [@ohos.accessibility (辅助功能)](js-apis-accessibility.md)
- [@ohos.accessibility.config (系统辅助功能配置)](js-apis-accessibility-config.md) - [@ohos.accessibility.config (系统辅助功能配置)](js-apis-accessibility-config.md)
- [@ohos.faultLogger (故障日志获取)](js-apis-faultLogger.md) - [@ohos.faultLogger (故障日志获取)](js-apis-faultLogger.md)
...@@ -211,8 +195,10 @@ ...@@ -211,8 +195,10 @@
- [@ohos.hiSysEvent (系统事件打点)](js-apis-hisysevent.md) - [@ohos.hiSysEvent (系统事件打点)](js-apis-hisysevent.md)
- [@ohos.hiTraceChain (分布式跟踪)](js-apis-hitracechain.md) - [@ohos.hiTraceChain (分布式跟踪)](js-apis-hitracechain.md)
- [@ohos.hiTraceMeter (性能打点)](js-apis-hitracemeter.md) - [@ohos.hiTraceMeter (性能打点)](js-apis-hitracemeter.md)
- [@ohos.inputMethod (输入法框架)](js-apis-inputmethod.md) - [@ohos.inputmethod (输入法框架)](js-apis-inputmethod.md)
- [@ohos.inputMethodEngine (输入法服务)](js-apis-inputmethodengine.md) - [@ohos.inputmethodengine (输入法服务)](js-apis-inputmethodengine.md)
- [@ohos.inputmethodextensionability (InputMethodExtensionAbility)](js-apis-inputmethod-extension-ability.md)
- [@ohos.inputmethodextensioncontext (InputMethodExtensionContext)](js-apis-inputmethod-extension-context.md)
- [@ohos.pasteboard (剪贴板)](js-apis-pasteboard.md) - [@ohos.pasteboard (剪贴板)](js-apis-pasteboard.md)
- [@ohos.screenLock (锁屏管理)](js-apis-screen-lock.md) - [@ohos.screenLock (锁屏管理)](js-apis-screen-lock.md)
- [@ohos.systemTime (系统时间、时区)](js-apis-system-time.md) - [@ohos.systemTime (系统时间、时区)](js-apis-system-time.md)
...@@ -247,12 +233,10 @@ ...@@ -247,12 +233,10 @@
- [@ohos.usb (USB管理)](js-apis-usb.md) - [@ohos.usb (USB管理)](js-apis-usb.md)
- [@ohos.vibrator (振动)](js-apis-vibrator.md) - [@ohos.vibrator (振动)](js-apis-vibrator.md)
- 帐号管理 - 帐号管理
- [@ohos.account.appAccount (应用帐号管理)](js-apis-appAccount.md) - [@ohos.account.appAccount (应用帐号管理)](js-apis-appAccount.md)
- [@ohos.account.distributedAccount (分布式帐号管理)](js-apis-distributed-account.md) - [@ohos.account.distributedAccount (分布式帐号管理)](js-apis-distributed-account.md)
- [@ohos.account.osAccount (系统帐号管理)](js-apis-osAccount.md) - [@ohos.account.osAccount (系统帐号管理)](js-apis-osAccount.md)
- 语言基础类库 - 语言基础类库
- [@ohos.buffer (Buffer)](js-apis-buffer.md) - [@ohos.buffer (Buffer)](js-apis-buffer.md)
- [@ohos.convertxml (xml转换JavaScript)](js-apis-convertxml.md) - [@ohos.convertxml (xml转换JavaScript)](js-apis-convertxml.md)
- [@ohos.process (获取进程相关的信息)](js-apis-process.md) - [@ohos.process (获取进程相关的信息)](js-apis-process.md)
...@@ -279,7 +263,6 @@ ...@@ -279,7 +263,6 @@
- [@ohos.application.testRunner (TestRunner)](js-apis-testRunner.md) - [@ohos.application.testRunner (TestRunner)](js-apis-testRunner.md)
- [@ohos.uitest (UiTest)](js-apis-uitest.md) - [@ohos.uitest (UiTest)](js-apis-uitest.md)
- 已停止维护的接口 - 已停止维护的接口
- [@ohos.bytrace (性能打点)](js-apis-bytrace.md) - [@ohos.bytrace (性能打点)](js-apis-bytrace.md)
- [@ohos.data.storage (轻量级存储)](js-apis-data-storage.md) - [@ohos.data.storage (轻量级存储)](js-apis-data-storage.md)
- [@system.app (应用上下文)](js-apis-system-app.md) - [@system.app (应用上下文)](js-apis-system-app.md)
......
...@@ -152,17 +152,17 @@ CommonEvent模块支持的事件类型。名称指的是系统公共事件宏; ...@@ -152,17 +152,17 @@ CommonEvent模块支持的事件类型。名称指的是系统公共事件宏;
| COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | 无 | 当用户设备作为USB主机时,USB设备被卸载的公共事件的动作。 | | COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | 无 | 当用户设备作为USB主机时,USB设备被卸载的公共事件的动作。 |
| COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | 无 | 表示已连接USB附件的公共事件的动作。 | | COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | 无 | 表示已连接USB附件的公共事件的动作。 |
| COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | 无 | 表示USB附件被卸载的公共事件的动作。 | | COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | 无 | 表示USB附件被卸载的公共事件的动作。 |
| COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 外部存储设备状态变更为移除时发送此公共事件。 | | COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为移除时发送此公共事件。 |
| COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 外部存储设备状态变更为卸载时发送此公共事件。 | | COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为卸载时发送此公共事件。 |
| COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 外部存储设备状态变更为挂载时发送此公共事件。 | | COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为挂载时发送此公共事件。 |
| COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 外部存储设备状态变更为挂载状态下移除时发送此公共事件。 | | COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为挂载状态下移除时发送此公共事件。 |
| COMMON_EVENT_DISK_UNMOUNTABLE | usual.event.data.DISK_UNMOUNTABLE | ohos.permission.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 外部存储设备状态变更为插卡情况下无法挂载时发送此公共事件。 | | COMMON_EVENT_DISK_UNMOUNTABLE | usual.event.data.DISK_UNMOUNTABLE | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为插卡情况下无法挂载时发送此公共事件。 |
| COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 用户已表示希望删除外部存储介质时发送此公共事件。 | | COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.STORAGE_MANAGER | 用户已表示希望删除外部存储介质时发送此公共事件。 |
| COMMON_EVENT_VOLUME_REMOVED<sup>9+<sup> | usual.event.data.VOLUME_REMOVED | ohos.permission.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 外部存储设备状态变更为移除时发送此公共事件。 | | COMMON_EVENT_VOLUME_REMOVED<sup>9+<sup> | usual.event.data.VOLUME_REMOVED | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为移除时发送此公共事件。 |
| COMMON_EVENT_VOLUME_UNMOUNTED<sup>9+<sup> | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 外部存储设备状态变更为卸载时发送此公共事件。 | | COMMON_EVENT_VOLUME_UNMOUNTED<sup>9+<sup> | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为卸载时发送此公共事件。 |
| COMMON_EVENT_VOLUME_MOUNTED<sup>9+<sup> | usual.event.data.VOLUME_MOUNTED | ohos.permission.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 外部存储设备状态变更为挂载时发送此公共事件。 | | COMMON_EVENT_VOLUME_MOUNTED<sup>9+<sup> | usual.event.data.VOLUME_MOUNTED | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为挂载时发送此公共事件。 |
| COMMON_EVENT_VOLUME_BAD_REMOVAL<sup>9+<sup> | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 外部存储设备状态变更为挂载状态下移除时发送此公共事件。 | | COMMON_EVENT_VOLUME_BAD_REMOVAL<sup>9+<sup> | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为挂载状态下移除时发送此公共事件。 |
| COMMON_EVENT_VOLUME_EJECT<sup>9+<sup> | usual.event.data.VOLUME_EJECT | ohos.permission.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 用户已表示希望删除外部存储介质时发送此公共事件。 | | COMMON_EVENT_VOLUME_EJECT<sup>9+<sup> | usual.event.data.VOLUME_EJECT | ohos.permission.STORAGE_MANAGER | 用户已表示希望删除外部存储介质时发送此公共事件。 |
| COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED | usual.event.data.VISIBLE_ACCOUNTS_UPDATED | ohos.permission.GET_APP_ACCOUNTS | 表示帐户可见更改的公共事件的动作。 | | COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED | usual.event.data.VISIBLE_ACCOUNTS_UPDATED | ohos.permission.GET_APP_ACCOUNTS | 表示帐户可见更改的公共事件的动作。 |
| COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | 删除帐户的公共事件的动作。 | | COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | 删除帐户的公共事件的动作。 |
| COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | 表示foundation已准备好的公共事件的动作。 | | COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | 表示foundation已准备好的公共事件的动作。 |
......
# 加解密算法库框架
为屏蔽底层硬件和算法库,向上提供统一的密码算法库加解密和证书相关接口。
> **说明:**
>
> 本模块首批接口从API version 9开始支持。
## 导入模块
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
```
## Result
表示执行结果的枚举。
**系统能力:** SystemCapability.Security.CryptoFramework
| 名称 | 默认值 | 描述 |
| --------------------------------------| -------- | ------------------------------|
| INVALID_PARAMS | 401 | 非法入参。 |
| NOT_SUPPORT | 801 | 操作不支持。 |
| ERR_OUT_OF_MEMORY | 17620001 | 内存错误。 |
| ERR_EXTERNAL_ERROR | 17620002 | 运行时外部错误。 |
| ERR_CRYPTO_OPERATION | 17630001 | 调用三方算法库API出错。 |
| ERR_CERT_SIGNATURE_FAILURE | 17630002 | 证书签名验证错误。 |
| ERR_CERT_NOT_YET_VALID | 17630003 | 证书尚未生效。 |
| ERR_CERT_HAS_EXPIRED | 17630004 | 证书过期。 |
| ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY | 17630005 | 无法获取证书的颁发者。 |
| ERR_KEYUSAGE_NO_CERTSIGN | 17630006 | 证书的秘钥用途不含证书签名。 |
| ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE | 17630007 | 证书的秘钥用途不含数字签名。 |
## DataBlob
buffer数组。
**系统能力:** SystemCapability.Security.CryptoFramework
| 名称 | 类型 | 可读 | 可写 | 描述 |
| -------------- | -------------- | ---- | ---- | ----------------|
| data | Uint8Array | 是 | 是 | 数据。 |
## DataArray
buffer数组的列表。
**系统能力:** SystemCapability.Security.CryptoFramework
| 名称 | 类型 | 可读 | 可写 | 描述 |
| -------------- | -------------- | ---- | ---- | ----------------|
| data | Uint8Array | 是 | 是 | 数据列表。 |
## EncodingFormat
表示证书编码格式的枚举。
**系统能力:** SystemCapability.Security.CryptoFramework
| 名称 | 默认值 | 描述 |
| ------------| ---------| -----------|
| FORMAT_DER | 0 | DER格式。 |
| FORMAT_PEM | 1 | PEM格式。 |
## EncodingBlob
证书链数据,在证书链校验时,作为入参传入。
### 属性
**系统能力:** SystemCapability.Security.CryptoFramework
| 名称 | 类型 | 可读 | 可写 | 描述 |
| -------------- | -------------- | ---- | ---- | ----------------------------------|
| data | Uint8Array | 是 | 是 | 传入的数据中,包含的证书数量。 |
| encodingFormat | [EncodingFormat](#encodingformat) | 是 | 是 | 指明证书编码格式。 |
## CertChainData
证书链数据,在证书链校验时,作为入参传入。
### 属性
**系统能力:** SystemCapability.Security.CryptoFramework
| 名称 | 类型 | 可读 | 可写 | 描述 |
| -------------- | -------------- | ---- | ---- | ------------------------------------------------------------ |
| data | Uint8Array | 是 | 是 | 证书数据,按照长度(2字节)-数据的形式传入,如:08ABCDEFGH07ABCDEFG,第一本证书,前2个字节表示证书的长度为8字节,后面附加8字节的证书数据;第2本证书前2个字节表示证书的长度为7字节,后面附加7字节的证书数据。 |
| count | number | 是 | 是 | 传入的数据中,包含的证书数量。 |
| encodingFormat | [EncodingFormat](#encodingformat) | 是 | 是 | 指明证书编码格式。 |
## cryptoFramework.createMac
createMac(algName : string) : Mac
生成Mac实例,用于进行消息认证码的计算与操作
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| algName | string | 是 | 指定摘要算法,支持算法范围:SHA1/SHA224/SHA256/SHA384/SHA512 |
**返回值**
| 类型 | 说明 |
| ---- | --------------------------------------- |
| Mac | 返回由输入算法指定生成的[Mac](#mac)对象 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
```
## Mac
Mac类,调用Mac方法可以进行MAC(Message Authentication Code)加密计算。调用前,需要通过[createMac](#cryptoframeworkcreatemac)构造Mac实例。
### **属性**
**系统能力:**SystemCapability.Security.CryptoFramework
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------- | ------ | ---- | ---- | -------------------- |
| algName | string | 是 | 否 | 代表指定的摘要算法名 |
### init
init(key : SymKey, callback : AsyncCallback\<void>) : void;
使用对称密钥初始化Mac计算
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ------------------ |
| key | SymKey | 是 | 共享对称密钥 |
| callback | AsyncCallback\<void> | 是 | 回调函数 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
var KeyBlob;
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
symKeyGenerator.convertKey(KeyBlob, (err, symKey) => {
if (err) {
console.error("[Callback] err: " + err.code);
}
mac.init(symKey, (err1, ) => {
if (err1) {
console.error("[Callback] err: " + err1.code);
}
});
});
```
### init
init(key : SymKey) : Promise\<void>;
使用对称密钥初始化Mac计算
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------------ |
| key | SymKey | 是 | 共享对称密钥 |
**返回值:**
| 类型 | 说明 |
| --------------- | ------------ |
| Promise\<void> | Promise对象 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
AlertDialog.show({message: "[Promise]: error code: " + error.code + ", message is: " + error.message});
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Mac algName is: " + mac.algName);
var KeyBlob;
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob);
promiseConvertKey.then(symKey => {
var promiseMacInit = mac.init(symKey);
return promiseMacInit;
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
```
### update
update(input : DataBlob, callback : AsyncCallback\<void>) : void;
传入消息进行Mac更新计算
**系统能力:** SystemCapability.Security.CryptoFramework
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ---------- |
| input | DataBlob | 是 | 传入的消息 |
| callback | AsyncCallback\<void> | 是 | 回调函数 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var KeyBlob;
var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
AlertDialog.show({message: "[Callback]: error code: " + error.code + ", message is: " + error.message});
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
symKeyGenerator.convertKey(KeyBlob, (err, symKey) => {
if (err) {
console.error("[Callback] err: " + err.code);
}
mac.init(symKey, (err1, ) => {
if (err1) {
console.error("[Callback] err: " + err1.code);
}
let blob;
mac.update(blob, (err2, data) => {
if (err2) {
console.error("[Callback] err: " + err2.code);
}
});
});
});
```
### update
update(input : DataBlob) : Promise\<void>;
传入消息进行Mac更新计算
**系统能力:** SystemCapability.Security.CryptoFramework
| 参数名 | 类型 | 必填 | 说明 |
| ------ | -------- | ---- | ---------- |
| input | DataBlob | 是 | 传入的消息 |
**返回值:**
| 类型 | 说明 |
| --------------- | ----------- |
| Promise\<void> | Promise对象 |
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
AlertDialog.show({message: "[Promise]: error code: " + error.code + ", message is: " + error.message});
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Mac algName is: " + mac.algName);
AlertDialog.show({message: "Mac algName is: " + mac.algName});
var KeyBlob;
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob);
promiseConvertKey.then(symKey => {
var promiseMacInit = mac.init(symKey);
return promiseMacInit;
}).then(() => {
let blob;
var promiseMacUpdate = mac.update(blob);
return promiseMacUpdate;
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
```
### doFinal
doFinal(callback : AsyncCallback\<DataBlob>) : void;
返回Mac的计算结果
**系统能力:** SystemCapability.Security.CryptoFramework
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | -------- |
| callback | AsyncCallback\<DataBlob> | 是 | 回调函数 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var KeyBlob;
var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
AlertDialog.show({message: "[Callback]: error code: " + error.code + ", message is: " + error.message});
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
symKeyGenerator.convertKey(KeyBlob, (err, symKey) => {
if (err) {
console.error("[Callback] err: " + err.code);
}
mac.init(symKey, (err1, ) => {
if (err1) {
console.error("[Callback] err: " + err1.code);
}
let blob;
mac.update(blob, (err2, ) => {
if (err2) {
console.error("[Callback] err: " + err2.code);
}
mac.doFinal((err3, macOutput) => {
if (err3) {
console.error("[Callback] err: " + err3.code);
} else {
console.error("[Promise]: HMAC result: " + macOutput);
}
});
});
});
});
```
### doFinal
doFinal() : Promise\<DataBlob>
返回Mac的计算结果
**系统能力:** SystemCapability.Security.CryptoFramework
**返回值:**
| 类型 | 说明 |
| ------------------- | ----------- |
| Promise\<DataBlob> | Promise对象 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Mac algName is: " + mac.algName);
AlertDialog.show({message: "Mac algName is: " + mac.algName});
var KeyBlob;
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob);
promiseConvertKey.then(symKey => {
var promiseMacInit = mac.init(symKey);
return promiseMacInit;
}).then(() => {
let blob;
var promiseMacUpdate = mac.update(blob);
return promiseMacUpdate;
}).then(() => {
var PromiseMacDoFinal = mac.doFinal();
return PromiseMacDoFinal;
}).then(macOutput => {
console.error("[Promise]: HMAC result: " + macOutput.data);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
```
### getMacLength
getMacLength() : number
获取Mac消息认证码的长度(字节数)
**系统能力:** SystemCapability.Security.CryptoFramework
**返回值:**
| 类型 | 说明 |
| ------ | ------------------------- |
| number | 返回mac计算结果的字节长度 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Mac algName is: " + mac.algName);
AlertDialog.show({message: "Mac algName is: " + mac.algName});
var KeyBlob;
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob);
promiseConvertKey.then(symKey => {
var promiseMacInit = mac.init(symKey);
return promiseMacInit;
}).then(() => {
let blob;
var promiseMacUpdate = mac.update(blob);
return promiseMacUpdate;
}).then(() => {
var PromiseMacDoFinal = mac.doFinal();
return PromiseMacDoFinal;
}).then(macOutput => {
console.error("[Promise]: HMAC result: " + macOutput.data);
let macLen = mac.getMacLength();
AlertDialog.show({message: "MAC len: " + macLen});
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
```
## cryptoFramework.createMd
createMd(algName : string) : Md
生成Md实例,用于进行消息摘要的计算与操作
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| algName | string | 是 | 指定摘要算法,支持算法范围:SHA1/SHA224/SHA256/SHA384/SHA512/MD5 |
**返回值**
| 类型 | 说明 |
| ---- | ------------------------------------- |
| Md | 返回由输入算法指定生成的[Md](#md)对象 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var md;
try {
md = cryptoFramework.createMd("SHA256");
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
```
## Md
Md类,调用Md方法可以进行MD(Message Digest)摘要计算。调用前,需要通过[createMd](#cryptoframeworkcreatemd)构造Md实例。
### **属性**
**系统能力:**SystemCapability.Security.CryptoFramework
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------- | ------ | ---- | ---- | -------------------- |
| algName | string | 是 | 否 | 代表指定的摘要算法名 |
### update
update(input : DataBlob, callback : AsyncCallback\<void>) : void;
传入消息进行Md更新计算
**系统能力:** SystemCapability.Security.CryptoFramework
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ------------ |
| input | DataBlob | 是 | 传入的消息 |
| callback | AsyncCallback\<void> | 是 | 回调函数 |
**返回值:**
| 类型 | 说明 |
| --------------- | ------------ |
| Promise\<void> | Promise对象 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var md;
try {
md = cryptoFramework.createMd("SHA256");
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Md algName is: " + md.algName);
let blob;
md.update(blob, (err,) => {
if (err) {
console.error("[Callback] err: " + err.code);
}
});
```
### update
update(input : DataBlob) : Promise\<void>;
传入消息进行Md更新计算
**系统能力:** SystemCapability.Security.CryptoFramework
| 参数名 | 类型 | 必填 | 说明 |
| ------ | -------- | ---- | ---------- |
| input | DataBlob | 是 | 传入的消息 |
**返回值:**
| 类型 | 说明 |
| --------------- | ------------ |
| Promise\<void> | Promise对象 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var md;
try {
md = cryptoFramework.createMd("SHA256");
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Md algName is: " + md.algName);
let blob;
var promiseMdUpdate = md.update(blob);
promiseMdUpdate.then(() => {
// do something
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
```
### digest
digest(callback : AsyncCallback\<DataBlob>) : void
返回Md的计算结果
**系统能力:** SystemCapability.Security.CryptoFramework
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | -------------------- |
| callback | AsyncCallback\<DataBlob> | 是 | 回调函数 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var md;
try {
md = cryptoFramework.createMd("SHA256");
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Md algName is: " + md.algName);
let blob;
md.update(blob, (err,) => {
if (err) {
console.error("[Callback] err: " + err.code);
}
md.digest((err1, mdOutput) => {
if (err1) {
console.error("[Callback] err: " + err1.code);
} else {
console.error("[Callback]: MD result: " + mdOutput);
}
});
});
```
### digest
digest() : Promise\<DataBlob>
返回Md的计算结果
**系统能力:** SystemCapability.Security.CryptoFramework
**返回值:**
| 类型 | 说明 |
| ------------------- | ----------- |
| Promise\<DataBlob> | Promise对象 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var md;
try {
md = cryptoFramework.createMd("SHA256");
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Md algName is: " + md.algName);
let blob;
var promiseMdUpdate = md.update(blob);
promiseMdUpdate.then(() => {
var PromiseMdDigest = md.digest();
return PromiseMdDigest;
}).then(mdOutput => {
console.error("[Promise]: MD result: " + mdOutput.data);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
```
### getMdLength
getMdLength() : number
获取Md消息摘要长度(字节数)
**系统能力:** SystemCapability.Security.CryptoFramework
**返回值:**
| 类型 | 说明 |
| ------ | ------------------------ |
| number | 返回md计算结果的字节长度 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var md;
try {
md = cryptoFramework.createMd("SHA256");
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Md algName is: " + md.algName);
let blob;
var promiseMdUpdate = md.update(blob);
promiseMdUpdate.then(() => {
var PromiseMdDigest = md.digest();
return PromiseMdDigest;
}).then(mdOutput => {
console.error("[Promise]: MD result: " + mdOutput.data);
let mdLen = md.getMdLength();
AlertDialog.show({message: "MD len: " + mdLen});
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
```
## cryptoFramework.createRandom
createRandom() : Random
生成Random实例,用于进行随机数的计算与设置种子
**系统能力:** SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------ | --------------------------------------------- |
| Random | 返回由输入算法指定生成的[Random](#random)对象 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
try {
var rand = cryptoFramework.createRandom();
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
```
## Random
Random类,调用Random方法可以进行随机数计算。调用前,需要通过[createRandom](#cryptoframeworkcreaterandom)构造Random实例。
### generateRandom
generateRandom(len : number, callback: AsyncCallback\<DataBlob>) : void;
生成指定长度的随机数
**系统能力:** SystemCapability.Security.CryptoFramework
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | -------------------- |
| len | number | 是 | 表示生成随机数的长度 |
| callback | AsyncCallback\<DataBlob> | 是 | 回调函数 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var rand;
try {
rand = cryptoFramework.createRandom();
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
rand.generateRandom(12, (err, randData) => {
if (err) {
console.error("[Callback] err: " + err.code);
} else {
console.error("[Callback]: generate random result: " + randData.data);
}
});
```
### generateRandom
generateRandom(len : number) : Promise\<DataBlob>;
生成指定长度的随机数
**系统能力:** SystemCapability.Security.CryptoFramework
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | -------------------- |
| len | number | 是 | 表示生成随机数的长度 |
**返回值:**
| 类型 | 说明 |
| ------------------- | ----------- |
| Promise\<DataBlob> | Promise对象 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var rand;
try {
rand = cryptoFramework.createRandom();
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
var promiseGenerateRand = rand.generateRandom(12);
promiseGenerateRand.then(randData => {
console.error("[Promise]: rand result: " + randData.data);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
```
### setSeed
setSeed(seed : DataBlob, callback : AsyncCallback\<void>) : void;
设置指定的种子
**系统能力:** SystemCapability.Security.CryptoFramework
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ------------ |
| seed | DataBlob | 是 | 设置的种子 |
| callback | AsyncCallback\<void\> | 是 | 回调函数 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var rand;
try {
rand = cryptoFramework.createRandom();
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
rand.generateRandom(12, (err, randData) => {
if (err) {
console.error("[Callback] err: " + err.code);
} else {
console.error("[Callback]: generate random result: " + randData.data);
rand.setSeed(randData, (err1, data) => {
if (err1) {
console.error("[Callback] err: " + err1.code);
} else {
console.error("[Callback]: setSeed success");
}
});
}
});
```
### setSeed
setSeed(seed : DataBlob) : Promise\<void>;
设置指定的种子
**系统能力:** SystemCapability.Security.CryptoFramework
| 参数名 | 类型 | 必填 | 说明 |
| ------ | -------- | ---- | ---------- |
| seed | DataBlob | 是 | 设置的种子 |
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
var rand;
try {
rand = cryptoFramework.createRandom();
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
var promiseGenerateRand = rand.generateRandom(12);
promiseGenerateRand.then(randData => {
console.error("[Promise]: rand result: " + randData.data);
var promiseSetSeed = rand.setSeed(randData);
return promiseSetSeed;
}).then(() => {
console.error("[Promise]: setSeed success");
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
```
## ParamsSpec
加解密参数,在进行对称加解密时需要构造其子类对象,并将子类对象传入[init()](#init-2)方法。适用于需要iv等参数的对称加解密模式(对于无iv等参数的模式如ECB模式,不需要构造其子类对象)。
**系统能力:** SystemCapability.Security.CryptoFramework
| 名称 | 类型 | 可读 | 可写 | 描述 |
| ------- | ------ | ---- | ---- | ---------------------- |
| algoName | string | 是 | 是 | 指明对称加解密参数的算法模式。可选值如下:<br/>- "IvParamsSpec": 适用于CBC\|CTR\|OFB\|CFB模式<br/>- "GcmParamsSpec": 适用于GCM模式<br/>- "CcmParamsSpec": 适用于CCM模式 |
## IvParamsSpec
适用于CBC、CTR、OFB、CFB模式,仅使用iv的加解密参数,在对称加解密时构造并传入[init()](#init-2)方法作为参数。
**系统能力:** SystemCapability.Security.CryptoFramework
| 名称 | 类型 | 可读 | 可写 | 描述 |
| ------- | ------ | ---- | ---- | ---------------------- |
| iv | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数iv。常见取值如下:<br/>- AES的CBC\|CTR\|OFB\|CFB模式:iv长度为16字节<br/>- 3DES的CBC\|OFB\|CFB模式:iv长度为8字节|
## GcmParamsSpec
适用于GCM模式的加解密参数,在对称加解密时构造并传入[init()](#init-2)方法作为参数。
**系统能力:** SystemCapability.Security.CryptoFramework
| 名称 | 类型 | 可读 | 可写 | 描述 |
| ------- | ------ | ---- | ---- | ---------------------- |
| iv | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数iv,长度为12字节|
| aad | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数aad,长度为8字节|
| authTag | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数authTag,长度为16字节。<br/>采用GCM模式加密时,需要获取[doFinal()](#dofinal-2)输出的[DataBlob](#datablob),将其作为解密时[GcmParamsSpec](#gcmparamsspec)中的authTag|
## CcmParamsSpec
适用于CCM模式的加解密参数,在对称加解密时构造并传入[init()](#init-2)方法作为参数。
**系统能力:** SystemCapability.Security.CryptoFramework
| 名称 | 类型 | 可读 | 可写 | 描述 |
| ------- | -------- | ---- | ---- | -------------------------------|
| iv | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数iv,长度为7字节 |
| aad | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数aad,长度为8字节 |
| authTag | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数authTag,长度为12字节。<br/>采用CCM模式加密时,需要获取[doFinal()](#dofinal-2)输出的[DataBlob](#datablob),将其作为解密时[CcmParamsSpec](#ccmparamsspec)中的authTag |
## CryptoMode
表示加解密操作的枚举。
**系统能力:** SystemCapability.Security.CryptoFramework
| 名称 | 值 | 描述 |
| ------------ | -------- | -------------------------------- |
| ENCRYPT_MODE | 0 | 表示进行加密操作 |
| DECRYPT_MODE | 1 | 表示进行解密操作 |
## Key
密钥(父类),在运行密码算法(如加解密)时需要提前生成其子类对象,并传入[Cipher](#cipher)实例的[init()](#init-2)方法。密钥可以通过密钥生成器来生成。
### 属性
**系统能力:** SystemCapability.Security.CryptoFramework
| 名称 | 类型 | 可读 | 可写 | 描述 |
| ------- | ------ | ---- | ---- | ---------------------- |
| format | string | 是 | 否 | 密钥的格式。|
| algName | string | 是 | 否 | 密钥对应的算法名(含长度)。|
### getEncoded
getEncoded() : DataBlob
以同步方法,获取16进制形式的密钥内容。
**系统能力:** SystemCapability.Security.CryptoFramework
**返回值:**
| 类型 |描述 |
| ------- | ----------- |
| [DataBlob](#datablob) | 用于查看密钥的具体内容。|
**示例:**
```js
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
let key; // key为使用对称密钥生成器 生成的密钥,此处省略生成过程
let encodedKey = key.getEncoded();
console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data));
```
## SymKey
对称密钥,是[Key](#key)的子类,在对称加解密时需要将其对象传入[Cipher](#cipher)实例的[init()](#init-2)方法使用。对称密钥可以通过对称密钥生成器[SymKeyGenerator](#symkeygenerator)来生成。
### clearMem
clearMem() : void
以同步方法,将系统底层内存中的的密钥内容清零。
**系统能力:** SystemCapability.Security.CryptoFramework
**示例:**
```js
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
let key; // key为使用对称密钥生成器 生成的密钥,此处省略生成过程
let encodedKey = key.getEncoded();
console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // 输出密钥内容
key.clearMem();
encodedKey = key.getEncoded();
console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // 输出全零
```
## PubKey
公钥,是Key的子类,在非对称加解密、验签、密钥协商时需要将其对象作为输入使用。公钥可以通过非对称密钥生成器AsyKeyGenerator来生成。
### 属性
**系统能力:** SystemCapability.Security.CryptoFramework
| 名称 | 类型 | 可读 | 可写 | 描述 |
| ------- | ------ | ---- | ---- | ---------------------- |
| format | string | 是 | 否 | 密钥的格式。|
| algName | string | 是 | 否 | 密钥对应的算法名(含长度)。|
### getEncoded
getEncoded() : DataBlob
以同步方法,获取二进制形式的密钥内容。
**系统能力:** SystemCapability.Security.CryptoFramework
**返回值:**
| 类型 |描述 |
| ------- | ----------- |
| [DataBlob](#datablob) | 用于查看密钥的具体内容。|
**示例:**
```js
console.info("key format:" + key.format);
console.info("key algName:" + key.algName);
var encodedKey = key.getEncoded();
console.info("key encoded:" + Uint8ArrayToShowStr(encodedKey.data));
```
## PriKey
私钥,是Key的子类,在非对称加解密、签名、密钥协商时需要将其作为输入使用。私钥可以通过非对称密钥生成器AsyKeyGenerator来生成。
### 属性
**系统能力:** SystemCapability.Security.CryptoFramework
| 名称 | 类型 | 可读 | 可写 | 描述 |
| ------- | ------ | ---- | ---- | ---------------------- |
| format | string | 是 | 否 | 密钥的格式。|
| algName | string | 是 | 否 | 密钥对应的算法名(含长度)。|
### getEncoded
getEncoded() : DataBlob
以同步方法,获取二进制形式的密钥内容。
**系统能力:** SystemCapability.Security.CryptoFramework
**返回值:**
| 类型 |描述 |
| ------- | ----------- |
| [DataBlob](#datablob) | 用于查看密钥的具体内容。|
**示例:**
```js
console.info("key format:" + key.format);
console.info("key algName:" + key.algName);
var encodedKey = key.getEncoded();
console.info("key encoded:" + Uint8ArrayToShowStr(encodedKey.data));
```
### clearMem
clearMem() : void
以同步方法,将系统底层内存中的的密钥内容清零。
**系统能力:** SystemCapability.Security.CryptoFramework
**示例:**
```js
key.clearMem();
```
## cryptoFramework.createSymKeyGenerator
createSymKeyGenerator(algName : string) : SymKeyGenerator
通过指定算法名称的字符串,获取相应的对称密钥生成器实例。
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ----------------------------- |
| algName | string | 是 | 待生成对称密钥生成器的算法名称。 |
**返回值:**
| 类型 | 说明 |
| ----------------------------------- | -------------------------- |
| [SymKeyGenerator](#symkeygenerator) | 返回对称密钥生成器的对象。 |
## SymKeyGenerator
对称密钥生成器。在使用该类的方法前,需要先使用[createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator)方法构建一个symKeyGenerator实例。
### 属性
**系统能力:** SystemCapability.Security.CryptoFramework
| 名称 | 类型 | 可读 | 可写 | 描述 |
| ------- | ------ | ---- | ---- | ---------------------------- |
| algName | string | 是 | 否 | 对称密钥生成器指定的算法名称。 |
### generateSymKey
generateSymKey(callback : AsyncCallback\<SymKey>) : void
异步获取对称密钥生成器随机生成的密钥,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 名称 | 类型 | 必填 | 说明 |
| -------- | ----------------- | ---- | ------------------- |
| callback | AsyncCallback\<[SymKey](#symkey)> | 是 | 回调函数,用于获取对称密钥。 |
**示例:**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
let symAlgoName = '3DES192';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName);
symKeyGenerator.generateSymKey((err, symKey) => {
if (err) {
console.error('Failed to generate symKey');
return;
}
console.log('Generate symKey success, algName: ' + symKey.algName);
})
```
### generateSymKey
generateSymKey() : Promise\<SymKey>
异步获取该对称密钥生成器随机生成的密钥,通过Promise获取结果。
**系统能力:** SystemCapability.Security.CryptoFramework
**返回值:**
| 类型 | 说明 |
| --------------------- | ------------------------------- |
| Promise\<[SymKey](#symkey)> | 使用Promise的方式获取对称密钥。 |
**示例:**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
let symAlgoName = 'AES128';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName);
symKeyGenerator.generateSymKey().then((symKey) => {
console.log('Generate symKey success, algName:' + symKey.algName);
})
```
### convertKey
convertKey(key : DataBlob, callback : AsyncCallback\<SymKey>) : void
异步获取指定数据生成对称密钥,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 名称 | 类型 | 必填 | 说明 |
| -------- | ----------------- | ---- | ---------------------- |
| key | [DataBlob](#datablob) | 是 | 指定的对称密钥材料。 |
| callback | AsyncCallback\<[SymKey](#symkey)> | 是 | 回调函数,用于获取对称密钥。 |
**示例:**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
function genKeyMaterialBlob() {
let arr = [
0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56,
0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c,
0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes)
let keyMaterial = new Uint8Array(arr);
return {data : keyMaterial};
}
let symAlgoName = '3DES192';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName);
let keyMaterialBlob = genKeyMaterialBlob();
symKeyGenerator.convertKey(keyMaterial, (err, symKey) => {
if (err) {
console.error('Failed to convert symKey');
return;
}
console.log('Convert symKey success, algName:' + symKey.algName);
})
```
### convertKey
convertKey(key : DataBlob) : Promise\<SymKey>
异步获取指定数据生成对称密钥,通过Promise获取结果。
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 名称 | 类型 | 必填 | 说明 |
| ---- | -------- | ---- | -------------------- |
| key | [DataBlob](#datablob) | 是 | 指定的密钥材料数据。 |
**返回值:**
| 类型 | 说明 |
| --------------------- | ------------------------------- |
| Promise\<[SymKey](#symkey)> | 使用Promise的方式获取对称密钥。 |
**示例:**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
function genKeyMaterialBlob() {
let arr = [
0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56,
0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c,
0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes)
let keyMaterial = new Uint8Array(arr);
return {data : keyMaterial};
}
let symAlgoName = '3DES192';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName);
let keyMaterialBlob = genKeyMaterialBlob();
symKeyGenerator.convertKey(keyMaterial).then((symKey) => {
console.log('Convert symKey success, algName:' + symKey.algName);
})
```
## cryptoFramework.createAsyKeyGenerator
createAsyKeyGenerator(algName : string) : AsyKeyGenerator
通过指定算法名称的字符串,获取相应的非对称密钥生成器实例。
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | -------------------------------- |
| algName | string | 是 | 待生成对称密钥生成器的算法名称。 |
**返回值:**
| 类型 | 说明 |
| --------------- | -------------------------- |
| asyKeyGenerator | 返回非对称密钥生成器的对象。 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
```
## AsyKeyGenerator
非对称密钥生成器。在使用该类的方法前,需要先使用createAsyKeyGenerator()方法构建一个AsyKeyGenerator实例。
### 属性
**系统能力:** SystemCapability.Security.CryptoFramework
| 名称 | 类型 | 可读 | 可写 | 描述 |
| -------------- | -------------- | ---- | ---- | ----------------------------------|
| algName | string | 是 | 否 | 非对称密钥生成器指定的算法名称。 |
### generateKeyPair
generateKeyPair(callback : AsyncCallback\<KeyPair>) : void;
异步获取非对称密钥生成器随机生成的密钥,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 名称 | 类型 | 必填 | 说明 |
| -------- | -------------------------- | ---- | ---------------------------- |
| callback | AsyncCallback\<KeyPair> | 是 | 回调函数,用于获取非对称密钥。 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
asyKeyGenerator.generateKeyPair((err, keyPair) => {
if (err) {
console.error("generateKeyPair: error.");
return;
}
console.info("generateKeyPair: success.");
})
```
### generateKeyPair
generateKeyPair() : Promise\<KeyPair>
异步获取该非对称密钥生成器随机生成的密钥,通过Promise获取结果。
**系统能力:** SystemCapability.Security.CryptoFramework
**返回值:**
| 类型 | 说明 |
| --------------------- | ------------------------------- |
| Promise\<KeyPair> | 使用Promise的方式获取非对称密钥。 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
let keyGenPromise = asyKeyGenerator.generateKeyPair();
keyGenPromise.then( keyPair => {
console.info("generateKeyPair success.");
}).catch(error => {
console.error("generateKeyPair error.");
});
```
### convertKey
convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\<KeyPair\>) : void
异步获取指定数据生成非对称密钥,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 名称 | 类型 | 必填 | 说明 |
| -------- | -------------------------- | ---- | ---------------------------- |
| pubKey | DataBlob | 否 | 指定的公钥材料。 |
| priKey | DataBlob | 否 | 指定的私钥材料。 |
| callback | AsyncCallback\<KeyPair> | 是 | 回调函数,用于获取非对称密钥。 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
asyKeyGenerator.convertKey(pubKey, priKey, (err, keyPair) => {
if (err) {
console.error("convertKey: error.");
return;
}
console.info("convertKey: success.");
})
```
### convertKey
convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\<KeyPair>
异步获取指定数据生成非对称密钥,通过Promise获取结果。
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 名称 | 类型 | 必填 | 说明 |
| ---- | -------- | ---- | -------------------- |
| pubKey | DataBlob | 否 | 指定的公钥材料。 |
| priKey | DataBlob | 否 | 指定的私钥材料。 |
**返回值:**
| 类型 | 说明 |
| --------------------- | ------------------------------- |
| Promise\<KeyPair> | 使用Promise的方式获取非对称密钥。 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
let keyGenPromise = asyKeyGenerator.convertKey(pubKey, priKey);
keyGenPromise.then( keyPair => {
console.info("convertKey success.");
}).catch(error => {
console.error("convertKey error.");
});
```
## cryptoFramework.createCipher
createCipher(transformation : string) : Cipher
通过指定算法名称,获取相应的[Cipher](#cipher)实例。
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------------- | ------ | -------- | ------------------------------------------------------------ |
| transformation | string | 是 | 待生成Cipher的算法名称、加密模式以及填充方法的组合。输入可以为"RSA1024\|PKCS1", "RSA1024\|PKCS1_OAEP\|SHA256\|SHA256"等 |
**返回值:**
| 类型 | 说明 |
| ------ | ------------------------ |
| [Cipher](#cipher) | 返回加解密生成器的对象。 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let cipherAlgoName = '3DES192|ECB|PKCS7';
var cipher;
try {
cipher = cryptoFramework.createCipher(cipherAlgoName);
console.info(`cipher algName: ${cipher.algName}`);
} catch (error) {
console.error(`createCipher failed, ${error.code}, ${error.message}`);
return;
}
```
## Cipher
提供加解密的算法操作功能,按序调用本类中的[init()](#init-2)[update()](#update-4)[doFinal()](#dofinal-2)方法,可以实现对称加密/对称解密/非对称加密/非对称解密。
### 属性
**系统能力:** SystemCapability.Security.CryptoFramework
| 名称 | 类型 | 可读 | 可写 | 描述 |
| ------- | ------ | -------- | ----------- | ---------------------------- |
| algName | string | 是 | 否 | 加解密生成器指定的算法名称。 |
### init
init(opMode : CryptoMode, key : Key, params : ParamsSpec, callback : AsyncCallback\<void>) : void
初始化加解密的[cipher](#cipher)对象,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 名称 | 类型 | 必填 | 说明 |
| -------- | ------------------------ | ------- | ------------------------ |
| opMode | [CryptoMode](#cryptomode) | 是 | 加密或者解密模式。 |
| key | [Key](#key) | 是 | 指定加密或解密的密钥。 |
| params | [ParamsSpec](#paramsspec) | 是 | 指定加密或解密的参数。 |
| callback | AsyncCallback\<void> | 是 | 回调函数。 |
**示例:**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
let symKey; // 此处省略生成对称密钥的过程
let cipher; // 此处省略生成cipher实例的过程
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => {
if (err) {
console.error('Failed to init cipher');
return;
}
console.log('Init cipher success');
// 此处进行update等后续操作
})
```
### init
init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\<void>
初始化加解密的cipher对象,通过Promise获取结果。
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 名称 | 类型 | 必填 | 说明 |
| ------ | ---------- | ---- | ---------------------- |
| opMode | [CryptoMode](#cryptomode) | 是 | 加密或者解密模式。 |
| key | [Key](#key) | 是 | 指定加密或解密的密钥。 |
| params | [ParamsSpec](#paramsspec) | 是 | 指定加密或解密的参数,对于ECB等没有参数的算法模式,可以传入null。 |
**返回值:**
| 类型 | 说明 |
| ------------------- | --------------------------- |
| Promise\<void> | 使用Promise的方式获取结果。 |
**示例:**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
let symKey; // 此处省略生成对称密钥的过程
let cipher; // 此处省略生成cipher实例的过程
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null).then(() => {
console.log('Init cipher success');
// 此处进行update等后续操作
})
```
### update
update(data : DataBlob, callback : AsyncCallback\<DataBlob>) : void
分段更新加密或者解密数据操作,通过注册回调函数获取加密或者解密数据。(根据数据量,可不调用update或调用多次update)
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 名称 | 类型 | 必填 | 说明 |
| -------- | ---------------------------- | ---- | ------------------------------------------ |
| data | [DataBlob](#datablob) | 是 | 加密或者解密的数据。 |
| callback | AsyncCallback\<[DataBlob](#datablob)> | 是 | 回调函数,用于获取加密或者解密的数据结果。 |
**示例:**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
function stringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
return new Uint8Array(arr);
}
let cipher; // 此处省略生成cipher实例的过程
// 此处省略init()过程
let plainText = {data : stringToUint8Array('this is test!')};
cipher.update(plainText, (err, output) => { // 加密过程举例
if (err) {
console.error('Failed to update cipher');
return;
}
console.log('Update cipher success');
// 此处进行doFinal等后续操作
})
```
### update
update(data : DataBlob) : Promise\<DataBlob>
分段更新加密或者解密数据操作,通过Promise获取结果。(根据数据量,可不调用update或调用多次update)
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 名称 | 类型 | 必填 | 说明 |
| ---- | -------- | ---- | -------------------- |
| data | [DataBlob](#datablob) | 是 | 加密或者解密的数据。 |
**返回值:**
| 类型 | 说明 |
| ----------------------- | --------------------------- |
| Promise\<[DataBlob](#datablob)> | 使用Promise的方式获取结果。 |
**示例:**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
function stringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
return new Uint8Array(arr);
}
let cipher; // 此处省略生成cipher实例的过程
// 此处省略init()过程
let plainText = {data : stringToUint8Array('this is test!')};
cipher.update(data).then((output) => {
console.log('Update cipher success');
// 此处进行doFinal等后续操作
})
```
### doFinal
doFinal(data : DataBlob, callback : AsyncCallback\<DataBlob>) : void
最后结束加密或者解密数据操作,通过注册回调函数获取加密或者解密数据。如果在本次加解密过程中已经使用[update](#update-4)传入过数据,可以在doFinal的data参数处传入null。<br/>根据对称加解密的模式不同,doFinal的输出可能不同。<br/>对于GCM和CCM模式的对称加密,在doFinal完成后需要将其结果暂存作为解密时的authTag。<br/>对于其他模式的对称加解密,存在两种情况(1)update输出一部分加解密结果,doFinal输出剩余加解密结果;(2)update输出加解密结果全部由update输出,doFinal输出空。
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 名称 | 类型 | 必填 | 说明 |
| -------- | ---------------------------- | ---- | ------------------------------------------ |
| data | [DataBlob](#datablob) | 是 | 加密或者解密的数据。 |
| callback | AsyncCallback\<[DataBlob](#datablob)> | 是 | 回调函数,用于获取加密或者解密的数据结果。 |
**示例:**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
let cipher; // 此处省略生成cipher实例的过程
let data; // 此处省略准备待加密/解密数据的过程
// 此处省略init()和update()过程
cipher.doFinal(data, (err, output) => {
if (err) {
console.error('Failed to final cipher');
return;
}
console.log('Final cipher success');
})
```
### doFinal
doFinal(data : DataBlob) : Promise\<DataBlob>
最后结束加密或者解密数据操作,通过Promise获取结果。如果在本次加解密过程中已经使用update传入过数据,可以在doFinal的data参数处传入null。
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 名称 | 类型 | 必填 | 说明 |
| ---- | -------- | ---- | -------------------- |
| data | [DataBlob](#datablob) | 是 | 加密或者解密的数据。 |
**返回值:**
| 类型 | 说明 |
| ----------------------- | --------------------------- |
| Promise\<[DataBlob](#datablob)> | 使用Promise的方式获取结果。 |
**示例:**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
let cipher; // 此处省略生成cipher实例的过程
let data; // 此处省略准备待加密/解密数据的过程
// 此处省略init()和update()过程
cipher.doFinal(data).then((output) => {
console.log('Final cipher success');
})
```
**callback示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let cipher = cryptoFramework.createCipher("RSA1024|PKCS1");
rsaGenerator.generateKeyPair(function (err, keyPair) {
let pubKey = keyPair.pubKey;
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, function (err, data) {
let input = {data : stringToUint8Array(plan) };
cipher.doFinal(input, function (err, data) {
AlertDialog.show({ message : "EncryptOutPut is " + data.data} );
});
});
});
```
**promise示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let cipher = cryptoFramework.createCipher("RSA1024|PKCS1");
let keyGenPromise = rsaGenerator.generateKeyPair();
keyGenPromise.then(rsaKeyPair => {
let pubKey = rsaKeyPair.pubKey;
return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); // 传入私钥和DECRYPT_MODE可初始化解密模式
}).then(() => {
let input = { data : stringToUint8Array(plan) };
return cipher.doFinal(input);
}).then(dataBlob => {
console.info("EncryptOutPut is " + dataBlob.data);
});
```
## cryptoFramework.createSign
createSign(algName : string) : Sign
Sign实例生成
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| algName | string | 是 | 指定签名算法:RSA或ECC,使用RSA PKCS1模式时需要设置摘要,使用RSA PSS模式时需要设置摘要和掩码摘要 |
**返回值**
| 类型 | 说明 |
| ---- | ------------------------------ |
| Sign | 返回由输入算法指定生成的Sign对象 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let signer1 = cryptoFramework.createSign("RSA1024|PKCS1|SHA256");
let singer2 = cryptoFramework.createSign("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256")
```
## Sign
Sign类,使用Sign方法之前需要创建该类的实例进行操作,通过createSign(algName : string) : Sign方法构造此实例。
### init
init(priKey : PriKey, callback : AsyncCallback\<void>) : void
使用私钥初始化Sign对象,Callback形式
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ------------------ |
| priKey | Key |是| 用于Sign的初始化 |
| callback | AsyncCallback\<void> | 是 | 回调函数的 |
### init
init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\<void>
使用私钥初始化Sign对象,Promise形式
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ------------------ |
| priKey | Key |是| 用于Sign的初始化 |
**返回值:**
| 类型 | 说明 |
| ------------- | ----------- |
| Promise<void> | Promise对象 |
### update
update(data : DataBlob, callback : AsyncCallback\<void>) : void
追加待签名数据,callback方式
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ------------------ |
| data | DataBlob | 是 | 传入的消息 |
| callback | AsyncCallback<void> | 是 | 回调函数 |
### update
update(data : DataBlob) : Promise\<void>;
追加待签名数据,promise方式
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | -------- | ---- | ---------- |
| data | DataBlob | 是 | 传入的消息 |
**返回值:**
| 类型 | 说明 |
| ------------- | ----------- |
| Promise\<void> | Promise对象 |
### sign
sign(data : DataBlob, callback : AsyncCallback\<DataBlob>) : void
对数据进行签名,返回签名结果,callback方式
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ------------------ |
| data | DataBlob | 是 | 传入的消息 |
| callback | AsyncCallback\<void> | 是 | 回调函数 |
### sign
sign(data : DataBlob) : Promise\<DataBlob>
对数据进行签名,返回签名结果,promise方式
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | -------- | ---- | ---------- |
| data | DataBlob | 是 | 传入的消息 |
**返回值:**
| 类型 | 说明 |
| ------------- | ----------- |
| Promise\<void> | Promise对象 |
**callback示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256");
rsaGenerator.generateKeyPair(function (err, keyPair) {
globalKeyPair = keyPair;
let priKey = globalKeyPair.priKey;
signer.init(priKey, function (err, data) {
signer.update(input1, function (err, data) {
signer.sign(input2, function (err, data) {
SignMessageBlob = data;
console.info("sign output is " + SignMessageBlob.data);
});
});
});
});
```
**promise示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256");
let keyGenPromise = rsaGenerator.generateKeyPair();
keyGenPromise.then( keyPair => {
globalKeyPair = keyPair;
let priKey = globalKeyPair.priKey;
return signer.init(priKey);
}).then(() => {
return signer.update(input1);
}).then(() => {
return signer.sign(input2);
}).then(dataBlob => {
SignMessageBlob = dataBlob;
console.info("sign output is " + SignMessageBlob.data);
});
```
## cryptoFramework.createVerify
createVerify(algName : string) : Verify
Verify实例生成
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| algName | string | 是 | 指定签名算法:RSA或ECC,使用RSA PKCS1模式时需要设置摘要,使用RSA PSS模式时需要设置摘要和掩码摘要 |
**返回值**
| 类型 | 说明 |
| ---- | ------------------------------ |
| Verify | 返回由输入算法指定生成的Verify对象 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let verifyer1 = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256");
let verifyer2 = cryptoFramework.createVerify("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256")
```
## Verify
Verify类,使用Verify方法之前需要创建该类的实例进行操作,通过createVerify(algName : string) : Verify方法构造此实例。
### init
init(pubKey : PubKey, callback : AsyncCallback\<void>) : void
传入私钥初始化Verify对象,Callback形式
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ------------------ |
| pubKey | Key |是| 公钥对象,用于Verify的初始化 |
| callback | AsyncCallback\<void> | 是 | 回调函数 |
### init
init(pubKey : PubKey) : Promise\<void>
传入私钥初始化Verify对象,Promise形式
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ------------------ |
| pubKey | Key |是|公钥对象,用于Verify的初始化 |
**返回值:**
| 类型 | 说明 |
| --------------- | ------------ |
| Promise\<void> | Promise对象 |
### update
update(data : DataBlob, callback : AsyncCallback\<void>) : void
追加待验签数据,callback方式
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ------------------ |
| data | DataBlob | 是 | 传入的消息 |
| callback | AsyncCallback\<void> | 是 | 回调函数 |
### update
update(data : DataBlob) : Promise\<void>;
追加待验签数据,promise方式
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | -------- | ---- | ---------- |
| data | DataBlob | 是 | 传入的消息 |
**返回值:**
| 类型 | 说明 |
| ------------- | ----------- |
| Promise\<void> | Promise对象 |
### verify
verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback\<boolean>) : void
对数据进行签名,返回签名结果,callback方式
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ------------------ |
| data | DataBlob | 是 | 传入的消息 |
| signatureData | DataBlob | 是 | 签名数据 |
| callback | AsyncCallback\<void> | 是 | 回调函数 |
### verify
verify(data : DataBlob, signatureData : DataBlob) : Promise\<boolean>
对数据进行签名,返回签名结果,promise方式
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | -------- | ---- | ---------- |
| data | DataBlob | 是 | 传入的消息 |
| signatureData | DataBlob| 是 | 签名数据 |
**返回值:**
| 类型 | 说明 |
| --------------- | ------------ |
| Promise\<boolean> | 异步返回值,代表验签是否通过|
**callback示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA25");
verifyer.init(globalKeyPair.pubKey, function (err, data) {
verifyer.update(input1, function(err, data) {
verifyer.verify(input2, SignMessageBlob, function(err, data) {
console.info("verify result is " + data);
})
});
})
```
**promise示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256");
let verifyInitPromise = verifyer.init(globalKeyPair.pubKey);
verifyInitPromise.then(() => {
return verifyer.update(input1);
}).then(() => {
return verifyer.verify(input2, SignMessageBlob);
}).then(res => {
console.log("Verify result is " + res);
});
```
## cryptoFramework.createKeyAgreement
createKeyAgreement(algName : string) : KeyAgreement
KeyAgreement实例生成
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| algName | string | 是 | 指定密钥协商算法:目前仅支持ECC |
**返回值**
| 类型 | 说明 |
| ---- | ------------------------------ |
| KeyAgreement | 返回由输入算法指定生成的KeyAgreement对象 |
**示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let keyAgreement = cryptoFramework.createKeyAgreement("ECC256");
```
## KeyAgreement
KeyAgreement类,使用密钥协商方法之前需要创建该类的实例进行操作,通过createKeyAgreement(algName : string) : KeyAgreement方法构造此实例。
### generateSecret
generateSecret(priKey : PriKey, pubKey : PubKey, callback : AsyncCallback\<DataBlob>) : void
基于传入的私钥与公钥进行密钥协商,返回共享秘密,Callback形式
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ------------------ |
| priKey | PriKey |是| 设置密钥协商的私钥输入 |
| pubKey | PubKey |是| 设置密钥协商的公钥输入 |
| callback | AsyncCallback\<DataBlob> | 是 | 异步接受共享秘密的回调 |
### generateSecret
generateSecret(priKey : PriKey, pubKey : PubKey) : Promise\<DataBlob>
基于传入的私钥与公钥进行密钥协商,返回共享秘密,Promise形式
**系统能力:** SystemCapability.Security.CryptoFramework
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ------------------ |
| priKey | PriKey |是| 设置密钥协商的私钥输入 |
| pubKey | PubKey |是| 设置密钥协商的公钥输入 |
**返回值:**
| 类型 | 说明 |
| --------------- | ------------ |
| Promise\<DataBlob> | 共享秘密 |
**callback示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let keyAgreement = cryptoFramework.createKeyAgreement("ECC256");
keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function (err, secret) {
if (err) {
console.error("keyAgreement error.");
return;
}
console.info("keyAgreement output is " + secret.data);
});
```
**promise示例:**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let keyAgreement = cryptoFramework.createKeyAgreement("ECC256");
let keyAgreementPromise = keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey);
keyAgreementPromise.then((secret) => {
console.info("keyAgreement output is " + secret.data);
}).catch((error) => {
console.error("keyAgreement error.");
});
```
## cryptoFramework.createX509Cert
createX509Cert(inStream : EncodingBlob, callback : AsyncCallback\<X509Cert>) : void
表示创建X509证书对象。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------ |
| inStream | EncodingBlob | 是 | X509证书序列化数据 |
| callback | AsyncCallback\<X509Cert> | 否 | 回调函数。表示X509证书对象 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
}
});
```
## cryptoFramework.createX509Cert
createX509Cert(inStream : EncodingBlob) : Promise\<X509Cert>
表示创建X509证书对象。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------ | ---- | ------------------ |
| inStream | EncodingBlob | 是 | X509证书序列化数据 |
**返回值**
| 类型 | 说明 |
| :------- | ---------------- |
| X509Cert | 表示X509证书对象 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob).then(x509Cert => {
Console.log("createX509Cert success");
}, error => {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
## X509Cert
X509证书类。
### verify
verify(key : PubKey, callback : AsyncCallback\<void>) : void
表示对证书验签。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------ |
| key | PubKey | 是 | 用于验签的公钥对象 |
| callback | AsyncCallback\<void>) | 否 | 回调函数。使用AsyncCallback的第一个error参数判断是否验签成功,error为null表示成功,不为null表示失败 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
// 业务需通过AsyKeyGenerator生成PubKey或通过上级X509Cert证书对象的getPublicKey获取PubKey
let pubKey = null;
x509Cert.verify(pubKey, function (error, data) {
if (error != null) {
Console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("verify success");
}
});
}
});
```
### verify
verify(key : PubKey) : Promise\<void>
表示对证书验签。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------------------ |
| key | PubKey | 是 | 用于验签的公钥对象 |
**返回值**
| 类型 | 说明 |
| ---- | ------------------------------------------------------------ |
| Promise\<void> | Promise对象 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob).then(x509Cert => {
Console.log("createX509Cert success");
// 业务需通过AsyKeyGenerator生成PubKey或通过上级X509Cert证书对象的getPublicKey获取PubKey
let pubKey = null;
x509Cert.verify(pubKey).then(result => {
Console.log("verify success");
}, error => {
Console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getEncoded
getEncoded(callback : AsyncCallback\<EncodingBlob>) : void
表示获取X509证书序列化数据。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | -------- |
| callback | AsyncCallback\<EncodingBlob> | 否 | 回调函数。表示X509证书序列化数据 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
x509Cert.getEncoded(function (error, data) {
if (error != null) {
Console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getEncoded success");
}
});
}
});
```
### getEncoded
getEncoded() : Promise\<EncodingBlob>
表示获取X509证书序列化数据。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------------ | ---------------------- |
| Promise\<EncodingBlob> | 表示X509证书序列化数据 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob).then(x509Cert => {
Console.log("createX509Cert success");
x509Cert.getEncoded().then(result => {
Console.log("getEncoded success");
}, error => {
Console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getPublicKey
getPublicKey(callback : AsyncCallback\<PubKey>) : void
表示获取X509证书公钥。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | -------- |
| callback | AsyncCallback | 否 | 回调函数,X509证书公钥对象 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
x509Cert.getPublicKey(function (error, pubKey) {
if (error != null) {
Console.log("getPublicKey failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getPublicKey success");
}
});
}
});
```
### getPublicKey
getPublicKey() : Promise\<PubKey>
表示获取X509证书公钥。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------ | ---------------- |
| PubKey | X509证书公钥对象 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob).then(x509Cert => {
Console.log("createX509Cert success");
x509Cert.getPublicKey().then(pubKey => {
Console.log("getPublicKey success");
}, error => {
Console.log("getPublicKey failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### checkValidityWithDate
checkValidityWithDate(date: string, callback : AsyncCallback\<void>) : void
表示检查X509证书有效期。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | -------- |
| date | string | 是 | 日期 |
| callback | AsyncCallback\<void> | 否 | 回调函数。使用AsyncCallback的第一个error参数判断是否检查成功,error为null表示成功,不为null表示失败 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let date = "150527000001Z";
x509Cert.checkValidityWithDate(date, function (error, data) {
if (error != null) {
Console.log("checkValidityWithDate failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("checkValidityWithDate success");
}
});
}
});
```
### checkValidityWithDate
checkValidityWithDate(date: string) : Promise\<void>
表示检查X509证书有效期。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ---- |
| date | string | 是 | 日期 |
**返回值**
| 类型 | 说明 |
| ---- | ------------------------------------------------------------ |
| void | 使用AsyncCallback的第一个error参数判断是否检查成功,error为null表示成功,不为null表示失败 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob).then(x509Cert => {
Console.log("createX509Cert success");
let date = "150527000001Z";
x509Cert.checkValidityWithDate(date).then(result => {
Console.log("checkValidityWithDate success");
}, error => {
Console.log("checkValidityWithDate failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getVersion
getVersion() : number
表示获取X509证书版本。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------ | ---------------- |
| number | 表示X509证书版本 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let version = x509Cert.getVersion();
}
});
```
### getSerialNumber
getSerialNumber() : number
表示获取X509证书序列号。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------ | ------------------ |
| number | 表示X509证书序列号 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let serialNumber = x509Cert.getSerialNumber();
}
});
```
### getIssuerName
getIssuerName() : DataBlob
表示获取X509证书颁发者名称。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| -------- | ---------------------- |
| DataBlob | 表示X509证书颁发者名称 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let issuerName = x509Cert.getIssuerName();
}
});
```
### getSubjectName
getSubjectName() : DataBlob
表示获取X509证书主体名称。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| -------- | -------------------- |
| DataBlob | 表示X509证书主体名称 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let subjectName = x509Cert.getSubjectName();
}
});
```
### getNotBeforeTime
getNotBeforeTime() : string
表示获取X509证书有效期起始时间。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------ | -------------------------- |
| string | 表示X509证书有效期起始时间 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let notBefore = x509Cert.getNotBeforeTime();
}
});
```
### getNotAfterTime
getNotAfterTime() : string
表示获取X509证书有效期截止时间。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------ | -------------------------- |
| string | 表示X509证书有效期截止时间 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let notAfter = x509Cert.getNotAfterTime();
}
});
```
### getSignature
getSignature() : DataBlob
表示获取X509证书签名数据。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| -------- | -------------------- |
| DataBlob | 表示X509证书签名数据 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let signature = x509Cert.getSignature();
}
});
```
### getSignatureAlgName
getSignatureAlgName() : string
表示获取X509证书签名算法名称。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------ | ------------------------ |
| string | 表示X509证书签名算法名称 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let sigAlgName = x509Cert.getSignatureAlgName();
}
});
```
### getSignatureAlgOid
getSignatureAlgOid() : string
表示获取X509证书签名算法OID。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------ | ----------------------- |
| string | 表示X509证书签名算法OID |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let sigAlgOid = x509Cert.getSignatureAlgOid();
}
});
```
### getSignatureAlgParams
getSignatureAlgParams() : DataBlob
表示获取X509证书签名算法参数。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| -------- | ------------------------ |
| DataBlob | 表示X509证书签名算法参数 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let sigAlgParams = x509Cert.getSignatureAlgParams();
}
});
```
### getKeyUsage
getKeyUsage() : DataBlob
表示获取X509证书秘钥用途。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| -------- | -------------------- |
| DataBlob | 表示X509证书秘钥用途 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let keyUsage = x509Cert.getKeyUsage();
}
});
```
### getExtKeyUsage
getExtKeyUsage() : DataArray
表示获取X509证书扩展秘钥用途。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| --------- | ------------------------ |
| DataArray | 表示X509证书扩展秘钥用途 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let extKeyUsage = x509Cert.getExtKeyUsage();
}
});
```
### getBasicConstraints
getBasicConstraints() : number
表示获取X509证书基本约束。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------ | -------------------- |
| number | 表示X509证书基本约束 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let basicConstraints = x509Cert.getBasicConstraints();
}
});
```
### getSubjectAltNames
getSubjectAltNames() : DataArray
表示获取X509证书主体可选名称。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| --------- | ------------------------ |
| DataArray | 表示X509证书主体可选名称 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let subjectAltNames = x509Cert.getSubjectAltNames();
}
});
```
### getIssuerAltNames
getIssuerAltNames() : DataArray
表示获取X509证书颁发者可选名称。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| --------- | -------------------------- |
| DataArray | 表示X509证书颁发者可选名称 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
Console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Cert success");
let issuerAltNames = x509Cert.getIssuerAltNames();
}
});
```
## cryptoFramework.createX509Crl
createX509Crl(inStream : EncodingBlob, callback : AsyncCallback\<X509Crl>) : void
表示创建X509证书吊销列表的对象。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | -------------------------- |
| inStream | EncodingBlob | 是 | 表示证书吊销列表序列化数据 |
| callback | AsyncCallback\<X509Crl> | 否 | 回调函数。表示证书吊销列表对象 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
}
});
```
## cryptoFramework.createX509Crl
createX509Crl(inStream : EncodingBlob) : Promise\<X509Crl>
表示创建X509证书吊销列表的对象。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------ | ---- | -------------------------- |
| inStream | EncodingBlob | 是 | 表示证书吊销列表序列化数据 |
**返回值**
| 类型 | 说明 |
| ------- | -------------------- |
| Promise\<X509Crl> | 表示证书吊销列表对象 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob).then(x509Crl => {
Console.log("createX509Crl success");
}, error => {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
## X509Crl
X509证书吊销列表对象。
### isRevoked
isRevoked(cert : X509Cert, callback : AsyncCallback\<boolean>) : void
表示检查证书是否吊销。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | -------------------- |
| cert | X509Cert | 是 | 表示被检查的证书对象 |
| callback | AsyncCallback\<boolean> | 否 | 回调函数。表示证书吊销状态,true表示已吊销,false表示未吊销 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
// 业务需自行生成X509Cert证书对象
let x509Cert = null;
x509Crl.isRevoked(x509Cert, function (error, isRevoked) {
if (error != null) {
Console.log("call isRevoked failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("call isRevoked success");
}
});
}
});
```
### isRevoked
isRevoked(cert : X509Cert) : Promise\<boolean>
表示检查证书是否吊销。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | -------- | ---- | -------------------- |
| cert | X509Cert | 是 | 表示被检查的证书对象 |
**返回值**
| 类型 | 说明 |
| ------- | ------------------------------------------------- |
| Promise\<boolean> | 表示证书吊销状态,true表示已吊销,false表示未吊销 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob).then(x509Crl => {
Console.log("createX509Crl success");
// 业务需自行生成X509Cert证书对象
let x509Cert = null;
x509Crl.isRevoked(x509Cert).then(isRevoked => {
Console.log("call isRevoked success");
}, error => {
Console.log("call isRevoked failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getType
getType() : string
表示获取证书吊销列表类型。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------ | -------------------- |
| string | 表示证书吊销列表类型 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
let type = x509Crl.getType();
}
});
```
### getEncoded
getEncoded(callback : AsyncCallback\<EncodingBlob>) : void
表示获取X509证书吊销列表的序列化数据。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | -------- |
| callback | AsyncCallback\<EncodingBlob> | 否 | 回调函数,表示X509证书吊销列表的序列化数据 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
x509Crl.getEncoded(function (error, data) {
if (error != null) {
Console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getEncoded success");
}
});
}
});
```
### getEncoded
getEncoded() : Promise\<EncodingBlob>
表示获取X509证书吊销列表的序列化数据。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------------ | -------------------------------- |
| Promise\<EncodingBlob> | 表示X509证书吊销列表的序列化数据 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob).then(x509Crl => {
Console.log("createX509Crl success");
x509Crl.getEncoded().then(result => {
Console.log("getEncoded success");
}, error => {
Console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### verify
verify(key : PubKey, callback : AsyncCallback\<void>) : void
表示对X509证书吊销列表进行验签。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ---------------------- |
| key | PubKey | 是 | 表示用于验签的公钥对象 |
| callback | AsyncCallback\<void> | 否 | 回调函数,使用AsyncCallback的第一个error参数判断是否验签成功,error为null表示成功,error不为null表示失败。 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
// 业务需通过AsyKeyGenerator生成PubKey
let pubKey = null;
x509Crl.verify(pubKey, function (error, data) {
if (error != null) {
Console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("verify success");
}
});
}
});
```
### verify
verify(key : PubKey) : Promise\<void>
表示对X509证书吊销列表进行验签。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ---------------------- |
| key | PubKey | 是 | 表示用于验签的公钥对象 |
**返回值**
| 类型 | 说明 |
| ---- | ------------------------------------------------------------ |
| Promise\<void> | 使用AsyncCallback的第一个error参数判断是否验签成功,error为null表示成功,error不为null表示失败 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob).then(x509Crl => {
Console.log("createX509Crl success");
// 业务需通过AsyKeyGenerator生成PubKey
let pubKey = null;
x509Crl.verify(pubKey).then(result => {
Console.log("verify success");
}, error => {
Console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getVersion
getVersion() : number
表示获取X509证书吊销列表的版本号。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------ | -------------------------------- |
| number | 表示获取X509证书吊销列表的版本号 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
let version = x509Crl.getVersion();
}
});
```
### getIssuerName
getIssuerName() : DataBlob
表示获取X509证书吊销列表颁发者名称。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| -------- | ------------------------------ |
| DataBlob | 表示X509证书吊销列表颁发者名称 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
let issuerName = x509Crl.getIssuerName();
}
});
```
### getLastUpdate
getLastUpdate() : string
表示获取X509证书吊销列表最后一次更新日期。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------ | ------------------------------------ |
| string | 表示X509证书吊销列表最后一次更新日期 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
let lastUpdate = x509Crl.getLastUpdate();
}
});
```
### getNextUpdate
getNextUpdate() : string
表示获取证书吊销列表下一次更新的日期。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------ | ------------------------------------ |
| string | 表示X509证书吊销列表下一次更新的日期 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
let nextUpdate = x509Crl.getNextUpdate();
}
});
```
### getRevokedCert
getRevokedCert(serialNumber : number, callback : AsyncCallback\<X509CrlEntry>) : void
表示通过指定证书序列号获取被吊销X509证书对象。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------------ | ------------- | ---- | -------------- |
| serialNumber | number | 是 | 表示证书序列号 |
| callback | AsyncCallback\<X509CrlEntry> | 否 | 回调函数。表示被吊销X509证书对象 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
// 业务需赋值为对应证书的序列号
let serialNumber = 1000;
x509Crl.getRevokedCert(serialNumber, function (error, entry) {
if (error != null) {
Console.log("getRevokedCert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getRevokedCert success");
}
});
}
});
```
### getRevokedCert
getRevokedCert(serialNumber : number) : Promise\<X509CrlEntry>
表示通过指定证书序列号获取被吊销X509证书对象。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------------ | ------ | ---- | -------------- |
| serialNumber | number | 是 | 表示证书序列号 |
**返回值**:
| 类型 | 说明 |
| ------------ | ---------------------- |
| Promise\<X509CrlEntry> | 表示被吊销X509证书对象 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob).then(x509Crl => {
Console.log("createX509Crl success");
// 业务需赋值为对应证书的序列号
let serialNumber = 1000;
x509Crl.getRevokedCert(serialNumber).then(entry => {
Console.log("getRevokedCert success");
}, error => {
Console.log("getRevokedCert failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getRevokedCertWithCert
getRevokedCertWithCert(cert : X509Cert, callback : AsyncCallback\<X509CrlEntry>) : void
表示通过指定证书对象获取被吊销X509证书对象。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------ |
| cert | X509Cert | 是 | 表示证书对象 |
| callback | AsyncCallback\<X509CrlEntry> | 否 | 回调函数,表示被吊销X509证书对象 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
// 业务需自行生成X509Cert证书对象
let x509Cert = null;
x509Crl.getRevokedCertWithCert(x509Cert, function (error, entry) {
if (error != null) {
Console.log("getRevokedCertWithCert failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getRevokedCertWithCert success");
}
});
}
});
```
### getRevokedCertWithCert
getRevokedCertWithCert(cert : X509Cert) : Promise\<X509CrlEntry>
表示通过指定证书对象获取被吊销X509证书对象。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | -------- | ---- | ------------ |
| cert | X509Cert | 是 | 表示证书对象 |
**返回值**:
| 类型 | 说明 |
| ------------ | ---------------------- |
| Promise\<X509CrlEntry> | 表示被吊销X509证书对象 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob).then(x509Crl => {
Console.log("createX509Crl success");
// 业务需自行生成X509Cert证书对象
let x509Cert = null;
x509Crl.getRevokedCertWithCert(x509Cert).then(entry => {
Console.log("getRevokedCertWithCert success");
}, error => {
Console.log("getRevokedCertWithCert failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getRevokedCerts
getRevokedCerts(callback : AsyncCallback<Array\<X509CrlEntry>>) : void
表示获取被吊销X509证书列表。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | -------- |
| callback | AsyncCallback<Array\<X509CrlEntry>> | 否 | 回调函数。表示被吊销X509证书列表 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
x509Crl.getRevokedCerts(function (error, array) {
if (error != null) {
Console.log("getRevokedCerts failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getRevokedCerts success");
}
});
}
});
```
### getRevokedCerts
getRevokedCerts() : Promise<Array\<X509CrlEntry>>
表示获取被吊销X509证书列表。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**:
| 类型 | 说明 |
| ------------------- | ---------------------- |
|Promise<Array\<X509CrlEntry>> | 表示被吊销X509证书列表 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob).then(x509Crl => {
Console.log("createX509Crl success");
x509Crl.getRevokedCerts().then(array => {
Console.log("getRevokedCerts success");
}, error => {
Console.log("getRevokedCerts failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getTbsInfo
getTbsInfo(callback : AsyncCallback\<DataBlob>) : void
表示获取证书吊销列表的tbsCertList信息。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | -------- |
| callback | AsyncCallback\<DataBlob> | 否 | 回调函数。表示证书吊销列表的tbsCertList信息 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
x509Crl.getTbsInfo(function (error, tbsInfo) {
if (error != null) {
Console.log("getTbsInfo failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getTbsInfo success");
}
});
}
});
```
### getTbsInfo
getTbsInfo() : Promise\<DataBlob>
表示获取证书吊销列表的tbsCertList信息。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**:
| 类型 | 说明 |
| -------- | --------------------------------- |
| Promise\<DataBlob> | 表示证书吊销列表的tbsCertList信息 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob).then(x509Crl => {
Console.log("createX509Crl success");
x509Crl.getTbsInfo().then(tbsInfo => {
Console.log("getTbsInfo success");
}, error => {
Console.log("getTbsInfo failed, errCode: " + error.code + ", errMsg: " + error.message);
});
}, error => {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getSignature
getSignature() : DataBlob
表示获取X509证书吊销列表的签名数据。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| -------- | ------------------------------ |
| DataBlob | 表示X509证书吊销列表的签名数据 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
let signature = x509Crl.getSignature();
}
});
```
### getSignatureAlgName
getSignatureAlgName() : string
表示获取X509证书吊销列表签名的算法名称。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------ | -------------------------------- |
| string | 表示X509证书吊销列表签名的算法名 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
let sigAlgName = x509Crl.getSignatureAlgName();
}
});
```
### getSignatureAlgOid
getSignatureAlgOid() : string
表示获取X509证书吊销列表签名的算法OID。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------ | ----------------------------------- |
| string | 表示X509证书吊销列表签名的算法OID。 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
let sigAlgOid = x509Crl.getSignatureAlgOid();
}
});
```
### getSignatureAlgParams
getSignatureAlgParams() : DataBlob
表示获取X509证书吊销列表签名的算法参数。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| -------- | ---------------------------------- |
| DataBlob | 表示X509证书吊销列表签名的算法参数 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 证书吊销列表二进制数据,需业务自行赋值
let encodingData = null;
let encodingBlob = {
data: encodingData,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
cryptoFramework.createX509Crl(encodingBlob, function (error, x509Crl) {
if (error != null) {
Console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("createX509Crl success");
let sigAlgParams = x509Crl.getSignatureAlgParams();
}
});
```
## cryptoFramework.createCertChainValidator
createCertChainValidator(algorithm :string) : CertChainValidator
表示创建证书链校验器对象。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------ | ---- | -------------------- |
| algorithm | string | 是 | 表示证书链校验器算法 |
**返回值**
| 类型 | 说明 |
| ------------------ | -------------------- |
| CertChainValidator | 表示证书链校验器对象 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
let validator = cryptoFramework.createCertChainValidator("PKIX");
```
## CertChainValidator
证书链校验器对象。
### validate
validate(certChain : CertChainData, callback : AsyncCallback\<void>) : void
表示校验X509证书链。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------------- | ---- | ------------------------ |
| certChain | CertChainData | 是 | 表示X509证书链序列化数据 |
| callback | AsyncCallback\<void> | 否 | 回调函数。使用AsyncCallback的第一个error参数判断是否校验成功,error为null表示成功,error不为null表示失败 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
let validator = cryptoFramework.createCertChainValidator("PKIX");
// 证书链二进制数据,需业务自行赋值
let encodingData = null;
// 证书链包含的证书个数,需业务自行赋值
let certCount = 2;
let certChainData = {
data: encodingData,
count: certCount,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
validator.validate(certChainData, function (error, data) {
if (error != null) {
Console.log("validate failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("validate success");
}
});
```
### validate
validate(certChain : CertChainData) : Promise\<void>
表示校验X509证书链。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------------- | ---- | ------------------------ |
| certChain | CertChainData | 是 | 表示X509证书链序列化数据。使用AsyncCallback的第一个error参数判断是否校验成功,error为null表示成功,error不为null表示失败 |
**返回值**
| 类型 | 说明 |
| ---- | ------------------------------------------------------------ |
| Promise\<void> | Promise对象 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
let validator = cryptoFramework.createCertChainValidator("PKIX");
// 证书链二进制数据,需业务自行赋值
let encodingData = null;
// 证书链包含的证书个数,需业务自行赋值
let certCount = 2;
let certChainData = {
data: encodingData,
count: certCount,
// 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
};
validator.validate(certChainData).then(result => {
Console.log("validate success");
}, error => {
Console.log("validate failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### algorithm
algorithm : string
表示X509证书链校验器算法名称。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------ | ------------------------ |
| string | 表示证书链校验器算法名称 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
let validator = cryptoFramework.createCertChainValidator("PKIX");
let algorithm = validator.algorithm;
```
## X509CrlEntry
被吊销证书对象。
### getEncoded
getEncoded(callback : AsyncCallback\<EncodingBlob>) : void
表示获取被吊销证书的序列化数据。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | -------- |
| callback | AsyncCallback\<EncodingBlob> | 否 | 回调函数。表示被吊销证书的序列化数据 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 业务需通过X509Crl的getRevokedCert相关方法获取X509CrlEntry
let x509CrlEntry = null;
x509CrlEntry.getEncoded(function (error, data) {
if (error != null) {
Console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getEncoded success");
}
});
```
### getEncoded
getEncoded() : Promise\<EncodingBlob>
表示获取被吊销证书的序列化数据。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------------ | -------------------------- |
| Promise\<EncodingBlob> | 表示被吊销证书的序列化数据 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 业务需通过X509Crl的getRevokedCert相关方法获取X509CrlEntry
let x509CrlEntry = null;
x509CrlEntry.getEncoded().then(result => {
Console.log("getEncoded success");
}, error => {
Console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getSerialNumber
getSerialNumber() : number
表示获取被吊销证书的序列号。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------ | ---------------------- |
| number | 表示被吊销证书的序列号 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 业务需通过X509Crl的getRevokedCert相关方法获取X509CrlEntry
let x509CrlEntry = null;
let serialNumber = x509CrlEntry.getSerialNumber();
```
### getCertIssuer
getCertIssuer(callback : AsyncCallback\<DataBlob>) : void
表示获取被吊销证书的颁发者信息。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | -------- |
| callback | AsyncCallback\<DataBlob> | 否 | 回调函数。表示被吊销证书的颁发者信息 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 业务需通过X509Crl的getRevokedCert相关方法获取X509CrlEntry
let x509CrlEntry = null;
x509CrlEntry.getCertIssuer(function (error, issuer) {
if (error != null) {
Console.log("getCertIssuer failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getCertIssuer success");
}
});
```
### getCertIssuer
getCertIssuer() : Promise\<DataBlob>
表示获取被吊销证书的颁发者信息。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| -------- | -------------------------- |
| Promise\<DataBlob> | 表示被吊销证书的颁发者信息 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 业务需通过X509Crl的getRevokedCert相关方法获取X509CrlEntry
let x509CrlEntry = null;
x509CrlEntry.getCertIssuer().then(issuer => {
Console.log("getCertIssuer success");
}, error => {
Console.log("getCertIssuer failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
### getRevocationDate
getRevocationDate(callback : AsyncCallback\<string>) : void
表示获取证书被吊销的日期。
**系统能力**:SystemCapability.Security.CryptoFramework
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | -------- |
| callback | AsyncCallback\<string> | 否 | 回调函数。表示证书被吊销的日期 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 业务需通过X509Crl的getRevokedCert相关方法获取X509CrlEntry
let x509CrlEntry = null;
x509CrlEntry.getRevocationDate(function (error, date) {
if (error != null) {
Console.log("getRevocationDate failed, errCode: " + error.code + ", errMsg: " + error.message);
} else {
Console.log("getRevocationDate success");
}
});
```
### getRevocationDate
getRevocationDate() : Promise\<string>
表示获取证书被吊销的日期。
**系统能力**:SystemCapability.Security.CryptoFramework
**返回值**
| 类型 | 说明 |
| ------ | -------------------- |
| Promise\<string> | 表示证书被吊销的日期 |
**示例**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
// 业务需通过X509Crl的getRevokedCert相关方法获取X509CrlEntry
let x509CrlEntry = null;
x509CrlEntry.getRevocationDate().then(date => {
Console.log("getRevocationDate success");
}, error => {
Console.log("getRevocationDate failed, errCode: " + error.code + ", errMsg: " + error.message);
});
```
...@@ -29,7 +29,7 @@ export default class UserTestRunner implements TestRunner { ...@@ -29,7 +29,7 @@ export default class UserTestRunner implements TestRunner {
onPrepare() { onPrepare() {
console.log("Trigger onPrepare") console.log("Trigger onPrepare")
} }
onRun(){} onRun(){}
}; };
``` ```
...@@ -50,6 +50,6 @@ export default class UserTestRunner implements TestRunner { ...@@ -50,6 +50,6 @@ export default class UserTestRunner implements TestRunner {
onPrepare() { onPrepare() {
console.log("Trigger onRun") console.log("Trigger onRun")
} }
onRun(){} onRun(){}
}; };
``` ```
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
> 该模块从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 该模块从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 导入模块 ## 导入模块
```js ```js
import userFileManager from '@ohos.filemanagement.userfile_manager'; import userFileManager from '@ohos.filemanagement.userfile_manager';
``` ```
...@@ -36,6 +37,7 @@ getUserFileMgr(context: Context): UserFileManager ...@@ -36,6 +37,7 @@ getUserFileMgr(context: Context): UserFileManager
const context = getContext(this); const context = getContext(this);
let userFileMgr = userfilemanager.getUserFileMgr(context); let userFileMgr = userfilemanager.getUserFileMgr(context);
``` ```
## userFileManager.getUserFileMgr ## userFileManager.getUserFileMgr
getUserFileMgr(): UserFileManager getUserFileMgr(): UserFileManager
...@@ -59,9 +61,10 @@ getUserFileMgr(): UserFileManager ...@@ -59,9 +61,10 @@ getUserFileMgr(): UserFileManager
```js ```js
let userFileMgr = userfilemanager.getUserFileMgr(); let userFileMgr = userfilemanager.getUserFileMgr();
``` ```
## UserFileManager ## UserFileManager
### getPublicDirectory
### getPublicDirectory
getPublicDirectory(type: DirectoryType, callback: AsyncCallback&lt;string>): void; getPublicDirectory(type: DirectoryType, callback: AsyncCallback&lt;string>): void;
......
...@@ -249,7 +249,7 @@ ...@@ -249,7 +249,7 @@
| End | 元素在主轴方向尾部对齐,最后一个元素与行尾对齐,其他元素与后一个对齐。 | | End | 元素在主轴方向尾部对齐,最后一个元素与行尾对齐,其他元素与后一个对齐。 |
| SpaceBetween | Flex主轴方向均匀分配弹性元素,相邻元素之间距离相同。第一个元素与行首对齐,最后一个元素与行尾对齐。 | | SpaceBetween | Flex主轴方向均匀分配弹性元素,相邻元素之间距离相同。第一个元素与行首对齐,最后一个元素与行尾对齐。 |
| SpaceAround | Flex主轴方向均匀分配弹性元素,相邻元素之间距离相同。第一个元素到行首的距离和最后一个元素到行尾的距离是相邻元素之间距离的一半。 | | SpaceAround | Flex主轴方向均匀分配弹性元素,相邻元素之间距离相同。第一个元素到行首的距离和最后一个元素到行尾的距离是相邻元素之间距离的一半。 |
| SpaceEvenly | 、第一个元素与行首的间距、最后一个元素到行尾的间距都完全一样。 | | SpaceEvenly | Flex主轴方向均匀分配弹性元素,相邻元素之间的距离、第一个元素与行首的间距、最后一个元素到行尾的间距都完全一样。 |
## ItemAlign ## ItemAlign
......
...@@ -21,7 +21,7 @@ RichText(content:string) ...@@ -21,7 +21,7 @@ RichText(content:string)
| 参数名 | 参数类型 | 必填 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| ------- | -------- | ------------- | -------- | | ------- | -------- | ------------- | -------- |
| content | string | 是 | 表示HTML格式的字符串。 | | content | string | 是 | 表示HTML格式的字符串。 |
## 事件 ## 事件
...@@ -55,27 +55,27 @@ RichText(content:string) ...@@ -55,27 +55,27 @@ RichText(content:string)
@Entry @Entry
@Component @Component
struct RichTextExample { struct RichTextExample {
@State data: string = "<h1 style='text-align: center;'>h1标题</h1>" + @State data: string = '<h1 style="text-align: center;">h1标题</h1>' +
"<h1 style='text-align: center;'><i>h1斜体</i></h1>" + '<h1 style="text-align: center;"><i>h1斜体</i></h1>' +
"<h1 style='text-align: center;'><u>h1下划线</u></h1>" + '<h1 style="text-align: center;"><u>h1下划线</u></h1>' +
"<h2 style='text-align: center;'>h2标题</h2>" + '<h2 style="text-align: center;">h2标题</h2>' +
"<h3 style='text-align: center;'>h3标题</h3>" + '<h3 style="text-align: center;">h3标题</h3>' +
"<p style='text-align: center;'>p常规</p><hr/>" + '<p style="text-align: center;">p常规</p><hr/>' +
"<div style='width: 500px;height: 500px;border: 1px solid;margin: 0auto;'>" + '<div style="width: 500px;height: 500px;border: 1px solid;margin: 0auto;">' +
"<p style='font-size: 35px;text-align: center;font-weight: bold; color: rgb(24,78,228)'>字体大小35px,行高45px</p>" + '<p style="font-size: 35px;text-align: center;font-weight: bold; color: rgb(24,78,228)">字体大小35px,行高45px</p>' +
"<p style='background-color: #e5e5e5;line-height: 45px;font-size: 35px;text-indent: 2em;'>" + '<p style="background-color: #e5e5e5;line-height: 45px;font-size: 35px;text-indent: 2em;">' +
"<p>这是一段文字这是一段文字这是一段文字这是一段文字这是一段文字这是一段文字这是一段文字这是一段文字这是一段文字</p>" '<p>这是一段文字这是一段文字这是一段文字这是一段文字这是一段文字这是一段文字这是一段文字这是一段文字这是一段文字</p>';
build() { build() {
Flex({direction: FlexDirection.Column,alignItems: ItemAlign.Center, Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center,
justifyContent: FlexAlign.Center }){ justifyContent: FlexAlign.Center }) {
RichText(this.data) RichText(this.data)
.onStart(()=>{ .onStart(() => {
console.info("RichText onStart") console.info('RichText onStart');
}) })
.onComplete(()=>{ .onComplete(() => {
console.info("RichText onComplete") console.info('RichText onComplete');
}) })
} }
} }
} }
......
...@@ -16,7 +16,7 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num ...@@ -16,7 +16,7 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num
| 参数名称 | 参数类型 | 必填 | 参数描述 | | 参数名称 | 参数类型 | 必填 | 参数描述 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| fingers | number | 否 | 触发滑动的最少手指数,默认为1,最小为1指,最大为10指。<br/>默认值:1 | | fingers | number | 否 | 触发滑动的最少手指数,默认为1,最小为1指,最大为10指。<br/>默认值:1 |
| direction | SwipeDirection | 否 | 触发滑动手势的滑动方向。<br/>默认值:SwipeDirection.All | | direction | [SwipeDirection](#swipedirection枚举说明) | 否 | 触发滑动手势的滑动方向。<br/>默认值:SwipeDirection.All |
| speed | number | 否 | 识别滑动的最小速度(默认为100VP/秒)。<br/>默认值:100 | | speed | number | 否 | 识别滑动的最小速度(默认为100VP/秒)。<br/>默认值:100 |
## SwipeDirection枚举说明 ## SwipeDirection枚举说明
......
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
## 接口 ## 接口
方法1:Badge(value: {count: number, position?: BadgePosition, maxCount?: number, style: BadgeStyle}) **方法1:** Badge(value: {count: number, position?: BadgePosition, maxCount?: number, style: BadgeStyle})
创建数字标记组件。 创建数字标记组件。
...@@ -26,35 +26,38 @@ ...@@ -26,35 +26,38 @@
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| count | number | 是 | - | 设置提醒消息数。 | | count | number | 是 | - | 设置提醒消息数。 |
| position | BadgePosition | 否 | BadgePosition.RightTop | 设置提示点显示位置。 | | position | [BadgePosition](#badgeposition枚举说明) | 否 | BadgePosition.RightTop | 设置提示点显示位置。 |
| maxCount | number | 否 | 99 | 最大消息数,超过最大消息时仅显示maxCount+。 | | maxCount | number | 否 | 99 | 最大消息数,超过最大消息时仅显示maxCount+。 |
| style | BadgeStyle | 是 | - | Badge组件可设置样式,支持设置文本颜色、尺寸、圆点颜色和尺寸。 | | style | [BadgeStyle](#badgestyle对象说明) | 是 | - | Badge组件可设置样式,支持设置文本颜色、尺寸、圆点颜色和尺寸。 |
方法2: Badge(value: {value: string, position?: BadgePosition, style: BadgeStyle}) **方法2:** Badge(value: {value: string, position?: BadgePosition, style: BadgeStyle})
根据字符串创建标记组件。 根据字符串创建标记组件。
- 参数 **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- | | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| value | string | 是 | - | 提示内容的文本字符串。 | | -------- | -------- | -------- | -------- | -------- |
| position | BadgePosition | 否 | BadgePosition.RightTop | 设置提示点显示位置。 | | value | string | 是 | - | 提示内容的文本字符串。 |
| style | BadgeStyle | 是 | - | Badge组件可设置样式,支持设置文本颜色、尺寸、圆点颜色和尺寸。 | | position | [BadgePosition](#badgeposition枚举说明) | 否 | BadgePosition.RightTop | 设置提示点显示位置。 |
| style | [BadgeStyle](#badgestyle对象说明) | 是 | - | Badge组件可设置样式,支持设置文本颜色、尺寸、圆点颜色和尺寸。 |
- BadgeStyle对象说明
| 名称 | 类型 | 必填 | 默认值 | 描述 | ## BadgeStyle对象说明
| -------- | -------- | -------- | -------- | -------- |
| color | [ResourceColor](ts-types.md) | 否 | Color.White | 文本颜色。 | | 名称 | 类型 | 必填 | 默认值 | 描述 |
| fontSize | number&nbsp;\|&nbsp;string | 否 | 10 | 文本大小。 | | -------- | -------- | -------- | -------- | -------- |
| badgeSize | number&nbsp;\|&nbsp;string | 是 | - | badge的大小。 | | color | [ResourceColor](ts-types.md) | 否 | Color.White | 文本颜色。 |
| badgeColor | [ResourceColor](ts-types.md) | 否 | Color.Red | badge的颜色。 | | fontSize | number&nbsp;\|&nbsp;string | 否 | 10 | 文本大小。 |
| badgeSize | number&nbsp;\|&nbsp;string | 是 | - | badge的大小。 |
- BadgePosition枚举说明 | badgeColor | [ResourceColor](ts-types.md) | 否 | Color.Red | badge的颜色。 |
| 名称 | 描述 |
| -------- | -------- | ## BadgePosition枚举说明
| RightTop | 圆点显示在右上角。 |
| Right | 圆点显示在右侧纵向居中。 | | 名称 | 描述 |
| Left | 圆点显示在左侧纵向居中。 | | -------- | -------- |
| RightTop | 圆点显示在右上角。 |
| Right | 圆点显示在右侧纵向居中。 |
| Left | 圆点显示在左侧纵向居中。 |
## 示例 ## 示例
......
...@@ -242,8 +242,6 @@ struct FlexExample4 { ...@@ -242,8 +242,6 @@ struct FlexExample4 {
![zh-cn_image_0000001174422904](figures/zh-cn_image_0000001174422904.jpg) ![zh-cn_image_0000001174422904](figures/zh-cn_image_0000001174422904.jpg)
![zh-cn_image_0000001219662653](figures/zh-cn_image_0000001219662653.gif)
```ts ```ts
// xxx.ets // xxx.ets
@Component @Component
......
...@@ -28,7 +28,7 @@ Scroll(scroller?: Scroller) ...@@ -28,7 +28,7 @@ Scroll(scroller?: Scroller)
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。<br/>默认值:BarState.Off | | scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。<br/>默认值:BarState.Off |
| scrollBarColor | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;Color | 设置滚动条的颜色。 | | scrollBarColor | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;Color | 设置滚动条的颜色。 |
| scrollBarWidth | string&nbsp;\|&nbsp;number | 设置滚动条的宽度。 | | scrollBarWidth | string&nbsp;\|&nbsp;number | 设置滚动条的宽度。 |
| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | 设置滑动效果,目前支持的滑动效果参见EdgeEffect的枚举说明。<br/>默认值:EdgeEffect.Spring | | edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | 设置滑动效果,目前支持的滑动效果参见EdgeEffect的枚举说明。<br/>默认值:EdgeEffect.None |
## ScrollDirection枚举说明 ## ScrollDirection枚举说明
| 名称 | 描述 | | 名称 | 描述 |
......
...@@ -17,28 +17,28 @@ ...@@ -17,28 +17,28 @@
Circle(options?: {width?: string | number, height?: string | number}) Circle(options?: {width?: string | number, height?: string | number})
- 参数 - 参数
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| width | string \| number | 否 | 0 | 宽度。 | | width | string \| number | 否 | 宽度。<br>默认值:0 |
| height | string \| number | 否 | 0 | 高度。 | | height | string \| number | 否 | 高度。<br>默认值:0 |
## 属性 ## 属性
除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性:
| 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 | | 参数名称 | 参数类型 | 必填 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| fill | [ResourceColor](ts-types.md) | Color.Black | 否 | 设置填充区域颜色。 | | fill | [ResourceColor](ts-types.md) | 否 | 设置填充区域颜色。<br>默认值:Color.Black |
| fillOpacity | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource类型) | 1 | 否 | 设置填充区域透明度。 | | fillOpacity | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource类型) | 否 | 设置填充区域透明度。<br>默认值:1 |
| stroke | [ResourceColor](ts-types.md) | Color.Black | 否 | 设置线条颜色。 | | stroke | [ResourceColor](ts-types.md) | 否 | 设置线条颜色。<br>默认值:Color.Black |
| strokeDashArray | Array&lt;Length&gt; | [] | 否 | 设置线条间隙。 | | strokeDashArray | Array&lt;Length&gt; | 否 | 设置线条间隙。<br>默认值:[] |
| strokeDashOffset | number&nbsp;\|&nbsp;string | 0 | 否 | 线条绘制起点的偏移量。 | | strokeDashOffset | number&nbsp;\|&nbsp;string | 否 | 线条绘制起点的偏移量。<br>默认值:0 |
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 否 | 设置线条端点绘制样式。 | | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | 否 | 设置线条端点绘制样式。<br>默认值:LineCapStyle.Butt |
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 否 | 设置线条拐角绘制样式。 | | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | 否 | 设置线条拐角绘制样式。<br>默认值:LineJoinStyle.Miter |
| strokeMiterLimit | number&nbsp;\|&nbsp;string | 4 | 否 | 设置锐角绘制成斜角的极限值。 | | strokeMiterLimit | number&nbsp;\|&nbsp;string | 否 | 设置锐角绘制成斜角的极限值。<br>默认值:4 |
| strokeOpacity | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource类型) | 1 | 否 | 设置线条透明度。 | | strokeOpacity | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource类型) | 否 | 设置线条透明度。<br>默认值:1 |
| strokeWidth | Length | 1 | 否 | 设置线条宽度。 | | strokeWidth | Length | 否 | 设置线条宽度。<br>默认值:1 |
| antiAlias | boolean | true | 否 | 是否开启抗锯齿效果。 | | antiAlias | boolean | 否 | 是否开启抗锯齿效果。<br>默认值:true |
## 示例 ## 示例
...@@ -49,12 +49,18 @@ Circle(options?: {width?: string | number, height?: string | number}) ...@@ -49,12 +49,18 @@ Circle(options?: {width?: string | number, height?: string | number})
@Component @Component
struct CircleExample { struct CircleExample {
build() { build() {
Flex({ justifyContent: FlexAlign.SpaceAround }) { Column({ space: 10 }) {
// 绘制一个直径为150的圆 // 绘制一个直径为150的圆
Circle({ width: 150, height: 150 }) Circle({ width: 150, height: 150 })
// 绘制一个直径为150的圆 // 绘制一个直径为150、线条为红色虚线的圆环(宽高设置不一致时以短边为直径)
Circle().width(150).height(150) Circle()
}.width('100%').margin({ top: 5 }) .width(150)
.height(200)
.fillOpacity(0)
.strokeWidth(3)
.stroke(Color.Red)
.strokeDashArray([1, 2])
}.width('100%')
} }
} }
``` ```
......
...@@ -50,12 +50,17 @@ ellipse(options?: {width?: string | number, height?: string | number}) ...@@ -50,12 +50,17 @@ ellipse(options?: {width?: string | number, height?: string | number})
@Component @Component
struct EllipseExample { struct EllipseExample {
build() { build() {
Flex({ justifyContent: FlexAlign.SpaceAround }) { Column({ space: 10 }) {
// 在一个 150 * 80 的矩形框中绘制一个椭圆 // 绘制一个 150 * 80 的椭圆
Ellipse({ width: 150, height: 80 }) Ellipse({ width: 150, height: 80 })
// 在一个 150 * 80 的矩形框中绘制一个椭圆 // 绘制一个 150 * 100 、线条为蓝色的椭圆环
Ellipse().width(150).height(80) Ellipse()
}.width('100%').margin({ top: 5 }) .width(150)
.height(100)
.fillOpacity(0)
.stroke(Color.Blue)
.strokeWidth(3)
}.width('100%')
} }
} }
``` ```
......
...@@ -24,17 +24,17 @@ Line(value?: {width?: string | number, height?: string | number}) ...@@ -24,17 +24,17 @@ Line(value?: {width?: string | number, height?: string | number})
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | string \| number | 否 | 0 | 宽度。 | | width | string \| number | 否 | 0 | 宽度。 |
| height | string \| number | 否 | 0 | 高度。 | | height | string \| number | 否 | 0 | 高度。 |
## 属性 ## 属性
除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性:
| 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 | | 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| startPoint | Array&lt;Length&gt; | [0,&nbsp;0] | 否 | 直线起点坐标点(相对坐标),单位vp。 | | startPoint | Array&lt;Length&gt; | [0,&nbsp;0] | 否 | 直线起点坐标点(相对坐标),单位vp。 |
| endPoint | Array&lt;Length&gt; | [0,&nbsp;0] | 否 | 直线终点坐标点(相对坐标),单位vp。 | | endPoint | Array&lt;Length&gt; | [0,&nbsp;0] | 否 | 直线终点坐标点(相对坐标),单位vp。 |
...@@ -59,13 +59,31 @@ Line(value?: {width?: string | number, height?: string | number}) ...@@ -59,13 +59,31 @@ Line(value?: {width?: string | number, height?: string | number})
@Component @Component
struct LineExample { struct LineExample {
build() { build() {
Column() { Column({ space: 10 }) {
Line().startPoint([0, 0]).endPoint([50, 100]) // 线条绘制的起止点坐标均是相对于Line组件本身绘制区域的坐标
Line({ width: 50, height: 50 }).startPoint([0, 0]).endPoint([100, 100]) Line()
Line().width(200).height(200).startPoint([50, 50]).endPoint([150, 150]) .startPoint([0, 0])
}.margin({ top: 5 }) .endPoint([50, 100])
.backgroundColor('#F5F5F5')
Line()
.width(200)
.height(200)
.startPoint([50, 50])
.endPoint([150, 150])
.strokeWidth(5)
.stroke(Color.Orange)
.strokeOpacity(0.5)
.backgroundColor('#F5F5F5')
// 当坐标点设置的值超出Line组件的宽高范围时,线条会画出组件绘制区域
Line({ width: 50, height: 50 })
.startPoint([0, 0])
.endPoint([100, 100])
.strokeWidth(3)
.strokeDashArray([1, 3])
.backgroundColor('#F5F5F5')
}
} }
} }
``` ```
![zh-cn_image_0000001219982725](figures/zh-cn_image_0000001219982725.jpg) ![zh-cn_image_0000001219982725](figures/zh-cn_image_0000001219982725.png)
...@@ -67,24 +67,75 @@ commands支持的绘制命令如下: ...@@ -67,24 +67,75 @@ commands支持的绘制命令如下:
@Component @Component
struct PathExample { struct PathExample {
build() { build() {
Column({ space: 5 }) { Column({ space: 10 }) {
Text('Straight line').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('Straight line')
// 绘制一条长900px,宽3vp的直线。 .fontSize(11)
Path().width(300).height(10).commands('M0 0 L900 0').stroke(Color.Black).strokeWidth(3) .fontColor(0xCCCCCC)
.width('90%')
Text('Straight line graph').fontSize(9).fontColor(0xCCCCCC).width('90%') // 绘制一条长900px,宽3vp的直线
Flex({ justifyContent: FlexAlign.SpaceAround }) { Path()
Path().width(100).height(100).commands('M150 0 L300 300 L0 300 Z') .width(300)
Path().width(100).height(100).commands('M0 0 H300 V300 H0 Z') .height(10)
Path().width(100).height(100).commands('M150 0 L0 150 L60 300 L240 300 L300 150 Z') .commands('M0 0 L900 0')
.stroke(Color.Black)
.strokeWidth(3)
Text('Straight line graph')
.fontSize(11)
.fontColor(0xCCCCCC)
.width('90%')
// 绘制直线图形
Row({ space: 20 }) {
Path()
.width(100)
.height(100)
.commands('M150 0 L300 300 L0 300 Z')
.fillOpacity(0)
.stroke(Color.Black)
.strokeWidth(3)
Path()
.width(100)
.height(100)
.commands('M0 0 H300 V300 H0 Z')
.fillOpacity(0)
.stroke(Color.Black)
.strokeWidth(3)
Path()
.width(100)
.height(100)
.commands('M150 0 L0 150 L60 300 L240 300 L300 150 Z')
.fillOpacity(0)
.stroke(Color.Black)
.strokeWidth(3)
}.width('100%') }.width('100%')
Text('Curve graphics').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('Curve graphics').fontSize(11).fontColor(0xCCCCCC).width('90%')
Flex({ justifyContent: FlexAlign.SpaceAround }) { // 绘制弧线图形
Path().width(100).height(100).commands("M0 300 S150 0 300 300 Z") Row({ space: 20 }) {
Path().width(100).height(100).commands('M0 150 C0 150 150 0 300 150 L150 300 Z') Path()
.width(100)
.height(100)
.commands("M0 300 S150 0 300 300 Z")
.fillOpacity(0)
.stroke(Color.Black)
.strokeWidth(3)
Path()
.width(100)
.height(100)
.commands('M0 150 C0 150 150 0 300 150 L150 300 Z')
.fillOpacity(0)
.stroke(Color.Black)
.strokeWidth(3)
Path()
.width(100)
.height(100)
.commands('M0 200 A30 20 20 0 0 250 200 Z')
.fillOpacity(0)
.stroke(Color.Black)
.strokeWidth(3)
} }
}.width('100%').margin({ top: 5 }) }.width('100%')
.margin({ top: 5 })
} }
} }
``` ```
......
...@@ -18,17 +18,17 @@ Polygon(value?: {width?: string | number, height?: string | number}) ...@@ -18,17 +18,17 @@ Polygon(value?: {width?: string | number, height?: string | number})
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | string \| number | 否 | 0 | 宽度。 | | width | string \| number | 否 | 0 | 宽度。 |
| height | string \| number | 否 | 0 | 高度。 | | height | string \| number | 否 | 0 | 高度。 |
## 属性 ## 属性
除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性:
| 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 | | 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| points | Array&lt;Point&gt; | [] | 否 | 多边形的顶点坐标列表。 | | points | Array&lt;Point&gt; | [] | 否 | 多边形的顶点坐标列表。 |
| fill | [ResourceColor](ts-types.md) | Color.Black | 否 | 设置填充区域颜色。 | | fill | [ResourceColor](ts-types.md) | Color.Black | 否 | 设置填充区域颜色。 |
...@@ -60,18 +60,25 @@ Polygon(value?: {width?: string | number, height?: string | number}) ...@@ -60,18 +60,25 @@ Polygon(value?: {width?: string | number, height?: string | number})
@Component @Component
struct PolygonExample { struct PolygonExample {
build() { build() {
Column({ space: 5 }) { Column({ space: 10 }) {
Flex({ justifyContent: FlexAlign.SpaceAround }) { // 在 100 * 100 的矩形框中绘制一个三角形,起点(0, 0),经过(50, 100),终点(100, 0)
// 在 100 * 100 的矩形框中绘制一个三角形,起点(0, 0),经过(50, 100),终点(100, 0) Polygon({ width: 100, height: 100 })
Polygon({ width: 100, height: 100 }).points([[0, 0], [50, 100], [100, 0]]) .points([[0, 0], [50, 100], [100, 0]])
// 在 100 * 100 的矩形框中绘制一个四边形,起点(0, 0),经过(0, 100)和(100, 100),终点(100, 0) .fill(Color.Green)
Polygon().width(100).height(100).points([[0, 0], [0, 100], [100, 100], [100, 0]]) // 在 100 * 100 的矩形框中绘制一个四边形,起点(0, 0),经过(0, 100)和(100, 100),终点(100, 0)
// 在 100 * 100 的矩形框中绘制一个五边形,起点(50, 0),依次经过(0, 50)、(20, 100)和(80, 100),终点(100, 50) Polygon().width(100).height(100)
Polygon().width(100).height(100).points([[50, 0], [0, 50], [20, 100], [80, 100], [100, 50]]) .points([[0, 0], [0, 100], [100, 100], [100, 0]])
}.width('100%') .fillOpacity(0)
}.margin({ top: 5 }) .strokeWidth(5)
.stroke(Color.Blue)
// 在 100 * 100 的矩形框中绘制一个五边形,起点(50, 0),依次经过(0, 50)、(20, 100)和(80, 100),终点(100, 50)
Polygon().width(100).height(100)
.points([[50, 0], [0, 50], [20, 100], [80, 100], [100, 50]])
.fill(Color.Red)
.fillOpacity(0.6)
}.width('100%').margin({ top: 10 })
} }
} }
``` ```
![zh-cn_image_0000001174582856](figures/zh-cn_image_0000001174582856.gif) ![zh-cn_image_0000001174582856](figures/zh-cn_image_0000001174582856.png)
...@@ -18,19 +18,19 @@ Polyline(value?: {width?: string | number, height?: string | number}) ...@@ -18,19 +18,19 @@ Polyline(value?: {width?: string | number, height?: string | number})
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | string \| number | 否 | 0 | 宽度。 | | width | string \| number | 否 | 0 | 宽度。 |
| height | string \| number | 否 | 0 | 高度。 | | height | string \| number | 否 | 0 | 高度。 |
## 属性 ## 属性
除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性:
| 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 | | 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| points | Array&lt;Point&gt; | [] | 否 | 折线经过坐标点列表。 | | points | Array&lt;Point&gt; | [] | 否 | 折线经过坐标点列表。 |
| fill | [ResourceColor](ts-types.md) | Color.Black | 否 | 设置填充区域颜色。 | | fill | [ResourceColor](ts-types.md) | Color.Black | 否 | 设置填充区域颜色。 |
| fillOpacity | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource类型) | 1 | 否 | 设置填充区域透明度。 | | fillOpacity | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource类型) | 1 | 否 | 设置填充区域透明度。 |
| stroke | [ResourceColor](ts-types.md) | Color.Black | 否 | 设置线条颜色。 | | stroke | [ResourceColor](ts-types.md) | Color.Black | 否 | 设置线条颜色。 |
...@@ -59,16 +59,28 @@ Polyline(value?: {width?: string | number, height?: string | number}) ...@@ -59,16 +59,28 @@ Polyline(value?: {width?: string | number, height?: string | number})
@Component @Component
struct PolylineExample { struct PolylineExample {
build() { build() {
Column({ space: 5 }) { Column({ space: 10 }) {
Flex({ justifyContent: FlexAlign.SpaceAround }) { // 在 100 * 100 的矩形框中绘制一段折线,起点(0, 0),经过(20,60),到达终点(100, 100)
// 在 100 * 100 的矩形框中绘制一段折线,起点(0, 0),经过(20,60),到达终点(100, 100) Polyline({ width: 100, height: 100 })
Polyline({ width: 100, height: 100 }).points([[0, 0], [20, 60], [100, 100]]) .points([[0, 0], [20, 60], [100, 100]])
// 在 100 * 100 的矩形框中绘制一段折线,起点(0, 0),经过(0,100),到达终点(100, 100) .fillOpacity(0)
Polyline().width(100).height(100).points([[0, 0], [0, 100], [100, 100]]) .stroke(Color.Blue)
}.width('100%') .strokeWidth(3)
}.margin({ top: 5 }) // 在 100 * 100 的矩形框中绘制一段折线,起点(20, 0),经过(0,100),到达终点(100, 90)
Polyline()
.width(100)
.height(100)
.fillOpacity(0)
.stroke(Color.Red)
.strokeWidth(8)
.points([[20, 0], [0, 100], [100, 90]])
// 设置折线拐角处为圆弧
.strokeLineJoin(LineJoinStyle.Round)
// 设置折线两端为半圆
.strokeLineCap(LineCapStyle.Round)
}.width('100%')
} }
} }
``` ```
![zh-cn_image_0000001219744185](figures/zh-cn_image_0000001219744185.gif) ![zh-cn_image_0000001219744185](figures/zh-cn_image_0000001219744185.png)
...@@ -58,19 +58,30 @@ Rect(value?: {width?: string | number,height?: string | number,radius?: string | ...@@ -58,19 +58,30 @@ Rect(value?: {width?: string | number,height?: string | number,radius?: string |
@Component @Component
struct RectExample { struct RectExample {
build() { build() {
Column({ space: 5 }) { Column({ space: 10 }) {
Text('normal').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('normal').fontSize(11).fontColor(0xCCCCCC).width('90%')
// 绘制90% * 50矩形 // 绘制90% * 50矩形
Rect({ width: '90%', height: 50 }) Rect({ width: '90%', height: 50 })
// 绘制90% * 50矩形 .fill(Color.Pink)
Rect().width('90%').height(50) // 绘制90% * 50的矩形框
Rect()
Text('with rounded corners').fontSize(9).fontColor(0xCCCCCC).width('90%') .width('90%')
// 绘制90% * 50矩形, 圆角宽高20 .height(50)
Rect({ width: '90%', height: 50 }).radiusHeight(20).radiusWidth(20) .fillOpacity(0)
// 绘制90% * 50矩形, 圆角宽高20 .stroke(Color.Red)
Rect({ width: '90%', height: 50 }).radius(20) .strokeWidth(3)
}.width('100%').margin({ top: 5 })
Text('with rounded corners').fontSize(11).fontColor(0xCCCCCC).width('90%')
// 绘制90% * 80的矩形, 圆角宽高分别为40、20
Rect({ width: '90%', height: 80 })
.radiusHeight(20)
.radiusWidth(40)
.fill(Color.Pink)
// 绘制90% * 80的矩形, 圆角宽高为20
Rect({ width: '90%', height: 80 })
.radius(20)
.fill(Color.Pink)
}.width('100%').margin({ top: 10 })
} }
} }
``` ```
......
...@@ -23,9 +23,9 @@ Shape(value?: PixelMap) ...@@ -23,9 +23,9 @@ Shape(value?: PixelMap)
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| value | PixelMap | 否 | - | 绘制目标,可将图形绘制在指定的PixelMap对象中,若未设置,则在当前绘制目标中进行绘制。 | | value | PixelMap | 否 | - | 绘制目标,可将图形绘制在指定的PixelMap对象中,若未设置,则在当前绘制目标中进行绘制。 |
## 属性 ## 属性
...@@ -50,67 +50,186 @@ Shape(value?: PixelMap) ...@@ -50,67 +50,186 @@ Shape(value?: PixelMap)
## 示例 ## 示例
### 示例1
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct ShapeExample { struct ShapeExample {
build() { build() {
Column({ space: 5 }) { Column({ space: 10 }) {
Text('basic').fontSize(30).fontColor(0xCCCCCC).width(320) Text('basic').fontSize(11).fontColor(0xCCCCCC).width(320)
// 在Shape的(-2, -2)点绘制一个 300 * 50 带边框的矩形,颜色0x317Af7,边框颜色黑色,边框宽度4,边框间隙20,向左偏移10,尖端样式圆角,拐角样式圆角,抗锯齿(默认开启) // 在Shape的(-2, -2)点绘制一个 300 * 50 带边框的矩形,颜色0x317AF7,边框颜色黑色,边框宽度4,边框间隙20,向左偏移10,线条两端样式为半圆,拐角样式圆角,抗锯齿(默认开启)
// 在Shape的(-2, 58)点绘制一个 300 * 50 带边框的椭圆,颜色0x317Af7,边框颜色黑色,边框宽度4,边框间隙20,向左偏移10,尖端样式圆角,拐角样式圆角,抗锯齿(默认开启) // 在Shape的(-2, 58)点绘制一个 300 * 50 带边框的椭圆,颜色0x317AF7,边框颜色黑色,边框宽度4,边框间隙20,向左偏移10,线条两端样式为半圆,拐角样式圆角,抗锯齿(默认开启)
// 在Shape的(-2, 118)点绘制一个 300 * 10 线段,颜色0x317Af7,边框颜色黑色,宽度4,间隙20,向左偏移10,尖端样式圆角,拐角样式圆角,抗锯齿(默认开启) // 在Shape的(-2, 118)点绘制一个 300 * 10 直线路径,颜色0x317AF7,边框颜色黑色,宽度4,间隙20,向左偏移10,线条两端样式为半圆,拐角样式圆角,抗锯齿(默认开启)
Shape() { Shape() {
Rect().width(300).height(50) Rect().width(300).height(50)
Ellipse().width(300).height(50).offset({ x: 0, y: 60 }) Ellipse().width(300).height(50).offset({ x: 0, y: 60 })
Path().width(300).height(10).commands('M0 0 L900 0').offset({ x: 0, y: 120 }) Path().width(300).height(10).commands('M0 0 L900 0').offset({ x: 0, y: 120 })
} }
.viewPort({ x: -2, y: -2, width: 304, height: 130 }) .viewPort({ x: -2, y: -2, width: 304, height: 130 })
.fill(0x317Af7).stroke(Color.Black).strokeWidth(4) .fill(0x317AF7)
.strokeDashArray([20]).strokeDashOffset(10).strokeLineCap(LineCapStyle.Round) .stroke(Color.Black)
.strokeLineJoin(LineJoinStyle.Round).antiAlias(true) .strokeWidth(4)
// 在Shape的(-1, -1)点绘制一个 300 * 50 带边框的矩形,颜色0x317Af7,边框颜色黑色,边框宽度2 .strokeDashArray([20])
.strokeDashOffset(10)
.strokeLineCap(LineCapStyle.Round)
.strokeLineJoin(LineJoinStyle.Round)
.antiAlias(true)
// 分别在Shape的(0, 0)、(-5, -5)点绘制一个 300 * 50 带边框的矩形,可以看出之所以将视口的起始位置坐标设为负值是因为绘制的起点默认为线宽的中点位置,因此要让边框完全显示则需要让视口偏移半个线宽
Shape() { Shape() {
Rect().width(300).height(50) Rect().width(300).height(50)
}.viewPort({ x: -1, y: -1, width: 302, height: 52 }).fill(0x317Af7).stroke(Color.Black).strokeWidth(2) }
.viewPort({ x: 0, y: 0, width: 320, height: 70 })
.fill(0x317AF7)
.stroke(Color.Black)
.strokeWidth(10)
Text('border').fontSize(30).fontColor(0xCCCCCC).width(320).margin({top:30})
// 在Shape的(0, -5)点绘制一个 300 * 10 直线,颜色0xEE8443,边框宽度10,边框间隙20
Shape() { Shape() {
Path().width(300).height(10).commands('M0 0 L900 0') Rect().width(300).height(50)
}.viewPort({ x: 0, y: -5, width: 300, height: 20 }).stroke(0xEE8443).strokeWidth(10).strokeDashArray([20]) }
// 在Shape的(0, -5)点绘制一个 300 * 10 直线,颜色0xEE8443,边框宽度10,边框间隙20,向左偏移10 .viewPort({ x: -5, y: -5, width: 320, height: 70 })
.fill(0x317AF7)
.stroke(Color.Black)
.strokeWidth(10)
Text('path').fontSize(11).fontColor(0xCCCCCC).width(320)
// 在Shape的(0, -5)点绘制一条直线路径,颜色0xEE8443,线条宽度10,线条间隙20
Shape() { Shape() {
Path().width(300).height(10).commands('M0 0 L900 0') Path().width(300).height(10).commands('M0 0 L900 0')
} }
.viewPort({ x: 0, y: -5, width: 300, height: 20 }) .viewPort({ x: 0, y: -5, width: 300, height: 20 })
.stroke(0xEE8443).strokeWidth(10).strokeDashArray([20]).strokeDashOffset(10) .stroke(0xEE8443)
// 在Shape的(0, -5)点绘制一个 300 * 10 直线,颜色0xEE8443,边框宽度10,透明度0.5 .strokeWidth(10)
.strokeDashArray([20])
// 在Shape的(0, -5)点绘制一条直线路径,颜色0xEE8443,线条宽度10,线条间隙20,向左偏移10
Shape() { Shape() {
Path().width(300).height(10).commands('M0 0 L900 0') Path().width(300).height(10).commands('M0 0 L900 0')
}.viewPort({ x: 0, y: -5, width: 300, height: 20 }).stroke(0xEE8443).strokeWidth(10).strokeOpacity(0.5) }
// 在Shape的(0, -5)点绘制一个 300 * 10 直线,颜色0xEE8443,边框宽度10,边框间隙20,向左偏移10,尖端样式圆角 .viewPort({ x: 0, y: -5, width: 300, height: 20 })
.stroke(0xEE8443)
.strokeWidth(10)
.strokeDashArray([20])
.strokeDashOffset(10)
// 在Shape的(0, -5)点绘制一条直线路径,颜色0xEE8443,线条宽度10,透明度0.5
Shape() { Shape() {
Path().width(300).height(10).commands('M0 0 L900 0') Path().width(300).height(10).commands('M0 0 L900 0')
} }
.viewPort({ x: 0, y: -5, width: 300, height: 20 }) .viewPort({ x: 0, y: -5, width: 300, height: 20 })
.stroke(0xEE8443).strokeWidth(10).strokeDashArray([20]).strokeLineCap(LineCapStyle.Round) .stroke(0xEE8443)
// 在Shape的(-5, -5)点绘制一个 300 * 50 带边框的矩形,颜色0x317Af7,边框宽度10,边框颜色0xEE8443,拐角样式圆角 .strokeWidth(10)
.strokeOpacity(0.5)
// 在Shape的(0, -5)点绘制一条直线路径,颜色0xEE8443,线条宽度10,线条间隙20,线条两端样式为半圆
Shape() { Shape() {
Rect().width(300).height(100) Path().width(300).height(10).commands('M0 0 L900 0')
} }
.viewPort({ x: -5, y: -5, width: 310, height: 120 }) .viewPort({ x: 0, y: -5, width: 300, height: 20 })
.fill(0x317Af7).stroke(0xEE8443).strokeWidth(10).strokeLineJoin(LineJoinStyle.Round) .stroke(0xEE8443)
.strokeWidth(10)
.strokeDashArray([20])
.strokeLineCap(LineCapStyle.Round)
// 在Shape的(-80, -5)点绘制一个封闭路径,颜色0x317AF7,线条宽度10,边框颜色0xEE8443,拐角样式锐角(默认值)
Shape() { Shape() {
Path().width(300).height(60).commands('M0 0 L400 0 L400 200 Z') Path().width(200).height(60).commands('M0 0 L400 0 L400 150 Z')
} }
.viewPort({ x: -80, y: -5, width: 310, height: 100 }) .viewPort({ x: -80, y: -5, width: 310, height: 90 })
.fill(0x317Af7).stroke(0xEE8443).strokeWidth(10) .fill(0x317AF7)
.strokeLineJoin(LineJoinStyle.Miter).strokeMiterLimit(5) .stroke(0xEE8443)
.strokeWidth(10)
.strokeLineJoin(LineJoinStyle.Miter)
.strokeMiterLimit(5)
}.width('100%').margin({ top: 15 }) }.width('100%').margin({ top: 15 })
} }
} }
``` ```
![zh-cn_image_0000001184628104](figures/zh-cn_image_0000001184628104.png) ![zh-cn_image_0000001184628104](figures/zh-cn_image_0000001184628104.png)
### 示例2
```ts
// xxx.ets
@Entry
@Component
struct ShapeMeshExample {
@State columnVal: number = 0;
@State rowVal: number = 0;
@State count: number = 0;
@State verts: Array<number> = [];
@State shapeWidth: number = 600;
@State shapeHeight: number = 600;
build() {
Column() {
Shape() {
Rect()
.width('250px')
.height('250px')
.radiusWidth('10px')
.radiusHeight('10px')
.stroke('10px')
.margin({ left: '10px', top: '10px' })
.strokeWidth('10px')
.fill(Color.Blue)
Rect()
.width('250px')
.height('250px')
.radiusWidth('10px')
.radiusHeight('10px')
.stroke('10px')
.margin({ left: '270px', top: '10px' })
.strokeWidth('10px')
.fill(Color.Red)
}
.mesh(this.verts, this.columnVal, this.rowVal)
.width(this.shapeWidth + 'px')
.height(this.shapeHeight + 'px')
// 手指触摸Shape组件时会显示mesh扭曲效果
.onTouch((event: TouchEvent) => {
var touchX = event.touches[0].x * 2;
var touchY = event.touches[0].y * 2;
this.columnVal = 20;
this.rowVal = 20;
this.count = (this.columnVal + 1) * (this.rowVal + 1);
var orig = [this.count * 2];
var index = 0;
for (var i = 0; i <= this.rowVal; i++) {
var fy = this.shapeWidth * i / this.rowVal;
for (var j = 0; j <= this.columnVal; j++) {
var fx = this.shapeWidth * j / this.columnVal;
orig[index * 2 + 0] = this.verts[index * 2 + 0] = fx;
orig[index * 2 + 1] = this.verts[index * 2 + 1] = fy;
index++;
}
}
for (var k = 0; k < this.count * 2; k += 2) {
var dx = touchX - orig[k + 0];
var dy = touchY - orig[k + 1];
var dd = dx * dx + dy * dy;
var d = Math.sqrt(dd);
var pull = 80000 / (dd * d);
if (pull >= 1) {
this.verts[k + 0] = touchX;
this.verts[k + 1] = touchY;
} else {
this.verts[k + 0] = orig[k + 0] + dx * pull;
this.verts[k + 1] = orig[k + 1] + dy * pull;
}
}
})
}
.width('600px')
.height('600px')
.border({ width: 3, color: Color.Black })
}
}
```
示意图:
![zh-cn_image1_0000001184628104](figures/zh-cn_image1_0000001184628104.png)
手指触摸Shape组件时会显示mesh扭曲效果:
![zh-cn_image2_0000001184628104](figures/zh-cn_image2_0000001184628104.png)
\ No newline at end of file
...@@ -5,11 +5,6 @@ ...@@ -5,11 +5,6 @@
> **说明:** > **说明:**
> 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## TimePickerDialog.show ## TimePickerDialog.show
show(options?: TimePickerDialogOptions) show(options?: TimePickerDialogOptions)
...@@ -58,7 +53,10 @@ struct TimePickerDialogExample01 { ...@@ -58,7 +53,10 @@ struct TimePickerDialogExample01 {
} }
} }
``` ```
![zh-cn_image_0000001118642010](figures/zh-cn_image_0000001118642010.gif)
### 时间滑动选择器(12小时制)示例 ### 时间滑动选择器(12小时制)示例
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -87,3 +85,5 @@ struct TimePickerDialogExample02 { ...@@ -87,3 +85,5 @@ struct TimePickerDialogExample02 {
} }
} }
``` ```
![zh-cn_image_0000001118642020](figures/zh-cn_image_0000001118642020.gif)
\ No newline at end of file
...@@ -14,25 +14,15 @@ ...@@ -14,25 +14,15 @@
## BorderImageOption对象说明 ## BorderImageOption对象说明
| 名称 | 类型 | 描述 | | 名称 | 类型 | 描述 |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------- | ---------------------------------------- | --------------------------------------- |
| source | string \| [Resource](ts-types.md#resource) \| [linearGradient](ts-universal-attributes-gradient-color.md) | 边框图源或者渐变色设置。 | | source | string \| [Resource](ts-types.md#resource) \| [linearGradient](ts-universal-attributes-gradient-color.md) | 边框图源或者渐变色设置。 |
| slice | [Length](ts-types.md#length)\| EdgeWidths | 设置图片边框切割宽度。<br/>**说明:**<br/>切分过程会将图像分割为9个区域:四个角、四个边以及中心区域。四个角的区域,用于组成最终图片边框图像的四个角;四个边区域,在最终的边框图像中重复、缩放或修改它们以匹配元素的大小;中心区域默认情况下会被丢弃,不进行填充。<br/>默认值:0 | | slice | [Length](ts-types.md#length)\| [EdgeWidths](ts-types.md#edgewidths9) | 设置图片边框切割宽度。<br/>默认值:0 |
| width | [Length](ts-types.md#length)\| EdgeWidths | 设置图片边框宽度。<br/>默认值:0 | | width | [Length](ts-types.md#length)\| [EdgeWidths](ts-types.md#edgewidths9) | 设置图片边框宽度。<br/>默认值:0 |
| outset | [Length](ts-types.md#length)\| EdgeWidths | 设置边框图片向外延伸距离。<br/>默认值:0 | | outset | [Length](ts-types.md#length)\| [EdgeWidths](ts-types.md#edgewidths9) | 设置边框图片向外延伸距离。<br/>默认值:0 |
| RepeatMode | RepeatMode | 设置边框图片的重复方式。<br/>默认值:RepeatMode.Stretch | | RepeatMode | RepeatMode | 设置边框图片的重复方式。<br/>默认值:RepeatMode.Stretch |
| fill | boolean | 设置边框图片中心填充。<br/>默认值:false | | fill | boolean | 设置边框图片中心填充。<br/>默认值:false |
## EdgeWidths对象说明
引用该对象时,至少传入一个参数。
| 名称 | 参数类型 | 必填 |描述 |
| -------- | -------- |-------- |-------- |
| left | [Length](ts-types.md#length) | 否 | 左侧距离参数。 |
| right | [Length](ts-types.md#length) | 否 | 右侧距离参数。 |
| top | [Length](ts-types.md#length) | 否 | 上侧距离参数。 |
| bottom | [Length](ts-types.md#length) | 否 | 下侧距离参数。 |
## RepeatMode枚举说明 ## RepeatMode枚举说明
......
...@@ -11,7 +11,7 @@ id为组件的唯一标识,在整个应用内唯一。本模块提供组件标 ...@@ -11,7 +11,7 @@ id为组件的唯一标识,在整个应用内唯一。本模块提供组件标
| 名称 | 参数说明 | 描述 | | 名称 | 参数说明 | 描述 |
| -----| -------- | ----------------------------- | | -----| -------- | ----------------------------- |
| id | string | 组件的唯一标识,唯一性由使用者保证。<br>默认值:''| | id | string | 组件的唯一标识,唯一性由使用者保证。<br>默认值:'' |
## 接口 ## 接口
......
...@@ -23,7 +23,6 @@ ...@@ -23,7 +23,6 @@
@Entry @Entry
@Component @Component
struct FlexExample { struct FlexExample {
build() { build() {
Column({ space: 5 }) { Column({ space: 5 }) {
Text('flexBasis').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('flexBasis').fontSize(9).fontColor(0xCCCCCC).width('90%')
...@@ -31,11 +30,18 @@ struct FlexExample { ...@@ -31,11 +30,18 @@ struct FlexExample {
// flexBasis()值可以是'auto',表示基准尺寸是元素本来的大小 ,也可以是长度设置,相当于.width()/.height() // flexBasis()值可以是'auto',表示基准尺寸是元素本来的大小 ,也可以是长度设置,相当于.width()/.height()
Flex() { Flex() {
Text('flexBasis(100)') Text('flexBasis(100)')
.flexBasis('100').height(100).lineHeight(70) .flexBasis('100')
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) .height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
Text('flexBasis("auto")') Text('flexBasis("auto")')
.flexBasis('auto').width('60%').height(100).lineHeight(70) .flexBasis('auto')
.backgroundColor(0xD2B48C).textAlign(TextAlign.Center) .width('60%')
.height(100)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
Text('flexGrow').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('flexGrow').fontSize(9).fontColor(0xCCCCCC).width('90%')
...@@ -43,11 +49,17 @@ struct FlexExample { ...@@ -43,11 +49,17 @@ struct FlexExample {
// flexGrow()剩余空间分配给该元素的比例 // flexGrow()剩余空间分配给该元素的比例
Flex() { Flex() {
Text('flexGrow(2)') Text('flexGrow(2)')
.flexGrow(2).height(100).lineHeight(70) .flexGrow(2)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) .height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
Text('flexGrow(1)') Text('flexGrow(1)')
.flexGrow(1).height(100).lineHeight(70) .flexGrow(1)
.backgroundColor(0xD2B48C).textAlign(TextAlign.Center) .height(100)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
Text('flexShrink').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('flexShrink').fontSize(9).fontColor(0xCCCCCC).width('90%')
...@@ -55,13 +67,25 @@ struct FlexExample { ...@@ -55,13 +67,25 @@ struct FlexExample {
// text1比例是0,其他都是默认值1,放不下时直接等比例缩放后两个,第一个不缩放 // text1比例是0,其他都是默认值1,放不下时直接等比例缩放后两个,第一个不缩放
Flex({ direction: FlexDirection.Row }) { Flex({ direction: FlexDirection.Row }) {
Text('flexShrink(0)') Text('flexShrink(0)')
.flexShrink(0).width('50%').height(100).lineHeight(70) .flexShrink(0)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) .width('50%')
.height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
Text('no flexShrink') Text('no flexShrink')
.width('40%').height(100).lineHeight(70).backgroundColor(0xD2B48C).textAlign(TextAlign.Center) .width('40%')
.height(100)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
Text('flexShrink(2)') Text('flexShrink(2)')
.flexShrink(2).width('40%').height(100) .lineHeight(70) .flexShrink(2)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) .width('40%')
.height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
Text('alignSelf').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('alignSelf').fontSize(9).fontColor(0xCCCCCC).width('90%')
...@@ -70,8 +94,12 @@ struct FlexExample { ...@@ -70,8 +94,12 @@ struct FlexExample {
Text('no alignSelf,height:80').width('33%').height(80) Text('no alignSelf,height:80').width('33%').height(80)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) .backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
Text('alignSelf stretch') Text('alignSelf stretch')
.alignSelf(ItemAlign.Stretch).width('33%').height(80).lineHeight(70) .alignSelf(ItemAlign.Stretch)
.backgroundColor(0xD2B48C).textAlign(TextAlign.Center) .width('33%')
.height(80)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
Text('no alignSelf,height:100').width('34%').height(100) Text('no alignSelf,height:100').width('34%').height(100)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) .backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
......
...@@ -10,9 +10,9 @@ ...@@ -10,9 +10,9 @@
## 属性 ## 属性
| 名称 | 参数类型 | 描述 | | 名称 | 参数类型 | 描述 |
| ------- | ---------------------------------------- | ---------------------------------------- | | ------- | ---------------------------------------------------- | ------------------------------------------------------------ |
| opacity | number&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 元素的不透明度,取值范围为0到1,1表示为不透明,0表示为完全透明。<br>默认值:1 | | opacity | number&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 元素的不透明度,取值范围为0到1,1表示为不透明,0表示为完全透明。<br>**说明:**<br/>子组件可以继承父组件的此属性。默认值:1 |
## 示例 ## 示例
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
| height | [Length](ts-types.md#length) | 设置组件自身的高度,缺省时使用元素自身内容需要的高度。若子组件的高大于父组件的高,则会画出父组件的范围。 | | height | [Length](ts-types.md#length) | 设置组件自身的高度,缺省时使用元素自身内容需要的高度。若子组件的高大于父组件的高,则会画出父组件的范围。 |
| size | {<br/>width?:&nbsp;[Length](ts-types.md#length),<br/>height?:&nbsp;[Length](ts-types.md#length)<br/>} | 设置高宽尺寸。 | | size | {<br/>width?:&nbsp;[Length](ts-types.md#length),<br/>height?:&nbsp;[Length](ts-types.md#length)<br/>} | 设置高宽尺寸。 |
| padding | [Padding](ts-types.md#padding)&nbsp;\|&nbsp;[Length](ts-types.md#length) | 设置内边距属性。<br/>参数为Length类型时,四个方向内边距同时生效。<br>默认值:0 <br>padding设置百分比时,上下左右内边距均以父容器的width作为基础值。 | | padding | [Padding](ts-types.md#padding)&nbsp;\|&nbsp;[Length](ts-types.md#length) | 设置内边距属性。<br/>参数为Length类型时,四个方向内边距同时生效。<br>默认值:0 <br>padding设置百分比时,上下左右内边距均以父容器的width作为基础值。 |
| margin | [Margin](ts-types.md#margin))&nbsp;\|&nbsp;[Length](ts-types.md#length) | 设置外边距属性。<br/>参数为Length类型时,四个方向外边距同时生效。<br>默认值:0 <br>margin设置百分比时,上下左右外边距均以父容器的width作为基础值。| | margin | [Margin](ts-types.md#margin)&nbsp;\|&nbsp;[Length](ts-types.md#length) | 设置外边距属性。<br/>参数为Length类型时,四个方向外边距同时生效。<br>默认值:0 <br>margin设置百分比时,上下左右外边距均以父容器的width作为基础值。|
| constraintSize | {<br/>minWidth?:&nbsp;[Length](ts-types.md#length),<br/>maxWidth?:&nbsp;[Length](ts-types.md#length),<br/>minHeight?:&nbsp;[Length](ts-types.md#length),<br/>maxHeight?:&nbsp;[Length](ts-types.md#length)<br/>} | 设置约束尺寸,组件布局时,进行尺寸范围限制。constraintSize的优先级高于Width和Height。<br>默认值:<br>{<br/>minWidth:&nbsp;0,<br/>maxWidth:&nbsp;Infinity,<br/>minHeight:&nbsp;0,<br/>maxHeight:&nbsp;Infinity<br/>} | | constraintSize | {<br/>minWidth?:&nbsp;[Length](ts-types.md#length),<br/>maxWidth?:&nbsp;[Length](ts-types.md#length),<br/>minHeight?:&nbsp;[Length](ts-types.md#length),<br/>maxHeight?:&nbsp;[Length](ts-types.md#length)<br/>} | 设置约束尺寸,组件布局时,进行尺寸范围限制。constraintSize的优先级高于Width和Height。<br>默认值:<br>{<br/>minWidth:&nbsp;0,<br/>maxWidth:&nbsp;Infinity,<br/>minHeight:&nbsp;0,<br/>maxHeight:&nbsp;Infinity<br/>} |
| layoutWeight | number&nbsp;\|&nbsp;string | 容器尺寸确定时,元素与兄弟节点主轴布局尺寸按照权重进行分配,忽略本身尺寸设置,表示自适应占满剩余空间。<br>**说明:**<br/>仅在Row/Column/Flex布局中生效。<br>默认值:0 | | layoutWeight | number&nbsp;\|&nbsp;string | 容器尺寸确定时,元素与兄弟节点主轴布局尺寸按照权重进行分配,忽略本身尺寸设置,表示自适应占满剩余空间。<br>**说明:**<br/>仅在Row/Column/Flex布局中生效。<br>默认值:0 |
......
...@@ -23,8 +23,8 @@ ...@@ -23,8 +23,8 @@
struct ScrollExample { struct ScrollExample {
scroller: Scroller = new Scroller() scroller: Scroller = new Scroller()
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
@State testTextStr: string = "test" @State testTextStr: string = 'test'
@State testRowStr: string = "test" @State testRowStr: string = 'test'
build() { build() {
Column() { Column() {
...@@ -46,22 +46,22 @@ struct ScrollExample { ...@@ -46,22 +46,22 @@ struct ScrollExample {
.height(200) .height(200)
.margin({ top: 50, bottom: 20 }) .margin({ top: 50, bottom: 20 })
.backgroundColor(Color.Green) .backgroundColor(Color.Green)
// 通过设置ratios为[0.0, 1.0],实现当组件完全显示或完全消失在屏幕中时触发回调 // 通过设置ratios为[0.0, 1.0],实现当组件完全显示或完全消失在屏幕中时触发回调
.onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => { .onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => {
console.info("Test Text isVisible: " + isVisible + ", currentRatio:" + currentRatio) console.info('Test Text isVisible: ' + isVisible + ', currentRatio:' + currentRatio)
if (isVisible && currentRatio >= 1.0) { if (isVisible && currentRatio >= 1.0) {
console.info("Test Text is fully visible. currentRatio:" + currentRatio) console.info('Test Text is fully visible. currentRatio:' + currentRatio)
this.testTextStr = "Test Text is fully visible" this.testTextStr = 'Test Text is fully visible'
} }
if (!isVisible && currentRatio <= 0.0) { if (!isVisible && currentRatio <= 0.0) {
console.info("Test Text is completely invisible.") console.info('Test Text is completely invisible.')
this.testTextStr = "Test Text is completely invisible" this.testTextStr = 'Test Text is completely invisible'
} }
}) })
Row() { Row() {
Text("Test Row Visible Change") Text('Test Row Visible Change')
.fontSize(20) .fontSize(20)
.margin({ bottom: 20 }) .margin({ bottom: 20 })
...@@ -69,15 +69,15 @@ struct ScrollExample { ...@@ -69,15 +69,15 @@ struct ScrollExample {
.height(200) .height(200)
.backgroundColor(Color.Yellow) .backgroundColor(Color.Yellow)
.onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => { .onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => {
console.info("Test Row isVisible:" + isVisible + ", currentRatio:" + currentRatio) console.info('Test Row isVisible:' + isVisible + ', currentRatio:' + currentRatio)
if (isVisible && currentRatio >= 1.0) { if (isVisible && currentRatio >= 1.0) {
console.info("Test Row is fully visible.") console.info('Test Row is fully visible.')
this.testRowStr = "Test Row is fully visible" this.testRowStr = 'Test Row is fully visible'
} }
if (!isVisible && currentRatio <= 0.0) { if (!isVisible && currentRatio <= 0.0) {
console.info("Test Row is is completely invisible.") console.info('Test Row is is completely invisible.')
this.testRowStr = "Test Row is is completely invisible" this.testRowStr = 'Test Row is is completely invisible'
} }
}) })
......
...@@ -80,7 +80,7 @@ background: repeating-linear-gradient(direction/angle, color, color, ...); ...@@ -80,7 +80,7 @@ background: repeating-linear-gradient(direction/angle, color, color, ...);
```css ```css
/* 从左向右重复渐变,重复渐变区域30px(60-30)透明度0.5 */ /* 从左向右重复渐变,重复渐变区域30px(60-30)透明度0.5 */
background: repeating-linear-gradient(to right, rgba(255, 255, 0, 1) 30px,rgba(0, 0, 255, .5) 60px); background: repeating-linear-gradient(to right, rgba(255, 255, 0, 1) 30vp,rgba(0, 0, 255, .5) 60vp);
``` ```
![444](figures/444.PNG) ![444](figures/444.PNG)
...@@ -35,6 +35,7 @@ ...@@ -35,6 +35,7 @@
```json ```json
// comp.json
{ {
"data": { "data": {
"progress": { "progress": {
......
# Native API # Native API
- 模块 - 模块
- [Native XComponent](_o_h___native_x_component.md) - [Native XComponent](_o_h___native_x_component.md)
- [HiLog](_hi_log.md) - [HiLog](_hi_log.md)
- [NativeWindow](_native_window.md) - [NativeWindow](_native_window.md)
- [OH_NativeBuffer](_o_h___native_buffer.md) - [OH_NativeBuffer](_o_h___native_buffer.md)
- [Drawing](_drawing.md) - [Drawing](_drawing.md)
- [OH_NativeImage](_o_h___native_image.md) - [OH_NativeImage](_o_h___native_image.md)
- [NativeVsync](_native_vsync.md) - [NativeVsync](_native_vsync.md)
- [Image](image.md) - [Image](image.md)
- [Rawfile](rawfile.md) - [Rawfile](rawfile.md)
- [MindSpore](_mind_spore.md)
- 头文件 - 头文件
- [drawing_bitmap.h](drawing__bitmap_8h.md) - [drawing_bitmap.h](drawing__bitmap_8h.md)
- [drawing_brush.h](drawing__brush_8h.md) - [drawing_brush.h](drawing__brush_8h.md)
- [drawing_canvas.h](drawing__canvas_8h.md) - [drawing_canvas.h](drawing__canvas_8h.md)
- [drawing_color.h](drawing__color_8h.md) - [drawing_color.h](drawing__color_8h.md)
- [drawing_font_collection.h](drawing__font__collection_8h.md) - [drawing_font_collection.h](drawing__font__collection_8h.md)
- [drawing_path.h](drawing__path_8h.md) - [drawing_path.h](drawing__path_8h.md)
- [drawing_pen.h](drawing__pen_8h.md) - [drawing_pen.h](drawing__pen_8h.md)
- [drawing_text_declaration.h](drawing__text__declaration_8h.md) - [drawing_text_declaration.h](drawing__text__declaration_8h.md)
- [drawing_text_typography.h](drawing__text__typography_8h.md) - [drawing_text_typography.h](drawing__text__typography_8h.md)
- [drawing_types.h](drawing__types_8h.md) - [drawing_types.h](drawing__types_8h.md)
- [external_window.h](external__window_8h.md) - [external_window.h](external__window_8h.md)
- [image_pixel_map_napi.h](image__pixel__map__napi_8h.md) - [image_pixel_map_napi.h](image__pixel__map__napi_8h.md)
- [log.h](log_8h.md) - [log.h](log_8h.md)
- [native_buffer.h](native__buffer_8h.md) - [native_buffer.h](native__buffer_8h.md)
- [native_image.h](native__image_8h.md) - [native_image.h](native__image_8h.md)
- [native_interface_xcomponent.h](native__interface__xcomponent_8h.md) - [native_interface_xcomponent.h](native__interface__xcomponent_8h.md)
- [native_vsync.h](native__vsync_8h.md) - [native_vsync.h](native__vsync_8h.md)
- [raw_dir.h](raw__dir_8h.md) - [raw_dir.h](raw__dir_8h.md)
- [raw_file_manager.h](raw__file__manager_8h.md) - [raw_file_manager.h](raw__file__manager_8h.md)
- [raw_file.h](raw__file_8h.md) - [raw_file.h](raw__file_8h.md)
- [context.h](context_8h.md)
- [data_type.h](data__type_8h.md)
- [format.h](format_8h.md)
- [model.h](model_8h.md)
- [status.h](status_8h.md)
- [tensor.h](tensor_8h.md)
- [types.h](types_8h.md)
- 结构体 - 结构体
- [OH_Drawing_BitmapFormat](_o_h___drawing___bitmap_format.md) - [OH_Drawing_BitmapFormat](_o_h___drawing___bitmap_format.md)
- [OH_NativeBuffer_Config](_o_h___native_buffer___config.md) - [OH_NativeBuffer_Config](_o_h___native_buffer___config.md)
- [OH_NativeXComponent_Callback](_o_h___native_x_component___callback.md) - [OH_NativeXComponent_Callback](_o_h___native_x_component___callback.md)
- [OH_NativeXComponent_MouseEvent](_o_h___native_x_component___mouse_event.md) - [OH_NativeXComponent_MouseEvent](_o_h___native_x_component___mouse_event.md)
- [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component___mouse_event___callback.md) - [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component___mouse_event___callback.md)
- [OH_NativeXComponent_TouchEvent](_o_h___native_x_component___touch_event.md) - [OH_NativeXComponent_TouchEvent](_o_h___native_x_component___touch_event.md)
- [OH_NativeXComponent_TouchPoint](_o_h___native_x_component___touch_point.md) - [OH_NativeXComponent_TouchPoint](_o_h___native_x_component___touch_point.md)
- [OHExtDataHandle](_o_h_ext_data_handle.md) - [OHExtDataHandle](_o_h_ext_data_handle.md)
- [OHHDRMetaData](_o_h_h_d_r_meta_data.md) - [OHHDRMetaData](_o_h_h_d_r_meta_data.md)
- [OhosPixelMapInfo](_ohos_pixel_map_info.md) - [OhosPixelMapInfo](_ohos_pixel_map_info.md)
- [RawFileDescriptor](_raw_file_descriptor.md) - [RawFileDescriptor](_raw_file_descriptor.md)
- [Region](_region.md) - [Region](_region.md)
- [Rect](_rect.md) - [Rect](_rect.md)
- [OH_AI_CallBackParam](_o_h___a_i___call_back_param.md)
- [OH_AI_ShapeInfo](_o_h___a_i___shape_info.md)
- [OH_AI_TensorHandleArray](_o_h___a_i___tensor_handle_array.md)
# MindSpore
提供MindSpore Lite的模型推理相关接口。
@Syscap SystemCapability.Ai.MindSpore
**自从:**
9
## 汇总
### 文件
| 文件名称 | 描述 |
| -------- | -------- |
| [context.h](context_8h.md) | 提供了Context相关的接口,可以配置运行时信息。 |
| [data_type.h](data__type_8h.md) | 声明了张量的数据的类型。 |
| [format.h](format_8h.md) | 提供张量数据的排列格式。 |
| [model.h](model_8h.md) | 提供了模型相关接口,可以用于模型创建、模型推理等。 |
| [status.h](status_8h.md) | 提供了Mindspore Lite运行时的状态码。 |
| [tensor.h](tensor_8h.md) | 提供了张量相关的接口,可用于创建和修改张量信息。 |
| [types.h](types_8h.md) | 提供了MindSpore Lite支持的模型文件类型和设备类型。 |
### 结构体
| 结构体名称 | 描述 |
| -------- | -------- |
| [OH_AI_TensorHandleArray](_o_h___a_i___tensor_handle_array.md) | 张量数组结构体,用于存储张量数组指针和张量数组长度。 |
| [OH_AI_ShapeInfo](_o_h___a_i___shape_info.md) | 维度信息,最大的维度为**MS_MAX_SHAPE_NUM**。 |
| [OH_AI_CallBackParam](_o_h___a_i___call_back_param.md) | 回调函数中传入的算子信息。 |
### 宏定义
| 宏定义名称 | 描述 |
| -------- | -------- |
| [OH_AI_MAX_SHAPE_NUM](#oh_ai_max_shape_num) 32 | 维度信息,最大的维度为**MS_MAX_SHAPE_NUM**。 |
### 类型定义
| 类型定义名称 | 描述 |
| -------- | -------- |
| [OH_AI_ContextHandle](#oh_ai_contexthandle) | Mindspore的上下文信息的指针,该指针会指向Context。 |
| [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) | Mindspore的运行设备信息的指针。 |
| [OH_AI_DataType](#oh_ai_datatype) | MSTensor保存的数据支持的类型。 |
| [OH_AI_Format](#oh_ai_format) | MSTensor保存的数据支持的排列格式。 |
| [OH_AI_ModelHandle](#oh_ai_modelhandle) | 指向模型对象的指针。 |
| [OH_AI_TensorHandleArray](#oh_ai_tensorhandlearray) | 张量数组结构体,用于存储张量数组指针和张量数组长度。 |
| [OH_AI_ShapeInfo](_o_h___a_i___shape_info.md) | 维度信息,最大的维度为**MS_MAX_SHAPE_NUM**。 |
| [OH_AI_CallBackParam](#oh_ai_callbackparam) | 回调函数中传入的算子信息。 |
| [OH_AI_KernelCallBack](#oh_ai_kernelcallback)) (const OH_AI_TensorHandleArray inputs, const OH_AI_TensorHandleArray outputs, const OH_AI_CallBackParam kernel_Info) | 回调函数指针。 |
| [OH_AI_Status](#oh_ai_status) | Minspore的状态码。 |
| [OH_AI_TensorHandle](#oh_ai_tensorhandle) | 指向张量对象句柄。 |
| [OH_AI_ModelType](#oh_ai_modeltype) | 模型文件的类型。 |
| [OH_AI_DeviceType](#oh_ai_devicetype) | 设备类型,该信息。 |
### 枚举
| 枚举名称 | 描述 |
| -------- | -------- |
| [OH_AI_DataType](#oh_ai_datatype) {<br/>OH_AI_DATATYPE_UNKNOWN = 0,<br/>OH_AI_DATATYPE_OBJECTTYPE_STRING = 12,<br/>OH_AI_DATATYPE_OBJECTTYPE_LIST = 13, <br/>OH_AI_DATATYPE_OBJECTTYPE_TUPLE = 14, <br/>OH_AI_DATATYPE_OBJECTTYPE_TENSOR = 17, <br/>OH_AI_DATATYPE_NUMBERTYPE_BEGIN = 29,<br/>OH_AI_DATATYPE_NUMBERTYPE_BOOL = 30,<br/>OH_AI_DATATYPE_NUMBERTYPE_INT8 = 32, <br/>OH_AI_DATATYPE_NUMBERTYPE_INT16 = 33, <br/>OH_AI_DATATYPE_NUMBERTYPE_INT32 = 34, <br/>OH_AI_DATATYPE_NUMBERTYPE_INT64 = 35, <br/>OH_AI_DATATYPE_NUMBERTYPE_UINT8 = 37, <br/>OH_AI_DATATYPE_NUMBERTYPE_UINT16 = 38,<br/>OH_AI_DATATYPE_NUMBERTYPE_UINT32 = 39, <br/>OH_AI_DATATYPE_NUMBERTYPE_UINT64 = 40, <br/>OH_AI_DATATYPE_NUMBERTYPE_FLOAT16 = 42, <br/>OH_AI_DATATYPE_NUMBERTYPE_FLOAT32 = 43, <br/>OH_AI_DATATYPE_NUMBERTYPE_FLOAT64 = 44,<br/>OH_AI_DATATYPE_NUMBERTYPE_END = 46,<br/>OH_AI_DataTypeInvalid = INT32_MAX } | MSTensor保存的数据支持的类型。 |
| [OH_AI_Format](#oh_ai_format) {<br/>OH_AI_FORMAT_NCHW = 0,<br/>OH_AI_FORMAT_NHWC = 1,<br/>OH_AI_FORMAT_NHWC4 = 2,<br/>OH_AI_FORMAT_HWKC = 3,<br/>OH_AI_FORMAT_HWCK = 4,<br/>OH_AI_FORMAT_KCHW = 5,<br/>OH_AI_FORMAT_CKHW = 6,<br/>OH_AI_FORMAT_KHWC = 7,<br/>OH_AI_FORMAT_CHWK = 8,<br/>OH_AI_FORMAT_HW = 9,<br/>OH_AI_FORMAT_HW4 = 10,<br/>OH_AI_FORMAT_NC = 11,<br/>OH_AI_FORMAT_NC4 = 12,<br/>OH_AI_FORMAT_NC4HW4 = 13,<br/>OH_AI_FORMAT_NCDHW = 15,<br/>OH_AI_FORMAT_NWC = 16,<br/>OH_AI_FORMAT_NCW = 17 } | MSTensor保存的数据支持的排列格式。 |
| [OH_AI_CompCode](#oh_ai_compcode) {<br/>OH_AI_COMPCODE_CORE = 0x00000000u,<br/>OH_AI_COMPCODE_LITE = 0xF0000000u } | Minspore不同组件的代码、 |
| [OH_AI_Status](#oh_ai_status) {<br/>OH_AI_STATUS_SUCCESS = 0,<br/>OH_AI_STATUS_CORE_FAILED = OH_AI_COMPCODE_CORE \| 0x1, <br/>OH_AI_STATUS_LITE_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -1), <br/>OH_AI_STATUS_LITE_NULLPTR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -2),<br/>OH_AI_STATUS_LITE_PARAM_INVALID = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -3),<br/>OH_AI_STATUS_LITE_NO_CHANGE = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -4),<br/>OH_AI_STATUS_LITE_SUCCESS_EXIT = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -5),<br/>OH_AI_STATUS_LITE_MEMORY_FAILED = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -6),<br/>OH_AI_STATUS_LITE_NOT_SUPPORT = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -7),<br/>OH_AI_STATUS_LITE_THREADPOOL_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -8),<br/>OH_AI_STATUS_LITE_UNINITIALIZED_OBJ = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -9),<br/>OH_AI_STATUS_LITE_OUT_OF_TENSOR_RANGE, <br/>OH_AI_STATUS_LITE_INPUT_TENSOR_ERROR,<br/>OH_AI_STATUS_LITE_REENTRANT_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -102),<br/>OH_AI_STATUS_LITE_GRAPH_FILE_ERROR,<br/>OH_AI_STATUS_LITE_NOT_FIND_OP = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -300), OH_AI_STATUS_LITE_INVALID_OP_NAME = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -301),<br/>OH_AI_STATUS_LITE_INVALID_OP_ATTR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -302),<br/>OH_AI_STATUS_LITE_OP_EXECUTE_FAILURE,<br/>OH_AI_STATUS_LITE_FORMAT_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -400),<br/>OH_AI_STATUS_LITE_INFER_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -500),<br/>OH_AI_STATUS_LITE_INFER_INVALID = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -501),<br/>OH_AI_STATUS_LITE_INPUT_PARAM_INVALID } | Minspore的状态码。 |
| [OH_AI_ModelType](#oh_ai_modeltype) {<br/>OH_AI_MODELTYPE_MINDIR = 0,<br/>OH_AI_MODELTYPE_INVALID = 0xFFFFFFFF } | 模型文件的类型。 |
| [OH_AI_DeviceType](#oh_ai_devicetype) {<br/>OH_AI_DEVICETYPE_CPU = 0,<br/>OH_AI_DEVICETYPE_KIRIN_NPU,<br/>OH_AI_DEVICETYPE_INVALID = 100 } | 设备类型,该信息。 |
### 函数
| 函数名称 | 描述 |
| -------- | -------- |
| [OH_AI_ContextCreate](#oh_ai_contextcreate) () | 创建一个上下文的对象。 |
| [OH_AI_ContextDestroy](#oh_ai_contextdestroy) (OH_AI_ContextHandle \*context) | 释放上下文对象。 |
| [OH_AI_ContextSetThreadNum](#oh_ai_contextsetthreadnum) (OH_AI_ContextHandle context, int32_t thread_num) | 设置运行时的线程数量。 |
| [OH_AI_ContextGetThreadNum](#oh_ai_contextgetthreadnum) (const OH_AI_ContextHandle context) | 获取线程数量。 |
| [OH_AI_ContextSetThreadAffinityMode](#oh_ai_contextsetthreadaffinitymode) (OH_AI_ContextHandle context, int mode) | 设置运行时线程绑定CPU核心的策略,按照CPU物理核频率分为大核与小核。 |
| [OH_AI_ContextGetThreadAffinityMode](#oh_ai_contextgetthreadaffinitymode) (const OH_AI_ContextHandle context) | 获取运行时线程绑定CPU核心的策略。 |
| [OH_AI_ContextSetThreadAffinityCoreList](#oh_ai_contextsetthreadaffinitycorelist) (OH_AI_ContextHandle context, const int32_t \*core_list, <br/>size_t core_num) | 设置运行时线程绑定CPU核心的列表。 |
| [OH_AI_ContextGetThreadAffinityCoreList](#oh_ai_contextgetthreadaffinitycorelist) (const OH_AI_ContextHandle context, size_t \*core_num) | 获取CPU绑核列表。 |
| [OH_AI_ContextSetEnableParallel](#oh_ai_contextsetenableparallel) (OH_AI_ContextHandle context, bool is_parallel) | 设置运行时是否支持并行。 |
| [OH_AI_ContextGetEnableParallel](#oh_ai_contextgetenableparallel) (const OH_AI_ContextHandle context) | 获取是否支持算子间并行。 |
| [OH_AI_ContextAddDeviceInfo](#oh_ai_contextadddeviceinfo) (OH_AI_ContextHandle context, OH_AI_DeviceInfoHandle device_info) | 添加运行设备信息。 |
| [OH_AI_DeviceInfoCreate](#oh_ai_deviceinfocreate) (OH_AI_DeviceType device_type) | 创建一个设备信息对象。 |
| [OH_AI_DeviceInfoDestroy](#oh_ai_deviceinfodestroy) (OH_AI_DeviceInfoHandle \*device_info) | 释放设备信息实例。 |
| [OH_AI_DeviceInfoSetProvider](#oh_ai_deviceinfosetprovider) (OH_AI_DeviceInfoHandle device_info, const char \*provider) | 设置供应商的名称。 |
| [OH_AI_DeviceInfoGetProvider](#oh_ai_deviceinfogetprovider) (const OH_AI_DeviceInfoHandle device_info) | 获取生产商的名称。 |
| [OH_AI_DeviceInfoSetProviderDevice](#oh_ai_deviceinfosetproviderdevice) (OH_AI_DeviceInfoHandle device_info, const char \*device) | 设置生产商设备的名称。 |
| [OH_AI_DeviceInfoGetProviderDevice](#oh_ai_deviceinfogetproviderdevice) (const OH_AI_DeviceInfoHandle device_info) | 获取生产商设备的名称。 |
| [OH_AI_DeviceInfoGetDeviceType](#oh_ai_deviceinfogetdevicetype) (const OH_AI_DeviceInfoHandle device_info) | 获取设备的类型。 |
| [OH_AI_DeviceInfoSetEnableFP16](#oh_ai_deviceinfosetenablefp16) (OH_AI_DeviceInfoHandle device_info, bool is_fp16) | 设置是否开启float16推理模式,仅CPU/GPU设备可用。 |
| [OH_AI_DeviceInfoGetEnableFP16](#oh_ai_deviceinfogetenablefp16) (const OH_AI_DeviceInfoHandle device_info) | 获取是否开启float16推理模式, 仅CPU/GPU设备可用。 |
| [OH_AI_DeviceInfoSetFrequency](#oh_ai_deviceinfosetfrequency) (OH_AI_DeviceInfoHandle device_info, int frequency) | 设置NPU的频率,仅NPU设备可用。 |
| [OH_AI_DeviceInfoGetFrequency](#oh_ai_deviceinfogetfrequency) (const OH_AI_DeviceInfoHandle device_info) | 获取NPU的频率类型,仅NPU设备可用。 |
| [OH_AI_ModelCreate](#oh_ai_modelcreate) () | 创建一个模型对象。 |
| [OH_AI_ModelDestroy](#oh_ai_modeldestroy) (OH_AI_ModelHandle \*model) | 释放一个模型对象。 |
| [OH_AI_ModelBuild](#oh_ai_modelbuild) (OH_AI_ModelHandle model, const void \*model_data, size_t data_size, OH_AI_ModelType model_type, const OH_AI_ContextHandle model_context) | 从内存缓冲区加载并编译MindSpore模型。 |
| [OH_AI_ModelBuildFromFile](#oh_ai_modelbuildfromfile) (OH_AI_ModelHandle model, const char \*model_path, <br/>OH_AI_ModelType model_type, const OH_AI_ContextHandle model_context) | 通过模型文件加载并编译MindSpore模型。 |
| [OH_AI_ModelResize](#oh_ai_modelresize) (OH_AI_ModelHandle model, const OH_AI_TensorHandleArray inputs, OH_AI_ShapeInfo \*shape_infos, size_t shape_info_num) | 调整已编译模型的输入形状。 |
| [OH_AI_ModelPredict](#oh_ai_modelpredict) (OH_AI_ModelHandle model, const OH_AI_TensorHandleArray inputs, OH_AI_TensorHandleArray \*outputs, const OH_AI_KernelCallBack before, <br/>const OH_AI_KernelCallBack after) | 执行模型推理。 |
| [OH_AI_ModelGetInputs](#oh_ai_modelgetinputs) (const OH_AI_ModelHandle model) | 获取模型的输入张量数组结构体。 |
| [OH_AI_ModelGetOutputs](#oh_ai_modelgetoutputs) (const OH_AI_ModelHandle model) | 获取模型的输出张量数组结构体。 |
| [OH_AI_ModelGetInputByTensorName](#oh_ai_modelgetinputbytensorname) (const OH_AI_ModelHandle model, const char \*tensor_name) | 通过张量名获取模型的输入张量。 |
| [OH_AI_ModelGetOutputByTensorName](#oh_ai_modelgetoutputbytensorname) (const OH_AI_ModelHandle model, const char \*tensor_name) | 通过张量名获取模型的输出张量。 |
| [OH_AI_TensorCreate](#oh_ai_tensorcreate) (const char \*name, OH_AI_DataType type, const int64_t \*shape, <br/>size_t shape_num, const void \*data, size_t data_len) | 创建一个张量对象。 |
| [OH_AI_TensorDestroy](#oh_ai_tensordestroy) (OH_AI_TensorHandle \*tensor) | 释放张量对象。 |
| [OH_AI_TensorClone](#oh_ai_tensorclone) (OH_AI_TensorHandle tensor) | 深拷贝一个张量。 |
| [OH_AI_TensorSetName](#oh_ai_tensorsetname) (OH_AI_TensorHandle tensor, const char \*name) | 设置张量的名称。 |
| [OH_AI_TensorGetName](#oh_ai_tensorgetname) (const OH_AI_TensorHandle tensor) | 获取张量的名称。 |
| [OH_AI_TensorSetDataType](#oh_ai_tensorsetdatatype) (OH_AI_TensorHandle tensor, OH_AI_DataType type) | 设置张量的数据类型。 |
| [OH_AI_TensorGetDataType](#oh_ai_tensorgetdatatype) (const OH_AI_TensorHandle tensor) | 获取张量类型。 |
| [OH_AI_TensorSetShape](#oh_ai_tensorsetshape) (OH_AI_TensorHandle tensor, const int64_t \*shape, size_t shape_num) | 设置张量的形状。 |
| [OH_AI_TensorGetShape](#oh_ai_tensorgetshape) (const OH_AI_TensorHandle tensor, size_t \*shape_num) | 获取张量的形状。 |
| [OH_AI_TensorSetFormat](#oh_ai_tensorsetformat) (OH_AI_TensorHandle tensor, OH_AI_Format format) | 设置张量数据的排列方式。 |
| [OH_AI_TensorGetFormat](#oh_ai_tensorgetformat) (const OH_AI_TensorHandle tensor) | 获取张量数据的排列方式。 |
| [OH_AI_TensorSetData](#oh_ai_tensorsetdata) (OH_AI_TensorHandle tensor, void \*data) | 设置张量的数据。 |
| [OH_AI_TensorGetData](#oh_ai_tensorgetdata) (const OH_AI_TensorHandle tensor) | 获取张量数据的指针。 |
| [OH_AI_TensorGetMutableData](#oh_ai_tensorgetmutabledata) (const OH_AI_TensorHandle tensor) | 获取可变的张量数据指针。如果数据为空则会开辟内存。 |
| [OH_AI_TensorGetElementNum](#oh_ai_tensorgetelementnum) (const OH_AI_TensorHandle tensor) | 获取张量元素数量。 |
| [OH_AI_TensorGetDataSize](#oh_ai_tensorgetdatasize) (const OH_AI_TensorHandle tensor) | 获取张量中的数据的字节数大小。 |
## **宏定义说明**
### OH_AI_MAX_SHAPE_NUM
```
#define OH_AI_MAX_SHAPE_NUM 32
```
**描述:**
维度信息,最大的维度为**MS_MAX_SHAPE_NUM**
## **类型定义说明**
### OH_AI_CallBackParam
```
typedef struct OH_AI_CallBackParam OH_AI_CallBackParam
```
**描述:**
回调函数中传入的算子信息。
### OH_AI_ContextHandle
```
typedef void* OH_AI_ContextHandle
```
**描述:**
Mindspore的上下文信息的指针,该指针会指向Context。
### OH_AI_DataType
```
typedef enum OH_AI_DataType OH_AI_DataType
```
**描述:**
MSTensor保存的数据支持的类型。
### OH_AI_DeviceInfoHandle
```
typedef void* OH_AI_DeviceInfoHandle
```
**描述:**
Mindspore的运行设备信息的指针。
### OH_AI_DeviceType
```
typedef enum OH_AI_DeviceType OH_AI_DeviceType
```
**描述:**
设备类型信息,包含了目前支持的设备类型。
### OH_AI_Format
```
typedef enum OH_AI_Format OH_AI_Format
```
**描述:**
MSTensor保存的数据支持的排列格式。
### OH_AI_KernelCallBack
```
typedef bool(* OH_AI_KernelCallBack) (const OH_AI_TensorHandleArray inputs, const OH_AI_TensorHandleArray outputs, const OH_AI_CallBackParam kernel_Info)
```
**描述:**
回调函数指针。
该函数指针是用于设置[OH_AI_ModelPredict](#oh_ai_modelpredict)函数参数中的两个回调函数。 该指针指向的函数需要包含三个参数,其中inputs和outputs对应了算子的输入和输出张量,kernel_Info表示当前算子的信息。 可以通过回调函数监控算子执行的情况,例如统计算子的执行时间,校验算子的正确性等等。
### OH_AI_ModelHandle
```
typedef void* OH_AI_ModelHandle
```
**描述:**
指向模型对象的指针。
### OH_AI_ModelType
```
typedef enum OH_AI_ModelType OH_AI_ModelType
```
**描述:**
模型文件的类型
### OH_AI_Status
```
typedef enum OH_AI_Status OH_AI_Status
```
**描述:**
Minspore的状态码。
### OH_AI_TensorHandle
```
typedef void* OH_AI_TensorHandle
```
**描述:**
指向张量对象句柄。
### OH_AI_TensorHandleArray
```
typedef struct OH_AI_TensorHandleArray OH_AI_TensorHandleArray
```
**描述:**
张量数组结构体,用于存储张量数组指针和张量数组长度。
## **枚举类型说明**
### OH_AI_CompCode
```
enum OH_AI_CompCode
```
**描述:**
Minspore不同组件的代码。
| 枚举值 | 描述 |
| -------- | -------- |
| OH_AI_COMPCODE_CORE | Minspore Core的代码。 |
| OH_AI_COMPCODE_LITE | Minspore Lite的代码。 |
### OH_AI_DataType
```
enum OH_AI_DataType
```
**描述:**
MSTensor保存的数据支持的类型。
| 枚举值 | 描述 |
| -------- | -------- |
| OH_AI_DATATYPE_UNKNOWN | 未知的数据类型。 |
| OH_AI_DATATYPE_OBJECTTYPE_STRING | String数据类型。 |
| OH_AI_DATATYPE_OBJECTTYPE_LIST | List数据类型。 |
| OH_AI_DATATYPE_OBJECTTYPE_TUPLE | Tuple数据类型。 |
| OH_AI_DATATYPE_OBJECTTYPE_TENSOR | TensorList数据类型。 |
| OH_AI_DATATYPE_NUMBERTYPE_BEGIN | Number类型的起始。 |
| OH_AI_DATATYPE_NUMBERTYPE_BOOL | Bool数据类型。 |
| OH_AI_DATATYPE_NUMBERTYPE_INT8 | Int8数据类型。 |
| OH_AI_DATATYPE_NUMBERTYPE_INT16 | 表示Int16数据类型。 |
| OH_AI_DATATYPE_NUMBERTYPE_INT32 | 表示Int32数据类型。 |
| OH_AI_DATATYPE_NUMBERTYPE_INT64 | 表示Int64数据类型。 |
| OH_AI_DATATYPE_NUMBERTYPE_UINT8 | 表示UInt8数据类型。 |
| OH_AI_DATATYPE_NUMBERTYPE_UINT16 | 表示UInt16数据类型。 |
| OH_AI_DATATYPE_NUMBERTYPE_UINT32 | 表示UInt32数据类型。 |
| OH_AI_DATATYPE_NUMBERTYPE_UINT64 | 表示UInt64数据类型。 |
| OH_AI_DATATYPE_NUMBERTYPE_FLOAT16 | 表示Float16数据类型。 |
| OH_AI_DATATYPE_NUMBERTYPE_FLOAT32 | 表示Float32数据类型。 |
| OH_AI_DATATYPE_NUMBERTYPE_FLOAT64 | 表示Float64数据类型。 |
| OH_AI_DATATYPE_NUMBERTYPE_END | 表示Number类型的结尾。 |
| OH_AI_DataTypeInvalid | 表示无效的数据类型。 |
### OH_AI_DeviceType
```
enum OH_AI_DeviceType
```
**描述:**
设备类型信息,包含了目前支持的设备类型。
| 枚举值 | 描述 |
| -------- | -------- |
| OH_AI_DEVICETYPE_CPU | 设备类型是CPU。 |
| OH_AI_DEVICETYPE_KIRIN_NPU | 设备类型是麒麟NPU。 |
| OH_AI_DEVICETYPE_INVALID | 设备类型无效。 |
### OH_AI_Format
```
enum OH_AI_Format
```
**描述:**
MSTensor保存的数据支持的排列格式。
| 枚举值 | 描述 |
| -------- | -------- |
| OH_AI_FORMAT_NCHW | 表示NCHW排列。 |
| OH_AI_FORMAT_NHWC | 表示NHWC排列。 |
| OH_AI_FORMAT_NHWC4 | 表示NHWC4排列。 |
| OH_AI_FORMAT_HWKC | 表示HWKC排列。 |
| OH_AI_FORMAT_HWCK | 表示HWCK排列。 |
| OH_AI_FORMAT_KCHW | 表示KCHW排列。 |
| OH_AI_FORMAT_CKHW | 表示CKHW排列。 |
| OH_AI_FORMAT_KHWC | 表示KHWC排列。 |
| OH_AI_FORMAT_CHWK | 表示CHWK排列。 |
| OH_AI_FORMAT_HW | 表示HW排列。 |
| OH_AI_FORMAT_HW4 | 表示HW4排列。 |
| OH_AI_FORMAT_NC | 表示NC排列。 |
| OH_AI_FORMAT_NC4 | 表示NC4排列。 |
| OH_AI_FORMAT_NC4HW4 | 表示NC4HW4排列。 |
| OH_AI_FORMAT_NCDHW | 表示NCDHW排列。 |
| OH_AI_FORMAT_NWC | 表示NWC排列。 |
| OH_AI_FORMAT_NCW | 表示NCW排列。 |
### OH_AI_ModelType
```
enum OH_AI_ModelType
```
**描述:**
模型文件的类型。
| 枚举值 | 描述 |
| -------- | -------- |
| OH_AI_MODELTYPE_MINDIR | 模型类型是MindIR。 |
| OH_AI_MODELTYPE_INVALID | 模型类型无效。 |
### OH_AI_Status
```
enum OH_AI_Status
```
**描述:**
Minspore的状态码。
| 枚举值 | 描述 |
| -------- | -------- |
| OH_AI_STATUS_SUCCESS | 通用的成功状态码。 |
| OH_AI_STATUS_CORE_FAILED | Mindspore Core 失败状态码。 |
| OH_AI_STATUS_LITE_ERROR | Mindspore Lite 异常状态码。 |
| OH_AI_STATUS_LITE_NULLPTR | Mindspore Lite 空指针状态码。 |
| OH_AI_STATUS_LITE_PARAM_INVALID | Mindspore Lite 参数异常状态码。 |
| OH_AI_STATUS_LITE_NO_CHANGE | Mindspore Lite 未改变状态码。 |
| OH_AI_STATUS_LITE_SUCCESS_EXIT | Mindspore Lite 没有错误但是退出的状态码。 |
| OH_AI_STATUS_LITE_MEMORY_FAILED | Mindspore Lite 内存分配失败的状态码。 |
| OH_AI_STATUS_LITE_NOT_SUPPORT | Mindspore Lite 功能未支持的状态码。 |
| OH_AI_STATUS_LITE_THREADPOOL_ERROR | Mindspore Lite 线程池异常状态码。 |
| OH_AI_STATUS_LITE_UNINITIALIZED_OBJ | Mindspore Lite 未初始化状态码。 |
| OH_AI_STATUS_LITE_OUT_OF_TENSOR_RANGE | Mindspore Lite 张量溢出错误的状态码。 |
| OH_AI_STATUS_LITE_INPUT_TENSOR_ERROR | Mindspore Lite 输入张量异常的状态码。 |
| OH_AI_STATUS_LITE_REENTRANT_ERROR | Mindspore Lite 重入异常的状态码。 |
| OH_AI_STATUS_LITE_GRAPH_FILE_ERROR | Mindspore Lite 文件异常状态码。 |
| OH_AI_STATUS_LITE_NOT_FIND_OP | Mindspore Lite 未找到算子的状态码。 |
| OH_AI_STATUS_LITE_INVALID_OP_NAME | Mindspore Lite 无效算子状态码。 |
| OH_AI_STATUS_LITE_INVALID_OP_ATTR | Mindspore Lite 无效算子超参数状态码。 |
| OH_AI_STATUS_LITE_OP_EXECUTE_FAILURE | Mindspore Lite 算子执行失败的状态码。 |
| OH_AI_STATUS_LITE_FORMAT_ERROR | Mindspore Lite 张量格式异常状态码。 |
| OH_AI_STATUS_LITE_INFER_ERROR | Mindspore Lite 形状推理异常状态码。 |
| OH_AI_STATUS_LITE_INFER_INVALID | Mindspore Lite 无效的形状推理的状态码。 |
| OH_AI_STATUS_LITE_INPUT_PARAM_INVALID | Mindspore Lite 用户输入的参数无效状态码。 |
## **函数说明**
### OH_AI_ContextAddDeviceInfo()
```
OH_AI_API void OH_AI_ContextAddDeviceInfo (OH_AI_ContextHandle context, OH_AI_DeviceInfoHandle device_info )
```
**描述:**
添加运行设备信息。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| context | 指向上下文信息实例的[OH_AI_ContextHandle](#oh_ai_contexthandle)。 |
| device_info | 指向设备信息实例的[OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle)。 |
### OH_AI_ContextCreate()
```
OH_AI_API OH_AI_ContextHandle OH_AI_ContextCreate ()
```
**描述:**
创建一个上下文的对象。
**返回:**
指向上下文信息的[OH_AI_ContextHandle](#oh_ai_contexthandle)
### OH_AI_ContextDestroy()
```
OH_AI_API void OH_AI_ContextDestroy (OH_AI_ContextHandle * context)
```
**描述:**
释放上下文对象。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| context | 指向[OH_AI_ContextHandle](#oh_ai_contexthandle)的二级指针,上下文销毁后会对context置为空指针。 |
### OH_AI_ContextGetEnableParallel()
```
OH_AI_API bool OH_AI_ContextGetEnableParallel (const OH_AI_ContextHandle context)
```
**描述:**
获取是否支持算子间并行。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| context | 指向上下文信息实例的[OH_AI_ContextHandle](#oh_ai_contexthandle)。 |
**返回:**
是否支持并行。true 为支持并行, false 为不支持并行。
### OH_AI_ContextGetThreadAffinityCoreList()
```
OH_AI_API const int32_t* OH_AI_ContextGetThreadAffinityCoreList (const OH_AI_ContextHandle context, size_t * core_num )
```
**描述:**
获取CPU绑核列表。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| context | 指向上下文信息实例的[OH_AI_ContextHandle](#oh_ai_contexthandle)。 |
| core_num | 该参数是输出参数,表示核的数量。 |
**返回:**
CPU绑核列表。
### OH_AI_ContextGetThreadAffinityMode()
```
OH_AI_API int OH_AI_ContextGetThreadAffinityMode (const OH_AI_ContextHandle context)
```
**描述:**
获取运行时线程绑定CPU核心的策略。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| context | 指向上下文信息实例的[OH_AI_ContextHandle](#oh_ai_contexthandle)。 |
**返回:**
绑核策略。一共有三种策略,0为不绑核, 1为大核优先, 2为小核优先。
### OH_AI_ContextGetThreadNum()
```
OH_AI_API int32_t OH_AI_ContextGetThreadNum (const OH_AI_ContextHandle context)
```
**描述:**
获取线程数量。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| context | 指向上下文信息实例的[OH_AI_ContextHandle](#oh_ai_contexthandle)。 |
**返回:**
当前的线程数量。
### OH_AI_ContextSetEnableParallel()
```
OH_AI_API void OH_AI_ContextSetEnableParallel (OH_AI_ContextHandle context, bool is_parallel )
```
**描述:**
设置运行时是否支持并行。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| context | 指向上下文信息实例的[OH_AI_ContextHandle](#oh_ai_contexthandle)。 |
| is_parallel | 是否支持并行。true 为支持并行, false 为不支持并行。 |
### OH_AI_ContextSetThreadAffinityCoreList()
```
OH_AI_API void OH_AI_ContextSetThreadAffinityCoreList (OH_AI_ContextHandle context, const int32_t * core_list, size_t core_num )
```
**描述:**
设置运行时线程绑定CPU核心的列表。
例如:当core_list=[2,6,8]时,则线程会在CPU的第2,6,8个核心上运行。 如果对于同一个上下文对象,调用了[OH_AI_ContextSetThreadAffinityMode](#oh_ai_contextsetthreadaffinitymode)[OH_AI_ContextSetThreadAffinityCoreList](#oh_ai_contextsetthreadaffinitycorelist) 这两个函数,则仅[OH_AI_ContextSetThreadAffinityCoreList](#oh_ai_contextsetthreadaffinitycorelist)的core_list参数生效,而[OH_AI_ContextSetThreadAffinityMode](#oh_ai_contextsetthreadaffinitymode)的 mode参数不生效。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| context | 指向上下文信息实例的[OH_AI_ContextHandle](#oh_ai_contexthandle)。 |
| core_list | CPU绑核的列表。 |
| core_num | 核的数量,它就代表**core_list**的长度。 |
### OH_AI_ContextSetThreadAffinityMode()
```
OH_AI_API void OH_AI_ContextSetThreadAffinityMode (OH_AI_ContextHandle context, int mode )
```
**描述:**
设置运行时线程绑定CPU核心的策略,按照CPU物理核频率分为大核与小核。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| context | 指向上下文信息实例的[OH_AI_ContextHandle](#oh_ai_contexthandle)。 |
| mode | 绑核策略。一共有三种策略,0为不绑核, 1为大核优先, 2为小核优先。 |
### OH_AI_ContextSetThreadNum()
```
OH_AI_API void OH_AI_ContextSetThreadNum (OH_AI_ContextHandle context, int32_t thread_num )
```
**描述:**
设置运行时的线程数量。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| context | 指向上下文信息实例的[OH_AI_ContextHandle](#oh_ai_contexthandle) |
| thread_num | 运行时的线程数量。 |
### OH_AI_DeviceInfoCreate()
```
OH_AI_API OH_AI_DeviceInfoHandle OH_AI_DeviceInfoCreate (OH_AI_DeviceType device_type)
```
**描述:**
创建一个设备信息对象。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| device_type | 设备类型, 具体见[OH_AI_DeviceType](#oh_ai_devicetype)。 |
**返回:**
指向设备信息实例的[OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle)
### OH_AI_DeviceInfoDestroy()
```
OH_AI_API void OH_AI_DeviceInfoDestroy (OH_AI_DeviceInfoHandle * device_info)
```
**描述:**
释放设备信息实例。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| device_info | 指向设备信息实例的[OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle)。 |
### OH_AI_DeviceInfoGetDeviceType()
```
OH_AI_API OH_AI_DeviceType OH_AI_DeviceInfoGetDeviceType (const OH_AI_DeviceInfoHandle device_info)
```
**描述:**
获取设备的类型。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| device_info | 指向设备信息实例的[OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle)。 |
**返回:**
生产商设备类型。
### OH_AI_DeviceInfoGetEnableFP16()
```
OH_AI_API bool OH_AI_DeviceInfoGetEnableFP16 (const OH_AI_DeviceInfoHandle device_info)
```
**描述:**
获取是否开启float16推理模式, 仅CPU/GPU设备可用。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| device_info | 指向设备信息实例的[OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle)。 |
**返回:**
设置是否开启float16推理模式。
### OH_AI_DeviceInfoGetFrequency()
```
OH_AI_API int OH_AI_DeviceInfoGetFrequency (const OH_AI_DeviceInfoHandle device_info)
```
**描述:**
获取NPU的频率类型,仅NPU设备可用。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| device_info | 指向设备信息实例的[OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle)。 |
**返回:**
NPU的频率类型。取值范围为0-4,1表示低功耗,2表示平衡,3表示高性能,4表示超高性能。
### OH_AI_DeviceInfoGetProvider()
```
OH_AI_API const char* OH_AI_DeviceInfoGetProvider (const OH_AI_DeviceInfoHandle device_info)
```
**描述:**
获取生产商的名称。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| device_info | 指向设备信息实例的[OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle)。 |
**返回:**
生产商的名称。
### OH_AI_DeviceInfoGetProviderDevice()
```
OH_AI_API const char* OH_AI_DeviceInfoGetProviderDevice (const OH_AI_DeviceInfoHandle device_info)
```
**描述:**
获取生产商设备的名称。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| device_info | 指向设备信息实例的[OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle)。 |
**返回:**
生产商设备的名称。
### OH_AI_DeviceInfoSetEnableFP16()
```
OH_AI_API void OH_AI_DeviceInfoSetEnableFP16 (OH_AI_DeviceInfoHandle device_info, bool is_fp16 )
```
**描述:**
设置是否开启float16推理模式,仅CPU/GPU设备可用。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| device_info | 指向设备信息实例的[OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle)。 |
| is_fp16 | 是否开启float16推理模式。 |
### OH_AI_DeviceInfoSetFrequency()
```
OH_AI_API void OH_AI_DeviceInfoSetFrequency (OH_AI_DeviceInfoHandle device_info, int frequency )
```
**描述:**
设置NPU的频率,仅NPU设备可用。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| device_info | 指向设备信息实例的[OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle)。 |
| frequency | 频率类型,取值范围为0-4,默认是3。1表示低功耗,2表示平衡,3表示高性能,4表示超高性能。 |
### OH_AI_DeviceInfoSetProvider()
```
OH_AI_API void OH_AI_DeviceInfoSetProvider (OH_AI_DeviceInfoHandle device_info, const char * provider )
```
**描述:**
设置供应商的名称。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| device_info | 指向设备信息实例的[OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle)。 |
| provider | 供应商的名称。 |
### OH_AI_DeviceInfoSetProviderDevice()
```
OH_AI_API void OH_AI_DeviceInfoSetProviderDevice (OH_AI_DeviceInfoHandle device_info, const char * device )
```
**描述:**
设置生产商设备的名称。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| device_info | 指向设备信息实例的[OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle)。 |
| device | 生产商设备名称。 例如: CPU。 |
### OH_AI_ModelBuild()
```
OH_AI_API OH_AI_Status OH_AI_ModelBuild (OH_AI_ModelHandle model, const void * model_data, size_t data_size, OH_AI_ModelType model_type, const OH_AI_ContextHandle model_context )
```
**描述:**
从内存缓冲区加载并编译MindSpore模型。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| model | 模型对象指针。 |
| model_data | 内存中已经加载的模型数据地址。 |
| data_size | 模型数据的长度。 |
| model_type | 模型文件类型,具体见[OH_AI_ModelType](#oh_ai_modeltype)。 |
| model_context | 模型运行时的上下文环境,具体见 [OH_AI_ContextHandle](#oh_ai_contexthandle)。 |
**返回:**
枚举类型的状态码[OH_AI_Status](#oh_ai_status),若返回MSStatus::kMSStatusSuccess则证明创建成功。
### OH_AI_ModelBuildFromFile()
```
OH_AI_API OH_AI_Status OH_AI_ModelBuildFromFile (OH_AI_ModelHandle model, const char * model_path, OH_AI_ModelType model_type, const OH_AI_ContextHandle model_context )
```
**描述:**
通过模型文件加载并编译MindSpore模型。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| model | 模型对象指针。 |
| model_path | 模型文件路径。 |
| model_type | 模型文件类型,具体见[OH_AI_ModelType](#oh_ai_modeltype)。 |
| model_context | 模型运行时的上下文环境,具体见 [OH_AI_ContextHandle](#oh_ai_contexthandle)。 |
**返回:**
枚举类型的状态码[OH_AI_Status](#oh_ai_status),若返回MSStatus::kMSStatusSuccess则证明创建成功。
### OH_AI_ModelCreate()
```
OH_AI_API OH_AI_ModelHandle OH_AI_ModelCreate ()
```
**描述:**
创建一个模型对象。
**返回:**
模型对象指针。
### OH_AI_ModelDestroy()
```
OH_AI_API void OH_AI_ModelDestroy (OH_AI_ModelHandle * model)
```
**描述:**
释放一个模型对象。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| model | 模型对象指针。 |
### OH_AI_ModelGetInputByTensorName()
```
OH_AI_API OH_AI_TensorHandle OH_AI_ModelGetInputByTensorName (const OH_AI_ModelHandle model, const char * tensor_name )
```
**描述:**
通过张量名获取模型的输入张量。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| model | 模型对象指针。 |
| tensor_name | 张量名称。 |
**返回:**
tensor_name所对应的输入张量的张量指针,如果输入中没有该张量则返回空。
### OH_AI_ModelGetInputs()
```
OH_AI_API OH_AI_TensorHandleArray OH_AI_ModelGetInputs (const OH_AI_ModelHandle model)
```
**描述:**
获取模型的输入张量数组结构体。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| model | 模型对象指针。 |
**返回:**
模型输入对应的张量数组结构体。
### OH_AI_ModelGetOutputByTensorName()
```
OH_AI_API OH_AI_TensorHandle OH_AI_ModelGetOutputByTensorName (const OH_AI_ModelHandle model, const char * tensor_name )
```
**描述:**
通过张量名获取模型的输出张量。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| model | 模型对象指针。 |
| tensor_名称 | 张量名称。 |
**返回:**
tensor_name所对应的输入张量的张量指针,如果输出中没有该张量则返回空。
### OH_AI_ModelGetOutputs()
```
OH_AI_API OH_AI_TensorHandleArray OH_AI_ModelGetOutputs (const OH_AI_ModelHandle model)
```
**描述:**
获取模型的输出张量数组结构体。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| model | 模型对象指针。 |
**返回:**
模型输出对应的张量数组结构体。
### OH_AI_ModelPredict()
```
OH_AI_API OH_AI_Status OH_AI_ModelPredict (OH_AI_ModelHandle model, const OH_AI_TensorHandleArray inputs, OH_AI_TensorHandleArray * outputs, const OH_AI_KernelCallBack before, const OH_AI_KernelCallBack after )
```
**描述:**
执行模型推理。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| model | 模型对象指针。 |
| inputs | 模型输入对应的张量数组结构体。 |
| outputs | 模型输出对应的张量数组结构体的指针。 |
| before | 模型推理前执行的回调函数。 |
| after | 模型推理后执行的回调函数。 |
**返回:**
枚举类型的状态码[OH_AI_Status](#oh_ai_status),若返回MSStatus::kMSStatusSuccess则证明创建成功。
### OH_AI_ModelResize()
```
OH_AI_API OH_AI_Status OH_AI_ModelResize (OH_AI_ModelHandle model, const OH_AI_TensorHandleArray inputs, OH_AI_ShapeInfo * shape_infos, size_t shape_info_num )
```
**描述:**
调整已编译模型的输入形状。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| model | 模型对象指针。 |
| inputs | 模型输入对应的张量数组结构体。 |
| shape_infos | 输入形状信息数组,按模型输入顺序排列的由形状信息组成的数组,模型会按顺序依次调整张量形状。 |
| shape_info_num | 形状信息数组的长度。 |
**返回:**
枚举类型的状态码[OH_AI_Status](#oh_ai_status),若返回MSStatus::kMSStatusSuccess则证明创建成功。
### OH_AI_TensorClone()
```
OH_AI_API OH_AI_TensorHandle OH_AI_TensorClone (OH_AI_TensorHandle tensor)
```
**描述:**
深拷贝一个张量。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| tensor | 待拷贝张量的指针。 |
**返回:**
指向新张量对象句柄。
### OH_AI_TensorCreate()
```
OH_AI_API OH_AI_TensorHandle OH_AI_TensorCreate (const char *name, OH_AI_DataType type, const int64_t * shape, size_t shape_num, const void * data, size_t data_len )
```
**描述:**
创建一个张量对象。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| 名称 | 张量名称 |
| type | 张量的数据类型 |
| shape | 张量的维度数组。 |
| shape_num | 张量维度数组长度。 |
| data | 指向数据的指针。 |
| data_len | 数据的长度。 |
**返回:**
指向张量对象句柄。
### OH_AI_TensorDestroy()
```
OH_AI_API void OH_AI_TensorDestroy (OH_AI_TensorHandle * tensor)
```
**描述:**
释放张量对象。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| tensor | 指向张量句柄的二级指针。 |
### OH_AI_TensorGetData()
```
OH_AI_API const void* OH_AI_TensorGetData (const OH_AI_TensorHandle tensor)
```
**描述:**
获取张量数据的指针。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| tensor | 张量对象句柄。 |
**返回:**
张量数据的指针。
### OH_AI_TensorGetDataSize()
```
OH_AI_API size_t OH_AI_TensorGetDataSize (const OH_AI_TensorHandle tensor)
```
**描述:**
获取张量中的数据的字节数大小。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| tensor | 张量对象句柄。 |
**返回:**
张量数据的字节数大小。
### OH_AI_TensorGetDataType()
```
OH_AI_API OH_AI_DataType OH_AI_TensorGetDataType (const OH_AI_TensorHandle tensor)
```
**描述:**
获取张量类型。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| tensor | 张量对象句柄。 |
**返回:**
张量的数据类型。
### OH_AI_TensorGetElementNum()
```
OH_AI_API int64_t OH_AI_TensorGetElementNum (const OH_AI_TensorHandle tensor)
```
**描述:**
获取张量元素数量。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| tensor | 张量对象句柄。 |
**返回:**
张量的元素数量。
### OH_AI_TensorGetFormat()
```
OH_AI_API OH_AI_Format OH_AI_TensorGetFormat (const OH_AI_TensorHandle tensor)
```
**描述:**
获取张量数据的排列方式。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| tensor | 张量对象句柄。 |
**返回:**
张量数据的排列方式。
### OH_AI_TensorGetMutableData()
```
OH_AI_API void* OH_AI_TensorGetMutableData (const OH_AI_TensorHandle tensor)
```
**描述:**
获取可变的张量数据指针。如果数据为空则会开辟内存。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| tensor | 张量对象句柄。 |
**返回:**
张量数据的指针。
### OH_AI_TensorGetName()
```
OH_AI_API const char* OH_AI_TensorGetName (const OH_AI_TensorHandle tensor)
```
**描述:**
获取张量的名称。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| tensor | 张量对象句柄。 |
**返回:**
张量的名称。
### OH_AI_TensorGetShape()
```
OH_AI_API const int64_t* OH_AI_TensorGetShape (const OH_AI_TensorHandle tensor, size_t * shape_num )
```
**描述:**
获取张量的形状。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| tensor | 张量对象句柄。 |
| shape_num | 该参数是输出参数,形状数组的长度会写入该变量。 |
**返回:**
形状数组。
### OH_AI_TensorSetData()
```
OH_AI_API void OH_AI_TensorSetData (OH_AI_TensorHandle tensor, void * data )
```
**描述:**
设置张量的数据。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| tensor | 张量对象句柄。 |
| data | 指向数据的指针。 |
### OH_AI_TensorSetDataType()
```
OH_AI_API void OH_AI_TensorSetDataType (OH_AI_TensorHandle tensor, OH_AI_DataType type )
```
**描述:**
设置张量的数据类型。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| tensor | 张量对象句柄。 |
| type | 数据类型,具体见[OH_AI_DataType](#oh_ai_datatype)。 |
### OH_AI_TensorSetFormat()
```
OH_AI_API void OH_AI_TensorSetFormat (OH_AI_TensorHandle tensor, OH_AI_Format format )
```
**描述:**
设置张量数据的排列方式。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| tensor | 张量对象句柄。 |
| format | 张量数据排列方式。 |
### OH_AI_TensorSetName()
```
OH_AI_API void OH_AI_TensorSetName (OH_AI_TensorHandle tensor, const char *name )
```
**描述:**
设置张量的名称。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| tensor | 张量对象句柄。 |
| 名称 | 张量名称。 |
### OH_AI_TensorSetShape()
```
OH_AI_API void OH_AI_TensorSetShape (OH_AI_TensorHandle tensor, const int64_t * shape, size_t shape_num )
```
**描述:**
设置张量的形状。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| tensor | 张量对象句柄。 |
| shape | 形状数组。 |
| shape_num | 张量形状数组长度。 |
# OH_AI_CallBackParam
## 概述
回调函数中传入的算子信息。
**自从:**
9
**相关模块:**
[MindSpore](_mind_spore.md)
## 汇总
### 成员变量
| 成员变量名称 | 描述 |
| -------- | -------- |
| [node_name](#node_name) | 算子名称。 |
| [node_type](#node_type) | 算子类型。 |
## 结构体成员变量说明
### node_name
```
char* OH_AI_CallBackParam::node_name
```
**描述:**
算子名称。
### node_type
```
char* OH_AI_CallBackParam::node_type
```
**描述:**
算子类型。
# OH_AI_ShapeInfo
## 概述
维度信息,最大的维度为MS_MAX_SHAPE_NUM。
**自从:**
9
**相关模块:**
[MindSpore](_mind_spore.md)
## 汇总
### 成员变量
| 成员变量名称 | 描述 |
| -------- | -------- |
| [shape_num](#shape_num) | 维度数组长度。 |
| [shape](#shape) [OH_AI_MAX_SHAPE_NUM] | 维度数组。 |
## 结构体成员变量说明
### shape
```
int64_t OH_AI_ShapeInfo::shape[OH_AI_MAX_SHAPE_NUM]
```
**描述:**
维度数组。
### shape_num
```
size_t OH_AI_ShapeInfo::shape_num
```
**描述:**
维度数组长度。
# OH_AI_TensorHandleArray
## 概述
张量数组结构体,用于存储张量数组指针和张量数组长度。
**自从:**
9
**相关模块:**
[MindSpore](_mind_spore.md)
## 汇总
### 成员变量
| 成员变量名称 | 描述 |
| -------- | -------- |
| [handle_num](#handle_num) | 张量数组长度。 |
| [handle_list](#handle_list) | 指向张量数组的指针。 |
## 结构体成员变量说明
### handle_list
```
OH_AI_TensorHandle* OH_AI_TensorHandleArray::handle_list
```
**描述:**
指向张量数组的指针。
### handle_num
```
size_t OH_AI_TensorHandleArray::handle_num
```
**描述:**
张量数组长度。
# context.h
## 概述
提供了Context相关的接口,可以配置运行时信息。
**自从:**
9
**相关模块:**
[MindSpore](_mind_spore.md)
## 汇总
### 类型定义
| 类型定义名称 | 描述 |
| -------- | -------- |
| [OH_AI_ContextHandle](_mind_spore.md#oh_ai_contexthandle) | Mindspore的上下文信息的指针,该指针会指向Context。 |
| [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) | Mindspore的运行设备信息的指针。 |
### 函数
| 函数名称 | 描述 |
| -------- | -------- |
| [OH_AI_ContextCreate](_mind_spore.md#oh_ai_contextcreate) () | 创建一个上下文的对象。 |
| [OH_AI_ContextDestroy](_mind_spore.md#oh_ai_contextdestroy) (OH_AI_ContextHandle \*context) | 释放上下文对象。 |
| [OH_AI_ContextSetThreadNum](_mind_spore.md#oh_ai_contextsetthreadnum) (OH_AI_ContextHandle context, int32_t thread_num) | 设置运行时的线程数量。 |
| [OH_AI_ContextGetThreadNum](_mind_spore.md#oh_ai_contextgetthreadnum) (const OH_AI_ContextHandle context) | 获取线程数量。 |
| [OH_AI_ContextSetThreadAffinityMode](_mind_spore.md#oh_ai_contextsetthreadaffinitymode) (OH_AI_ContextHandle context, int mode) | 设置运行时线程绑定CPU核心的策略,按照CPU物理核频率分为大核与小核。 |
| [OH_AI_ContextGetThreadAffinityMode](_mind_spore.md#oh_ai_contextgetthreadaffinitymode) (const OH_AI_ContextHandle context) | 获取运行时线程绑定CPU核心的策略。 |
| [OH_AI_ContextSetThreadAffinityCoreList](_mind_spore.md#oh_ai_contextsetthreadaffinitycorelist) (OH_AI_ContextHandle context, const int32_t \*core_list, size_t core_num) | 设置运行时线程绑定CPU核心的列表。 |
| [OH_AI_ContextGetThreadAffinityCoreList](_mind_spore.md#oh_ai_contextgetthreadaffinitycorelist) (const OH_AI_ContextHandle context, size_t \*core_num) | 获取CPU绑核列表。 |
| [OH_AI_ContextSetEnableParallel](_mind_spore.md#oh_ai_contextsetenableparallel) (OH_AI_ContextHandle context, bool is_parallel) | 设置运行时是否支持并行。 |
| [OH_AI_ContextGetEnableParallel](_mind_spore.md#oh_ai_contextgetenableparallel) (const OH_AI_ContextHandle context) | 获取是否支持算子间并行。 |
| [OH_AI_ContextAddDeviceInfo](_mind_spore.md#oh_ai_contextadddeviceinfo) (OH_AI_ContextHandle context, OH_AI_DeviceInfoHandle device_info) | 添加运行设备信息。 |
| [OH_AI_DeviceInfoCreate](_mind_spore.md#oh_ai_deviceinfocreate) (OH_AI_DeviceType device_type) | 创建一个设备信息对象。 |
| [OH_AI_DeviceInfoDestroy](_mind_spore.md#oh_ai_deviceinfodestroy) (OH_AI_DeviceInfoHandle \*device_info) | 释放设备信息实例。 |
| [OH_AI_DeviceInfoSetProvider](_mind_spore.md#oh_ai_deviceinfosetprovider) (OH_AI_DeviceInfoHandle device_info, const char \*provider) | 设置供应商的名称。 |
| [OH_AI_DeviceInfoGetProvider](_mind_spore.md#oh_ai_deviceinfogetprovider) (const OH_AI_DeviceInfoHandle device_info) | 获取生产商的名称。 |
| [OH_AI_DeviceInfoSetProviderDevice](_mind_spore.md#oh_ai_deviceinfosetproviderdevice) (OH_AI_DeviceInfoHandle device_info, const char \*device) | 设置生产商设备的名称。 |
| [OH_AI_DeviceInfoGetProviderDevice](_mind_spore.md#oh_ai_deviceinfogetproviderdevice) (const OH_AI_DeviceInfoHandle device_info) | 获取生产商设备的名称。 |
| [OH_AI_DeviceInfoGetDeviceType](_mind_spore.md#oh_ai_deviceinfogetdevicetype) (const OH_AI_DeviceInfoHandle device_info) | 获取设备的类型。 |
| [OH_AI_DeviceInfoSetEnableFP16](_mind_spore.md#oh_ai_deviceinfosetenablefp16) (OH_AI_DeviceInfoHandle device_info, bool is_fp16) | 设置是否开启float16推理模式,仅CPU/GPU设备可用。 |
| [OH_AI_DeviceInfoGetEnableFP16](_mind_spore.md#oh_ai_deviceinfogetenablefp16) (const OH_AI_DeviceInfoHandle device_info) | 获取是否开启float16推理模式, 仅CPU/GPU设备可用。 |
| [OH_AI_DeviceInfoSetFrequency](_mind_spore.md#oh_ai_deviceinfosetfrequency) (OH_AI_DeviceInfoHandle device_info, int frequency) | 设置NPU的频率,仅NPU设备可用。 |
| [OH_AI_DeviceInfoGetFrequency](_mind_spore.md#oh_ai_deviceinfogetfrequency) (const OH_AI_DeviceInfoHandle device_info) | 获取NPU的频率类型,仅NPU设备可用。 |
# data_type.h
## 概述
声明了张量的数据的类型。
**自从:**
9
**相关模块:**
[MindSpore](_mind_spore.md)
## 汇总
### 类型定义
| 类型定义名称 | 描述 |
| -------- | -------- |
| [OH_AI_DataType](_mind_spore.md#oh_ai_datatype) | MSTensor保存的数据支持的类型。 |
### 枚举
| 枚举名称 | 描述 |
| -------- | -------- |
| [OH_AI_DataType](_mind_spore.md#oh_ai_datatype) {<br/>OH_AI_DATATYPE_UNKNOWN = 0,<br/>OH_AI_DATATYPE_OBJECTTYPE_STRING = 12, <br/>OH_AI_DATATYPE_OBJECTTYPE_LIST = 13, <br/>OH_AI_DATATYPE_OBJECTTYPE_TUPLE = 14, <br/>OH_AI_DATATYPE_OBJECTTYPE_TENSOR = 17,<br/>OH_AI_DATATYPE_NUMBERTYPE_BEGIN = 29, <br/>OH_AI_DATATYPE_NUMBERTYPE_BOOL = 30, <br/>OH_AI_DATATYPE_NUMBERTYPE_INT8 = 32, <br/>OH_AI_DATATYPE_NUMBERTYPE_INT16 = 33,<br/>OH_AI_DATATYPE_NUMBERTYPE_INT32 = 34,<br/>OH_AI_DATATYPE_NUMBERTYPE_INT64 = 35, <br/>OH_AI_DATATYPE_NUMBERTYPE_UINT8 = 37, <br/>OH_AI_DATATYPE_NUMBERTYPE_UINT16 = 38, <br/>OH_AI_DATATYPE_NUMBERTYPE_UINT32 = 39,<br/>OH_AI_DATATYPE_NUMBERTYPE_UINT64 = 40, <br/>OH_AI_DATATYPE_NUMBERTYPE_FLOAT16 = 42, <br/>OH_AI_DATATYPE_NUMBERTYPE_FLOAT32 = 43, <br/>OH_AI_DATATYPE_NUMBERTYPE_FLOAT64 = 44, <br/>OH_AI_DATATYPE_NUMBERTYPE_END = 46,<br/>OH_AI_DataTypeInvalid = INT32_MAX } | MSTensor保存的数据支持的类型。 |
# format.h
## 概述
提供张量数据的排列格式。
**自从:**
9
**相关模块:**
[MindSpore](_mind_spore.md)
## 汇总
### 类型定义
| 类型定义名称 | 描述 |
| -------- | -------- |
| [OH_AI_Format](_mind_spore.md#oh_ai_format) | MSTensor保存的数据支持的排列格式。 |
### 枚举
| 枚举名称 | 描述 |
| -------- | -------- |
| [OH_AI_Format](_mind_spore.md#oh_ai_format) {<br/>OH_AI_FORMAT_NCHW = 0,<br/>OH_AI_FORMAT_NHWC = 1,<br/>OH_AI_FORMAT_NHWC4 = 2,<br/>OH_AI_FORMAT_HWKC = 3,<br/>OH_AI_FORMAT_HWCK = 4,<br/>OH_AI_FORMAT_KCHW = 5,<br/>OH_AI_FORMAT_CKHW = 6,<br/>OH_AI_FORMAT_KHWC = 7,<br/>OH_AI_FORMAT_CHWK = 8,<br/>OH_AI_FORMAT_HW = 9,<br/>OH_AI_FORMAT_HW4 = 10,<br/>OH_AI_FORMAT_NC = 11,<br/>OH_AI_FORMAT_NC4 = 12,<br/>OH_AI_FORMAT_NC4HW4 = 13,<br/>OH_AI_FORMAT_NCDHW = 15,<br/>OH_AI_FORMAT_NWC = 16,<br/>OH_AI_FORMAT_NCW = 17 } | MSTensor保存的数据支持的排列格式。 |
# model.h
## 概述
提供了模型相关接口,可以用于模型创建、模型推理等。
**自从:**
9
**相关模块:**
[MindSpore](_mind_spore.md)
## 汇总
### 结构体
| 结构体名称 | 描述 |
| -------- | -------- |
| [OH_AI_TensorHandleArray](_o_h___a_i___tensor_handle_array.md) | 张量数组结构体,用于存储张量数组指针和张量数组长度 |
| [OH_AI_ShapeInfo](_o_h___a_i___shape_info.md) | 维度信息,最大的维度为**MS_MAX_SHAPE_NUM** |
| [OH_AI_CallBackParam](_o_h___a_i___call_back_param.md) | 回调函数中传入的算子信息。 |
### 宏定义
| 宏定义名称 | 描述 |
| -------- | -------- |
| [OH_AI_MAX_SHAPE_NUM](_mind_spore.md#oh_ai_max_shape_num) 32 | 维度信息,最大的维度为**MS_MAX_SHAPE_NUM**。 |
### 类型定义
| 类型定义名称 | 描述 |
| -------- | -------- |
| [OH_AI_ModelHandle](_mind_spore.md#oh_ai_modelhandle) | 指向模型对象的指针。 |
| [OH_AI_TensorHandleArray](_mind_spore.md#oh_ai_tensorhandlearray) | 张量数组结构体,用于存储张量数组指针和张量数组长度 |
| [OH_AI_ShapeInfo](_o_h___a_i___shape_info.md) | 维度信息,最大的维度为**MS_MAX_SHAPE_NUM** |
| [OH_AI_CallBackParam](_mind_spore.md#oh_ai_callbackparam) | 回调函数中传入的算子信息。 |
| [OH_AI_KernelCallBack](_mind_spore.md#oh_ai_kernelcallback)) (const OH_AI_TensorHandleArray inputs, const OH_AI_TensorHandleArray outputs, const OH_AI_CallBackParam kernel_Info) | 回调函数指针。 |
### 函数
| 函数名称 | 描述 |
| -------- | -------- |
| [OH_AI_ModelCreate](_mind_spore.md#oh_ai_modelcreate) () | 创建一个模型对象。 |
| [OH_AI_ModelDestroy](_mind_spore.md#oh_ai_modeldestroy) (OH_AI_ModelHandle \*model) | 释放一个模型对象。 |
| [OH_AI_ModelBuild](_mind_spore.md#oh_ai_modelbuild) (OH_AI_ModelHandle model, const void \*model_data, <br/>size_t data_size, OH_AI_ModelType model_type, <br/>const OH_AI_ContextHandle model_context) | 从内存缓冲区加载并编译MindSpore模型。 |
| [OH_AI_ModelBuildFromFile](_mind_spore.md#oh_ai_modelbuildfromfile) (OH_AI_ModelHandle model, <br/>const char \*model_path, OH_AI_ModelType model_type, const OH_AI_ContextHandle model_context) | 通过模型文件加载并编译MindSpore模型。 |
| [OH_AI_ModelResize](_mind_spore.md#oh_ai_modelresize) (OH_AI_ModelHandle model, const OH_AI_TensorHandleArray inputs,<br/> OH_AI_ShapeInfo \*shape_infos, size_t shape_info_num) | 调整已编译模型的输入形状。 |
| [OH_AI_ModelPredict](_mind_spore.md#oh_ai_modelpredict) (OH_AI_ModelHandle model, const OH_AI_TensorHandleArray inputs, OH_AI_TensorHandleArray \*outputs, const OH_AI_KernelCallBack before, const OH_AI_KernelCallBack after) | 执行模型推理。 |
| [OH_AI_ModelGetInputs](_mind_spore.md#oh_ai_modelgetinputs) (const OH_AI_ModelHandle model) | 获取模型的输入张量数组结构体。 |
| [OH_AI_ModelGetOutputs](_mind_spore.md#oh_ai_modelgetoutputs) (const OH_AI_ModelHandle model) | 获取模型的输出张量数组结构体。 |
| [OH_AI_ModelGetInputByTensorName](_mind_spore.md#oh_ai_modelgetinputbytensorname) (const OH_AI_ModelHandle model, const char \*tensor_name) | 通过张量名获取模型的输入张量。 |
| [OH_AI_ModelGetOutputByTensorName](_mind_spore.md#oh_ai_modelgetoutputbytensorname) (const OH_AI_ModelHandle model, const char \*tensor_name) | 通过张量名获取模型的输出张量。 |
# status.h
## 概述
提供了Mindspore Lite运行时的状态码。
**自从:**
9
**相关模块:**
[MindSpore](_mind_spore.md)
## 汇总
### 类型定义
| 类型定义名称 | 描述 |
| -------- | -------- |
| [OH_AI_Status](_mind_spore.md#oh_ai_status) | Minspore的状态码。 |
### 枚举
| 枚举名称 | 描述 |
| -------- | -------- |
| [OH_AI_CompCode](_mind_spore.md#oh_ai_compcode) { OH_AI_COMPCODE_CORE = 0x00000000u, OH_AI_COMPCODE_LITE = 0xF0000000u } | Minspore不同组件的代码。 |
| [OH_AI_Status](_mind_spore.md#oh_ai_status) {<br>OH_AI_STATUS_SUCCESS = 0, <br/>OH_AI_STATUS_CORE_FAILED = OH_AI_COMPCODE_CORE \| 0x1, <br/>OH_AI_STATUS_LITE_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -1), <br/>OH_AI_STATUS_LITE_NULLPTR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -2),<br>OH_AI_STATUS_LITE_PARAM_INVALID = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -3),<br>OH_AI_STATUS_LITE_NO_CHANGE = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -4),<br>OH_AI_STATUS_LITE_SUCCESS_EXIT = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -5),<br>OH_AI_STATUS_LITE_MEMORY_FAILED = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -6),<br>OH_AI_STATUS_LITE_NOT_SUPPORT = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -7),<br>OH_AI_STATUS_LITE_THREADPOOL_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -8),<br>OH_AI_STATUS_LITE_UNINITIALIZED_OBJ = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -9), <br>OH_AI_STATUS_LITE_OUT_OF_TENSOR_RANGE, OH_AI_STATUS_LITE_INPUT_TENSOR_ERROR,<br>OH_AI_STATUS_LITE_REENTRANT_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -102), OH_AI_STATUS_LITE_GRAPH_FILE_ERROR, <br>OH_AI_STATUS_LITE_NOT_FIND_OP = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -300),<br>OH_AI_STATUS_LITE_INVALID_OP_NAME = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -301),<br>OH_AI_STATUS_LITE_INVALID_OP_ATTR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -302), <br>OH_AI_STATUS_LITE_OP_EXECUTE_FAILURE,<br>OH_AI_STATUS_LITE_FORMAT_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -400),<br>OH_AI_STATUS_LITE_INFER_ERROR = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -500),<br>OH_AI_STATUS_LITE_INFER_INVALID = OH_AI_COMPCODE_LITE \| (0x0FFFFFFF &amp; -501),<br>OH_AI_STATUS_LITE_INPUT_PARAM_INVALID } | Minspore的状态码。 |
# tensor.h
## 概述
提供了张量相关的接口,可用于创建和修改张量信息。
**自从:**
9
**相关模块:**
[MindSpore](_mind_spore.md)
## 汇总
### 类型定义
| 类型定义名称 | 描述 |
| -------- | -------- |
| [OH_AI_TensorHandle](_mind_spore.md#oh_ai_tensorhandle) | 指向张量对象句柄。 |
### 函数
| 函数名称 | 描述 |
| -------- | -------- |
| [OH_AI_TensorCreate](_mind_spore.md#oh_ai_tensorcreate) (const char \*name, OH_AI_DataType type, const int64_t \*shape, <br/>size_t shape_num, const void \*data, size_t data_len) | 创建一个张量对象。 |
| [OH_AI_TensorDestroy](_mind_spore.md#oh_ai_tensordestroy) (OH_AI_TensorHandle \*tensor) | 释放张量对象。 |
| [OH_AI_TensorClone](_mind_spore.md#oh_ai_tensorclone) (OH_AI_TensorHandle tensor) | 深拷贝一个张量。 |
| [OH_AI_TensorSetName](_mind_spore.md#oh_ai_tensorsetname) (OH_AI_TensorHandle tensor, const char \ *name) | 设置张量的名称。 |
| [OH_AI_TensorGetName](_mind_spore.md#oh_ai_tensorgetname) (const OH_AI_TensorHandle tensor) | 获取张量的名称。 |
| [OH_AI_TensorSetDataType](_mind_spore.md#oh_ai_tensorsetdatatype) (OH_AI_TensorHandle tensor, OH_AI_DataType type) | 设置张量的数据类型。 |
| [OH_AI_TensorGetDataType](_mind_spore.md#oh_ai_tensorgetdatatype) (const OH_AI_TensorHandle tensor) | 获取张量类型。 |
| [OH_AI_TensorSetShape](_mind_spore.md#oh_ai_tensorsetshape) (OH_AI_TensorHandle tensor, <br/>const int64_t \*shape, size_t shape_num) | 设置张量的形状。 |
| [OH_AI_TensorGetShape](_mind_spore.md#oh_ai_tensorgetshape) (const OH_AI_TensorHandle tensor, size_t \*shape_num) | 获取张量的形状。 |
| [OH_AI_TensorSetFormat](_mind_spore.md#oh_ai_tensorsetformat) (OH_AI_TensorHandle tensor, OH_AI_Format format) | 设置张量数据的排列方式。 |
| [OH_AI_TensorGetFormat](_mind_spore.md#oh_ai_tensorgetformat) (const OH_AI_TensorHandle tensor) | 获取张量数据的排列方式。 |
| [OH_AI_TensorSetData](_mind_spore.md#oh_ai_tensorsetdata) (OH_AI_TensorHandle tensor, void \*data) | 设置张量的数据。 |
| [OH_AI_TensorGetData](_mind_spore.md#oh_ai_tensorgetdata) (const OH_AI_TensorHandle tensor) | 获取张量数据的指针。 |
| [OH_AI_TensorGetMutableData](_mind_spore.md#oh_ai_tensorgetmutabledata) (const OH_AI_TensorHandle tensor) | 获取可变的张量数据指针。如果数据为空则会开辟内存。 |
| [OH_AI_TensorGetElementNum](_mind_spore.md#oh_ai_tensorgetelementnum) (const OH_AI_TensorHandle tensor) | 获取张量元素数量。 |
| [OH_AI_TensorGetDataSize](_mind_spore.md#oh_ai_tensorgetdatasize) (const OH_AI_TensorHandle tensor) | 获取张量中的数据的字节数大小。 |
# types.h
## 概述
提供了MindSpore Lite支持的模型文件类型和设备类型。
**自从:**
9
**相关模块:**
[MindSpore](_mind_spore.md)
## 汇总
### 类型定义
| 类型定义名称 | 描述 |
| -------- | -------- |
| [OH_AI_ModelType](_mind_spore.md#oh_ai_modeltype) | 模型文件的类型。 |
| [OH_AI_DeviceType](_mind_spore.md#oh_ai_devicetype) | 设备类型信息,包含了目前支持的设备类型。 |
### 枚举
| 枚举名称 | 描述 |
| -------- | -------- |
| [OH_AI_ModelType](_mind_spore.md#oh_ai_modeltype) { <br/>OH_AI_MODELTYPE_MINDIR = 0, <br/>OH_AI_MODELTYPE_INVALID = 0xFFFFFFFF } | 模型文件的类型。 |
| [OH_AI_DeviceType](_mind_spore.md#oh_ai_devicetype) { <br/>OH_AI_DEVICETYPE_CPU = 0,<br/>OH_AI_DEVICETYPE_KIRIN_NPU, <br/>OH_AI_DEVICETYPE_INVALID = 100 } | 设备类型信息,包含了目前支持的设备类型。 |
...@@ -2,7 +2,8 @@ ...@@ -2,7 +2,8 @@
- 访问控制 - 访问控制
- [访问控制(权限)开发概述](accesstoken-overview.md) - [访问控制(权限)开发概述](accesstoken-overview.md)
- [访问控制(权限)开发指导](accesstoken-guidelines.md) - [访问控制授权申请指导](accesstoken-guidelines.md)
- [访问控制权限校验指导](permission-verify-guidelines.md)
- [应用权限列表](permission-list.md) - [应用权限列表](permission-list.md)
- 用户认证 - 用户认证
- [用户认证开发概述](userauth-overview.md) - [用户认证开发概述](userauth-overview.md)
...@@ -10,6 +11,9 @@ ...@@ -10,6 +11,9 @@
- 密钥管理 - 密钥管理
- [HUKS开发概述](huks-overview.md) - [HUKS开发概述](huks-overview.md)
- [HUKS开发指导](huks-guidelines.md) - [HUKS开发指导](huks-guidelines.md)
- 加密算法库框架
- [加密算法库框架概述](cryptoFramework-overview.md)
- [加密算法框架开发指导](cryptoFramework-guidelines.md)
- Hap包签名工具 - Hap包签名工具
- [Hap包签名工具概述](hapsigntool-overview.md) - [Hap包签名工具概述](hapsigntool-overview.md)
- [Hap包签名工具指导](hapsigntool-guidelines.md) - [Hap包签名工具指导](hapsigntool-guidelines.md)
# 加解密算法库框架开发指导
## 使用加解密操作
**场景说明**
使用加解密操作中,典型的场景有:
1. 使用对称密钥的加解密操作
2. 使用非对称密钥的加解密操作
**接口及参数说明**
详细接口说明可参考[API参考](../reference/apis/js-apis-cryptoFramework.md)
以上场景设计的常用接口如下表所示:
|实例名|接口名|描述|
|---|---|---|
|cryptoFramework|createCipher(transformation : string) : Cipher|根据transformation设置的算法参数创建Cipher对象|
|Cipher|init(opMode : CryptoMode, key : Key, params : ParamsSpec, callback : AsyncCallback\<void>) : void|使用callback方式设置密钥并初始化Cipher对象|
|Cipher|init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\<void>|使用Promise方式设置密钥并初始化Cipher对象|
|Cipher|update(data : DataBlob, callback : AsyncCallback\<DataBlob>) : void|使用callback方式添加加解密数据|
|Cipher|update(data : DataBlob) : Promise\<DataBlob>|使用Promise方式添加加解密数据|
|Cipher|doFinal(data : DataBlob, callback : AsyncCallback\<DataBlob>) : void|使用callback方式结束对所有数据的加解密|
|Cipher|doFinal(data : DataBlob) : Promise\<DataBlob>|使用Promise方式结束对所有数据的加解密|
**开发步骤**
示例1:使用对称密钥的加解密操作
1. 生成对称密钥生成器。
2. 通过密钥生成器生成对称密钥。
3. 生成加解密生成器。
4. 通过加解密生成器加密或解密数据。
以AES GCM以Promise方式加解密为例:
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
var globalCipher;
var globalGcmParams;
var globalKey;
var globalCipherText;
function genGcmParamsSpec() {
let arr = [0, 0, 0, 0 , 0, 0, 0, 0, 0, 0 , 0, 0]; // 12 bytes
let dataIv = new Uint8Array(arr);
let ivBlob = {data : dataIv};
arr = [0, 0, 0, 0 , 0, 0, 0, 0]; // 8 bytes
let dataAad = new Uint8Array(arr);
let aadBlob = {data : dataAad};
arr = [0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0]; // 16 bytes
let dataTag = new Uint8Array(arr);
let tagBlob = {data : dataTag};
let gcmParamsSpec = {iv : ivBlob, aad : aadBlob, authTag : tagBlob, algoName : "GcmParamsSpec"};
return gcmParamsSpec;
}
// 可理解的字符串转成字节流
function stringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
return new Uint8Array(arr);
}
// 字节流转成可理解的字符串
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
// 字节流以16进制输出
function uint8ArrayToString(array) {
let arrayString = '';
for (let i = 0; i < array.length; i++) {
arrayString += String.fromCharCode(array[i]);
}
return arrayString;
}
function genKeyMaterialBlob() {
let arr = [
0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56,
0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c,
0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes)
let keyMaterial = new Uint8Array(arr);
return {data : keyMaterial};
}
// AES GCM模式示例,自动生成密钥(promise写法)
function testAesGcm() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('testAesGcm');
}, 10)
}).then(() => {
// 生成对称密钥生成器
let symAlgoName = 'AES128';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName);
if (symKeyGenerator == null) {
console.error('createSymKeyGenerator failed');
return;
}
console.info(`symKeyGenerator algName: ${symKeyGenerator.algName}`);
// 通过密钥生成器随机生成128位长度的对称密钥
let promiseSymKey = symKeyGenerator.generateSymKey();
// 构造参数
globalGcmParams = genGcmParamsSpec();
// 生成加解密生成器
let cipherAlgoName = 'AES128|GCM|PKCS7';
try {
globalCipher = cryptoFramework.createCipher(cipherAlgoName);
console.info(`cipher algName: ${globalCipher.algName}`);
} catch (error) {
console.error(`createCipher failed, ${error.code}, ${error.message}`);
return;
}
return promiseSymKey;
}).then(key => {
let encodedKey = key.getEncoded();
console.info('key hex:' + uint8ArrayToShowStr(encodedKey.data));
globalKey = key;
return key;
}).then(key => {
// 初始化加解密操作环境:开始加密
let mode = cryptoFramework.CryptoMode.ENCRYPT_MODE;
let promiseInit = globalCipher.init(mode, key, globalGcmParams); // init
return promiseInit;
}).then(() => {
let plainText = {data : stringToUint8Array('this is test!')};
let promiseUpdate = globalCipher.update(plainText); // update
return promiseUpdate;
}).then(updateOutput => {
globalCipherText = updateOutput;
let promiseFinal = globalCipher.doFinal(null); // doFinal
return promiseFinal;
}).then(authTag => {
// 获取加密后的认证信息
globalGcmParams.authTag = authTag;
return;
}).then(() => {
// 初始化加解密操作环境:开始解密
let mode = cryptoFramework.CryptoMode.DECRYPT_MODE;
let promiseInit = globalCipher.init(mode, globalKey, globalGcmParams); // init
return promiseInit;
}).then(() => {
let promiseUpdate = globalCipher.update(globalCipherText); // update
return promiseUpdate;
}).then(updateOutput => {
console.info('decrypt plainText: ' + uint8ArrayToString(updateOutput.data));
let promiseFinal = globalCipher.doFinal(null); // doFinal
return promiseFinal;
}).then(finalOutput => {
if (finalOutput == null) {
console.info('GCM finalOutput is null');
}
}).catch(error => {
console.error(`catch error, ${error.code}, ${error.message}`);
})
}
```
以3DES ECB以callback方式加解密(采用已有数据生成密钥)为例:
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
var globalCipher;
var globalGcmParams;
var globalKey;
var globalCipherText;
// 可理解的字符串转成字节流
function stringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
return new Uint8Array(arr);
}
// 字节流转成可理解的字符串
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
// 字节流以16进制输出
function uint8ArrayToString(array) {
let arrayString = '';
for (let i = 0; i < array.length; i++) {
arrayString += String.fromCharCode(array[i]);
}
return arrayString;
}
function genKeyMaterialBlob() {
let arr = [
0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56,
0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c,
0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes)
let keyMaterial = new Uint8Array(arr);
return {data : keyMaterial};
}
// 3DES ECB模式示例,采用已有数据生成密钥(callback写法)
function test3DesEcb() {
// 生成对称密钥生成器
let symAlgoName = '3DES192';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName);
if (symKeyGenerator == null) {
console.error('createSymKeyGenerator failed');
return;
}
console.info(`symKeyGenerator algName: ${symKeyGenerator.algName}`);
// 生成加解密生成器
let cipherAlgoName = '3DES192|ECB|PKCS7';
try {
globalCipher = cryptoFramework.createCipher(cipherAlgoName);
console.info(`cipher algName: ${globalCipher.algName}`);
} catch (error) {
console.error(`createCipher failed, ${error.code}, ${error.message}`);
return;
}
// 根据指定的数据,生成对称密钥
let keyMaterialBlob = genKeyMaterialBlob();
try {
symKeyGenerator.convertKey(keyMaterialBlob, (error, key) => {
if (error) {
console.error(`convertKey error, ${error.code}, ${error.message}`);
return;
}
console.info(`key algName: ${key.algName}`);
console.info(`key format: ${key.format}`);
let encodedKey = key.getEncoded();
console.info('key getEncoded hex: ' + uint8ArrayToShowStr(encodedKey.data));
globalKey = key;
// 初始化加解密操作环境:开始加密
let mode = cryptoFramework.CryptoMode.ENCRYPT_MODE;
// init
globalCipher.init(mode, key, null, (err, ) => {
let plainText = {data : stringToUint8Array('this is test!')};
// update
globalCipher.update(plainText, (err, updateOutput) => {
globalCipherText = updateOutput;
//doFinal
globalCipher.doFinal(null, (err, finalOutput) => {
if (error) {
console.error(`doFinal error, ${error.code}, ${error.message}`);
return;
}
if (finalOutput != null) {
globalCipherText = Array.from(globalCipherText.data);
finalOutput = Array.from(finalOutput.data);
globalCipherText = globalCipherText.concat(finalOutput);
globalCipherText = new Uint8Array(globalCipherText);
globalCipherText = {data : globalCipherText};
}
// 初始化加解密操作环境:开始解密
let mode = cryptoFramework.CryptoMode.DECRYPT_MODE;
// init
globalCipher.init(mode, globalKey, null, (err, ) => {
// update
globalCipher.update(globalCipherText, (err, updateOutput) => {
console.info('decrypt plainText: ' + uint8ArrayToString(updateOutput.data));
// doFinal
globalCipher.doFinal(null, (error, finalOutput) => {
if (finalOutput != null) {
console.info("decrypt plainText:" + uint8ArrayToString(finalOutput.data));
}
})
})
})
})
})
})
})
} catch (error) {
console.error(`convertKey failed, ${error.code}, ${error.message}`);
return;
}
}
```
示例2:使用非对称密钥的加解密操作
1. 生成RSA密钥。通过createAsyKeyGenerator接口创建AsyKeyGenerator对象,并生成RSA非对称密钥。
2. 生成Cipher对象。通过createCipher接口创建Cipher对象,执行初始化操作,设置密钥及加解密模式。
3. 执行加解密操作。通过调用Cipher对象提供的doFinal接口,执行加密操作生成密文或执行解密操作生成明文。
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
let plan = "This is cipher test.";
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpArray = new Uint8Array(arr);
return tmpArray;
}
function encryptMessageProMise() {
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let cipher = cryptoFramework.createCipher("RSA1024|PKCS1");
let keyGenPromise = rsaGenerator.generateKeyPair();
keyGenPromise.then(rsaKeyPair => {
let pubKey = rsaKeyPair.pubKey;
return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null);
}).then(() => {
let input = { data : stringToUint8Array(plan) };
return cipher.doFinal(input);
}).then(dataBlob => {
console.info("EncryptOutPut is " + dataBlob.data);
});
}
function encryptMessageCallback() {
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let cipher = cryptoFramework.createCipher("RSA1024|PKCS1");
rsaGenerator.generateKeyPair(function (err, keyPair) {
let pubKey = keyPair.pubKey;
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, function (err, data) {
let input = {data : stringToUint8Array(plan) };
cipher.doFinal(input, function (err, data) {
console.info("EncryptOutPut is " + data.data);
})
})
})
}
```
## 使用签名验签操作
**场景说明**
使用签名验签操作中,典型的场景有:
1. 使用RSA签名验签操作
2. 使用ECC签名验签操作
**接口及参数说明**
详细接口说明可参考[API参考](../reference/apis/js-apis-cryptoFramework.md)
|实例名|接口名|描述|
|---|---|---|
|cryptoFramework|createSign(algName : string) : Sign|根据String设置的参数创建Sign对象|
|Sign|init(priKey : PriKey, callback : AsyncCallback\<void>) : void|使用callback方式设置密钥并初始化Sign对象|
|Sign|init(priKey : PriKey) : Promise\<void>|使用Promise方式设置密钥并初始化Sign对象|
|Sign|update(data : DataBlob, callback : AsyncCallback\<void>) : void|使用callback方式添加签名数据|
|Sign|update(data : DataBlob) : Promise\<void>|用Promise方式添加签名数据|
|Sign|sign(data : DataBlob, callback : AsyncCallback<DataBlob>) : void|使用callback方式签名所有数据|
|Sign|sign(data : DataBlob) : Promise<DataBlob>|使用Promise方式签名所有数据|
|cryptoFramework|function createVerify(algName : string) : Verify|根据String设置的参数创建Verify对象|
|Verify|init(priKey : PriKey, callback : AsyncCallback\<void>) : void|使用callback方式设置密钥并初始化Verify对象|
|Verify|init(priKey : PriKey) : Promise\<void>|使用Promise方式设置密钥并初始化Verify对象|
|Verify|update(data : DataBlob, callback : AsyncCallback\<void>) : void|使用callback方式添加验签数据|
|Verify|update(data : DataBlob) : Promise\<void>|用Promise方式添加验签数据|
|Verify|verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback<boolean>) : void|使用callback方式验签所有数据|
|Verify|verify(data : DataBlob, signatureData : DataBlob) : Promise<boolean>|使用Promise方式验签所有数据|
**开发步骤**
示例1:使用RSA签名验签操作
1. 生成RSA密钥。通过createAsyKeyGenerator接口创建AsyKeyGenerator对象,并生成RSA非对称密钥。
2. 生成Sign对象。通过createSign接口创建Sign对象,执行初始化操作并设置签名私钥。
3. 执行签名操作。通过Sign类提供的update接口,添加签名数据,并调用doFinal接口生成数据的签名。
4. 生成Verify对象。通过createVerify接口创建Verify对象,执行初始化操作并设置验签公钥。
5. 执行验签操作。通过Verify类提供的update接口,添加签名数据,并调用doFinal接口传入签名进行验签。
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpArray = new Uint8Array(arr);
return tmpArray;
}
let globalKeyPair;
let SignMessageBlob;
let plan1 = "This is Sign test plan1";
let plan2 = "This is Sign test plan1";
let input1 = { data : stringToUint8Array(plan1) };
let input2 = { data : stringToUint8Array(plan2) };
function signMessagePromise() {
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256");
let keyGenPromise = rsaGenerator.generateKeyPair();
keyGenPromise.then( keyPair => {
globalKeyPair = keyPair;
let priKey = globalKeyPair.priKey;
return signer.init(priKey);
}).then(() => {
return signer.update(input1);
}).then(() => {
return signer.sign(input2);
}).then(dataBlob => {
SignMessageBlob = dataBlob;
console.info("sign output is " + SignMessageBlob.data);
});
}
function verifyMessagePromise() {
let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256");
let verifyInitPromise = verifyer.init(globalKeyPair.pubKey);
verifyInitPromise.then(() => {
return verifyer.update(input1);
}).then(() => {
return verifyer.verify(input2, SignMessageBlob);
}).then(res => {
console.log("Verify result is " + res);
});
}
function signMessageCallback() {
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256");
rsaGenerator.generateKeyPair(function (err, keyPair) {
globalKeyPair = keyPair;
let priKey = globalKeyPair.priKey;
signer.init(priKey, function (err, data) {
signer.update(input1, function (err, data) {
signer.sign(input2, function (err, data) {
SignMessageBlob = data;
console.info("sign output is " + SignMessageBlob.data);
});
});
});
});
}
function verifyMessageCallback() {
let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA25");
verifyer.init(globalKeyPair.pubKey, function (err, data) {
verifyer.update(input1, function(err, data) {
verifyer.verify(input2, SignMessageBlob, function(err, data) {
console.info("verify result is " + data);
});
});
})
}
```
示例2:使用ECDSA操作
1. 生成ECC密钥。通过createAsyKeyGenerator接口创建AsyKeyGenerator对象,并生成ECC非对称密钥。
2. 生成Sign对象。通过createSign接口创建Sign对象,执行初始化操作并设置签名私钥。
3. 执行签名操作。通过Sign类提供的update接口,添加签名数据,并调用doFinal接口生成数据的签名。
4. 生成Verify对象。通过createVerify接口创建Verify对象,执行初始化操作并设置验签公钥。
5. 执行验签操作。通过Verify类提供的update接口,添加签名数据,并调用doFinal接口传入签名进行验签。
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpArray = new Uint8Array(arr);
return tmpArray;
}
let globalKeyPair;
let SignMessageBlob;
let plan1 = "This is Sign test plan1";
let plan2 = "This is Sign test plan1";
let input1 = { data : stringToUint8Array(plan1) };
let input2 = { data : stringToUint8Array(plan2) };
function signMessagePromise() {
let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
let signer = cryptoFramework.createSign("ECC256|SHA256");
let keyGenPromise = eccGenerator.generateKeyPair();
keyGenPromise.then( keyPair => {
globalKeyPair = keyPair;
let priKey = globalKeyPair.priKey;
return signer.init(priKey);
}).then(() => {
return signer.update(input1);
}).then(() => {
return signer.sign(input2);
}).then(dataBlob => {
SignMessageBlob = dataBlob;
console.info("sign output is " + SignMessageBlob.data);
});
}
function verifyMessagePromise() {
let verifyer = cryptoFramework.createVerify("ECC256|SHA256");
let verifyInitPromise = verifyer.init(globalKeyPair.pubKey);
verifyInitPromise.then(() => {
return verifyer.update(input1);
}).then(() => {
return verifyer.verify(input2, SignMessageBlob);
}).then(res => {
console.log("Verify result is " + res);
});
}
function signMessageCallback() {
let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
let signer = cryptoFramework.createSign("ECC256|SHA256");
eccGenerator.generateKeyPair(function (err, keyPair) {
globalKeyPair = keyPair;
let priKey = globalKeyPair.priKey;
signer.init(priKey, function (err, data) {
signer.update(input1, function (err, data) {
signer.sign(input2, function (err, data) {
SignMessageBlob = data;
console.info("sign output is " + SignMessageBlob.data);
});
});
});
});
}
function verifyMessageCallback() {
let verifyer = cryptoFramework.createVerify("ECC256|SHA256");
verifyer.init(globalKeyPair.pubKey, function (err, data) {
verifyer.update(input1, function(err, data) {
verifyer.verify(input2, SignMessageBlob, function(err, data) {
console.info("verify result is " + data);
});
});
})
}
```
## 使用摘要操作
**场景说明**
使用摘要操作的主要场景为:
用户指定摘要算法(如SHA256)生成Md实例,并输入单段或多段需要摘要的信息,进行摘要计算更新,并返回消息摘要计算结果,在指定算法后可获取当前算法名与摘要计算长度(字节)
**接口及参数说明**
详细接口说明可参考[API参考](../reference/apis/js-apis-cryptoFramework.md)
| 实例名 | 接口名 | 描述 |
| --------------- | ------------------------------------------------------------ | -------------------------------------------------- |
| cryptoFramework | function createMd(algName : string) : Md; | 指定摘要算法,生成摘要操作实例Md |
| Md | update(input : DataBlob, callback : AsyncCallback\<void\>) : void; | 接受用户输入数据,通过Callback的方式,异步更新摘要 |
| Md | update(input : DataBlob) : Promise\<void\>; | 接受用户输入数据,通过Promise的方式,异步更新摘要 |
| Md | digest(callback : AsyncCallback\<DataBlob\>) : void; | 通过Callback的方式,返回结果 |
| Md | digest() : Promise\<DataBlob\>; | 通过Promise的方式,返回结果 |
| Md | getMdLength() : number; | 获取摘要的长度(由指定的摘要算法决定) |
| Md | readonly algName : string; | 获取当前设置的摘要算法名 |
**开发步骤**
1. 设置算法,通过接口`createMd`生成摘要操作实例
2. 接受用户数据,通过接口`update`,更新摘要,此步骤可重复
3. 通过接口`digest`,返回摘要计算结果
4. 获取当前摘要算法名与摘要计算长度
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
// turn string into uint8Arr
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array;
}
// generate dataBlob with given length
function GenDataBlob(dataBlobLen) {
var dataBlob;
if (dataBlobLen == 12) {
dataBlob = {data: stringToUint8Array("my test data")};
} else {
console.error("GenDataBlob: dataBlobLen is invalid");
dataBlob = {data: stringToUint8Array("my test data")};
}
return dataBlob;
}
// md with promise async
function doMdByPromise(algName) {
var md;
try {
md = cryptoFramework.createMd(algName);
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
console.error("[Promise]: Md algName is: " + md.algName);
var promiseMdUpdate = md.update(GenDataBlob(12));
promiseMdUpdate.then(() => {
var PromiseMdDigest = md.digest();
return PromiseMdDigest;
}).then(mdOutput => {
console.error("[Promise]: MD result: " + mdOutput.data);
var mdLen = md.getMdLength();
console.error("[Promise]: MD len: " + mdLen);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
}
// md with callback async
function doMdByCallback(algName) {
var md;
try {
md = cryptoFramework.createMd(algName);
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
console.error("[Callback]: Md algName is: " + md.algName);
md.update(GenDataBlob(12), (err,) => {
if (err) {
console.error("[Callback]: err: " + err.code);
}
md.digest((err1, mdOutput) => {
if (err1) {
console.error("[Callback]: err: " + err1.code);
} else {
console.error("[Callback]: MD result: " + mdOutput.data);
var mdLen = md.getMdLength();
console.error("[Callback]: MD len: " + mdLen);
}
});
});
}
```
## 使用密钥协商操作
**场景说明**
使用签名验签操作中,典型的场景有:
使用ECDH操作。
**接口及参数说明**
详细接口说明可参考[API参考](../reference/apis/js-apis-cryptoFramework.md)
|实例名|接口名|描述|
|---|---|---|
|cryptoFramework|createKeyAgreement(algName : string) : KeyAgreement|根据String设置的参数创建KeyAgreement对象|
|KeyAgreement|generateSecret(priKey : PriKey, pubKey : PubKey, callback : AsyncCallback\<DataBlob>) : void|使用callback方式进行密钥协商|
|KeyAgreement|generateSecret(priKey : PriKey, pubKey : PubKey) : Promise\<DataBlob>|使用Promise方式进行密钥协商|
**开发步骤**
1. 生成ECC密钥。通过createAsyKeyGenerator接口创建AsyKeyGenerator对象,并生成ECC非对称密钥。
2. 基于ECC密钥的私钥及公钥执行ECDH操作。
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpArray = new Uint8Array(arr);
return tmpArray;
}
let globalKeyPair;
function ecdhPromise() {
let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
let eccKeyAgreement = cryptoFramework.createKeyAgreement("ECC256");
let keyGenPromise = eccGenerator.generateKeyPair();
keyGenPromise.then( keyPair => {
globalKeyPair = keyPair;
return eccKeyAgreement.generateSecret(keyPair.priKey, keyPair.pubKey);
}).then((secret) => {
console.info("ecdh output is " + secret.data);
}).catch((error) => {
console.error("ecdh error.");
});
}
function ecdhCallback() {
let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
let eccKeyAgreement = cryptoFramework.createKeyAgreement("ECC256");
eccGenerator.generateKeyPair(function (err, keyPair) {
globalKeyPair = keyPair;
eccKeyAgreement.generateSecret(keyPair.priKey, keyPair.pubKey, function (err, secret) {
if (err) {
console.error("ecdh error.");
return;
}
console.info("ecdh output is " + secret.data);
});
});
}
```
## 使用消息认证码操作
**场景说明**
使用消息认证码操作的主要场景为:
用户指定摘要算法(如SHA256)生成消息认证码Mac实例,输入对称密钥初始化Mac,并传入单段或多段需要摘要的信息,进行消息认证码计算,并获取消息认证码计算结果,在指定算法后可获取当前算法名与消息认证码计算长度(字节)。
**接口及参数说明**
详细接口说明可参考[API参考](../reference/apis/js-apis-cryptoFramework.md)
| 实例名 | 接口名 | 描述 |
| --------------- | ------------------------------------------------------------ | --------------------------------------------------- |
| cryptoFramework | function createMd(algName : string) : Md; | 指定摘要算法,生成消息认证码实例Mac |
| Mac | init(key : SymKey, callback : AsyncCallback\<void\>) : void; | 接收输入对称密钥,通过Callback的方式,异步初始化MAC |
| Mac | init(key : SymKey) : Promise\<void\>; | 接收输入对称密钥,通过Promise的方式,异步初始化MAC |
| Mac | update(input : DataBlob, callback : AsyncCallback\<void\>) : void; | 接受输入数据,通过Callback的方式,异步更新MAC |
| Mac | update(input : DataBlob) : Promise\<void\>; | 接受输入数据,通过Promise的方式,异步更新MAC |
| Mac | doFinal(callback : AsyncCallback\<DataBlob\>) : void; | 通过Callback的方式,返回MAC计算结果 |
| Mac | doFinal() : Promise\<DataBlob\>; | 通过Promise的方式,返回MAC计算结果 |
| Mac | getMacLength() : number; | 获取MAC的长度(由指定的摘要算法决定) |
| Mac | readonly algName : string; | 获取当前设置的摘要算法名 |
**开发步骤**
1. 设置算法,通过接口`createMac`生成消息认证码操作实例
2. 接受输入对称密钥,通过接口`init`,初始化Mac
3. 接受数据,通过接口`update`,更新Mac,此步骤可重复
4. 通过接口`doFinal`,返回Mac计算结果
5. 获取当前摘要算法名与Mac计算长度
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
// turn string into uint8Arr
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array;
}
// generate blob with this func
function GenDataBlob(dataBlobLen) {
var dataBlob;
if (dataBlobLen == 12) {
dataBlob = {data: stringToUint8Array("my test data")};
} else {
console.error("GenDataBlob: dataBlobLen is invalid");
dataBlob = {data: stringToUint8Array("my test data")};
}
return dataBlob;
}
// process by promise
function doHmacByPromise(algName) {
var mac;
try {
mac = cryptoFramework.createMac(algName);
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
console.error("[Promise]: Mac algName is: " + mac.algName);
var KeyBlob = {
data : stringToUint8Array("12345678abcdefgh")
}
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob);
promiseConvertKey.then(symKey => {
var promiseMacInit = mac.init(symKey);
return promiseMacInit;
}).then(() => {
var promiseMacUpdate = mac.update(GenDataBlob(12));
return promiseMacUpdate;
}).then(() => {
var PromiseMacDoFinal = mac.doFinal();
return PromiseMacDoFinal;
}).then(macOutput => {
console.error("[Promise]: HMAC result: " + macOutput.data);
var macLen = mac.getMacLength();
console.error("[Promise]: MAC len: " + macLen);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
}
// process by callback
function doHmacByCallback(algName) {
var mac;
try {
mac = cryptoFramework.createMac(algName);
} catch (error) {
AlertDialog.show({message: "[Callback]: error code: " + error.code + ", message is: " + error.message});
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
var KeyBlob = {
data : stringToUint8Array("12345678abcdefgh")
}
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
symKeyGenerator.convertKey(KeyBlob, (err, symKey) => {
if (err) {
console.error("[Callback]: err: " + err.code);
}
mac.init(symKey, (err1, ) => {
if (err1) {
console.error("[Callback]: err: " + err1.code);
}
mac.update(GenDataBlob(12), (err2, ) => {
if (err2) {
console.error("[Callback]: err: " + err2.code);
}
mac.doFinal((err3, macOutput) => {
if (err3) {
console.error("[Callback]: err: " + err3.code);
} else {
console.error("[Callback]: HMAC result: " + macOutput.data);
var macLen = mac.getMacLength();
console.error("[Callback]: MAC len: " + macLen);
}
});
});
});
});
}
```
## 使用随机数操作
**场景说明**
使用随机数操作的主要场景为:
- 用户生成随机数Random实例,输入随机数生成的长度(字节),生成指定长度的随机数。
- 用户使用生成的随机数作为参数,进行种子设置。
**接口及参数说明**
详细接口说明可参考[API参考](../reference/apis/js-apis-cryptoFramework.md)
| 实例名 | 接口名 | 描述 |
| --------------- | ------------------------------------------------------------ | ---------------------------------------------- |
| cryptoFramework | function createRandom() : Random; | 生成随机数Random实例 |
| Random | generateRandom(len : number, callback: AsyncCallback\<DataBlob\>) : void; | 接受输入长度,通过Callback,异步生成随机数 |
| Random | generateRandom(len : number) : Promise\<DataBlob\>; | 接受输入长度,通过Promise,异步生成随机数 |
| Random | setSeed(seed : DataBlob, callback : AsyncCallback\<void\>) : void; | 接受输入Blob,通过Callback的方式,异步设置种子 |
| Random | setSeed(seed : DataBlob) : Promise\<void\>; | 接受输入Blob,通过Promise的方式,异步设置种子 |
**开发步骤**
1. 通过接口`createRandom`生成随机数操作实例
2. 接受输入长度,通过接口`generateRandom`,生成指定长度的随机数
3. 接受DataBlob数据,通过接口`setSeed`,为随机数生成池设置种子
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
// process by promise
function doRandByPromise(len) {
var rand;
try {
rand = cryptoFramework.createRandom();
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
var promiseGenerateRand = rand.generateRandom(len);
promiseGenerateRand.then(randData => {
console.error("[Promise]: rand result: " + randData.data);
var promiseSetSeed = rand.setSeed(randData);
return promiseSetSeed;
}).then(() => {
console.error("[Promise]: setSeed success");
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
}
// process by callback
function doRandByCallback(len) {
var rand;
try {
rand = cryptoFramework.createRandom();
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
rand.generateRandom(len, (err, randData) => {
if (err) {
console.error("[Callback]: err: " + err.code);
} else {
console.error("[Callback]: generate random result: " + randData.data);
rand.setSeed(randData, (err1,) => {
if (err1) {
console.error("[Callback] err: " + err1.code);
} else {
console.error("[Callback]: setSeed success");
}
});
}
});
}
```
# 加解密算法库框架概述
加解密算法库框架是一个屏蔽了第三方密码学算法库实现差异的算法框架,提供加解密、签名验签、消息验证码、哈希、安全随机数和证书等相关功能。开发者可以通过调用加解密算法库框架,忽略底层不同三方算法库的差异,实现迅捷开发。
## 框架实现原理
加解密算法库框架提供的组件分为三层:接口层,Framework层和插件层。接口层负责对外提供统一的JS接口,插件层实现针对具体三方算法库的功能,Framework层通过灵活加载插件层的插件适配并屏蔽三方算法库差异。
## 基本概念
**对称密钥**
对称密钥使用同一个密钥对数据进行加密解密操作。即对称加密算法中,数据发送方使用加密密钥对明文进行特殊加密算法处理后,使其变成复杂的加密密文发送出去。接收方收到密文后,若想解读原文,则需要使用同一个加密密钥以及相同算法的逆算法对密文进行解密,才能使其恢复成可读明文。
- **AES加密**
AES的全称是Advanced Encryption Standard,是最常见的对称加密。AES为分组密码,分组密码也就是把明文分成一组一组的,每组长度相等,每次加密一组数据,直到加密完整个明文。在AES标准规范中,分组长度只能是128位,也就是说,每个分组为16个字节(每个字节8位)。密钥的长度可以使用128位、192位或256位。
- **3DES加密**
3DES,也称为 3DESede 或 TripleDES,是三重数据加密算法,相当于是对每个数据块应用三次DES的对称加密算法,它使用3个64位的密钥对数据块进行三次加密。相比DES,3DES因密钥长度变长,安全性有所提高,但其处理速度不高。因此又出现了AES加密算法,AES较于3DES速度更快、安全性更高。
**非对称密钥**
非对称密钥使用公钥和私钥两个密钥来进行算法操作,公钥对外公开,私钥对外保密。对于加解密操作,一般使用公钥对明文进行加密形成密文,持有私钥的人即可对密文解密形成明文。对于签名验签操作,使用私钥对明文进行签名,公钥持有者可以通过公钥对签名数据做验签,验证数据是否被篡改。
- **RSA密钥**
RSA密钥以极大整数做因数分解的数学难题作为密钥安全性的基石。生成密钥时,首先需要随机出两个大素数p和q,计算n = p * q并将n做为模,再选择一个大于1且小于(p - 1) * (q - 1)的整数e,确保e与(p - 1)*(q - 1)互素,最后计算d,使得e * d - 1为(p - 1)和(q - 1)的倍数,则可得到公钥(n, e)和私钥(n, d)。
算法库框架除提供了默认的双素数RSA密钥生成外,还提供了多素数密钥生成方式,可以在密钥生成时通过指定primes参数(PRIMES_2, PRIMES_3, PRIMES_4, PRIMES_5)指定素数个数。多素数密钥的优点是可以减少解密、签名的计算量(中国剩余定理),但相对的劣势是密钥强度会越低,算法库依据OpenSSL的素数使用规则制定了相应规格,具体将在**约束与限制**章节中说明。
- **ECC密钥**
ECC是一种基于椭圆曲线数学的公开密钥加密算法,其数学基础是利用椭圆曲线上的有理点构成Abel加法群上椭圆离散对数的计算困难性,算法库框架提供了多种椭圆曲线的ECC密钥生成能力。
**加解密**
- **对称AES加解密**
算法库目前提供了AES加解密常用的7种加密模式:ECB、CBC、OFB、CFB、CTR、GCM和CCM。AES为分组加密算法,分组长度大小为128位。实际应用中明文最后一组可能不足128位,不足数据可以使用各种padding模式做数据填充。下文中描述了各个padding的区别:
- NoPadding:不带填充;
- PKCS5:填充字符由一个字节序列组成,每个字节填充该填充字节序列的长度,规定是8字节填充;
- PKCS7:填充字符和PKCS5填充方法一致,但是可以在1-255字节之间任意填充;
> **说明:** ECB、CBC加密模式,明文长度不是128位整数倍,必须使用填充方法补足;
- **对称3DES加解密**
该算法的加解密过程分别是对明文/密文数据进行三次DES加密或解密,得到相应的密文或明文。
算法库目前提供了3DES加解密常用的4种加密模式:ECB、CBC、OFB和CFB。DES为分组加密算法,分组长度大小为64位。实际应用中明文最后一组可能不足64位,不足数据可以使用各种padding模式做数据填充。下文中描述了各个padding的区别:
- NoPadding:不带填充;
- PKCS5:填充字符由一个字节序列组成,每个字节填充该填充字节序列的长度,规定是8字节填充;
- PKCS7:填充字符和PKCS5填充方法一致,但是可以在1-255字节之间任意填充;
> **说明:** ECB、CBC加密模式,明文长度不是64位整数倍,必须使用填充方法补足
- **非对称RSA加解密**
当持有RSA公钥(n, e)和私钥(n, d)后,RSA加密过程为:密文 = 明文 ^ e mod n, 解密过程为:明文 = 密文 ^ d mod n。算法库目前提供了RSA加解密常用的三种模式:PKCS1、PKCS1_OAEP和NoPadding。RSA为块加密算法,加密长度需要在固定长度进行,实际应用中会使用各种padding模式做数据填充。下文中描述了各个padding的区别:
- NoPadding:不带填充,输入的数据必须与RSA钥模一样长,输出数据长度与RSA钥模一样长;
- PKCS1:pkcs1padding V1.5是RSA加解密默认的填充方式,输入的数据必须<=RSA钥模-11,输出数据长度与RSA钥模一样长;
- PKCS1_OAEP:RSA_PKCS1_OAEP_PADDING填充模式是PKCS#1推出的新填充方式,此模式需要设置两个摘要(md和mgf1_md),输入的数据必须小于RSA钥模 - md摘要长度 - mgf1_md摘要长度 - 2,输出数据长度与RSA钥模一样长;<br/>
**补充说明:** RSA钥模 = (RSA的bits + 7) / 8
**签名验签**
- **RSA签名验签**
当持有RSA公钥(n, e)和私钥(n, d)后,RSA签名生成过程为:签名 = 消息 ^ d mod n, 验签过程为:消息 = 签名 ^ d mod n。消息发送方发送数据时,同时发送消息和私钥签名后的签名信息,消息接收方接受到数据后,将签名信息用公钥解密并验证消息是否一致。因发送的消息长度大多大于RSA钥模,因此算法库框架提供了两种padding模式,通过摘要提取消息的散列值再做签名。算法库框架中提供了签名验签相关的两种模式:PKCS1和PSS。下问对两种模式做详细描述:
- PKCS1: pkcs1padding V1.5是RSA加解密默认的填充方式,使用该模式时需要设置摘要(md);
- PSS: PSS模式是RSA 算法的基础上叠加上一种填充算法,使用该签名算法时需要使用摘要(md)和掩码函数(mgf1_md);
- **ECDSA**
椭圆曲线数字签名算法(ECDSA)是基于椭圆曲线密码(ECC)模拟数字签名算法(DSA)。相比普通的离散对数问题(DLP)和大数分解问题(IFP),椭圆曲线密码的单位比特强度要高于其他公钥体制。算法库框架提供了多种椭圆曲线及摘要算法组合的椭圆曲线数字签名算法(ECDSA)能力。
**密钥协商**
- **ECDH**
ECDH的全称是椭圆曲线迪菲-赫尔曼秘钥交换,是用来在一个非安全通道中建立起安全的共有加密资料,交换双方可以在不共享任何秘密的情况下协商出一个密钥。算法库框架基于开源算法库提供了多种椭圆曲线的ECDH能力。
**摘要**
消息摘要MD算法是一种能将任意长度的输入消息,通过哈希算法生成长度固定的摘要的算法。消息摘要算法通过其不可逆的特性能被用于敏感信息的加密。消息摘要算法也被称为哈希算法或单向散列算法。
在摘要算法相同时,生成的摘要值主要有下列特点:
- 当输入消息相同时,生成摘要序列相同;
- 当输入消息的长度不一致时,生成摘要序列长度固定(摘要长度由算法决定);
- 当输入消息不一致时,生成摘要序列几乎不会相同(依然存在相同概率,由摘要长度决定相同概率);
消息摘要算法主要分为三类:MD,SHA与MAC(详见HMAC章节)
MD算法包括MD2,MD4和MD5。
SHA算法主要包括SHA1,SHA224,SHA256,SHA384,SHA512。
**消息验证码**
HMAC(Hash-based Message Authentication Code)是一种基于密钥的消息认证码算法。HMAC通过指定摘要算法,以通信双方共享密钥与消息作为输入,生成消息认证码用于检验传递报文的完整性,HMAC生成的消息认证码为固定长度。HMAC在消息摘要算法的基础上增加了密钥的输入,确保了信息的正确性。
**随机数**
随机数在加解密过程中主要用于临时会话密钥的生成与非对称加密算法中密钥的生成。随机数由硬件生成的硬件随机数生成器或由软件生成的伪随机数生成器进行生成。在加解密的场景中,安全随机数生成器需要具备随机性,不可预测性,与不可重现性。密码学安全伪随机数生成器CSPRNG(Cryptography Secure Random Number Generators)生成的随机数满足密码学安全伪随机性
- **内部状态**代表随机数生成器内存中的数值,当内部状态相同时,随机数生成器会生成固定的随机数序列
- **种子**(seed)是一个用来对伪随机数的内部状态进行初始化的数据,随机数生成器通过种子来生成一系列的随机序列。
**证书**
数字证书提供了一种数字验证用户、设备、业务身份的方式。X509证书是国际定制的标准格式。加解密算法库框架部件提供X509证书、X509证书吊销列表、证书链校验器相关的功能。
- X509证书:提供X509证书的解析、序列化、X509证书签名验证、证书相关的信息查询等功能
- X509证书吊销列表:提供X509证书吊销列表的解析、序列化、信息查询等功能
- 证书链校验器:提供证书链校验(不包括证书有效期的校验)、证书链算法名称查询的功能
## 约束与限制
- 算法库框架不支持多线程并发操作。
### 密钥生成规格
**对称密钥生成规格**
支持的对称密钥生成参数:
|对称密钥算法|密钥长度|生成密钥的字符串参数|
|---|---|---|
|3DES|192|3DES192|
|AES|128|AES128|
|AES|192|AES192|
|AES|256|AES256|
**非对称密钥生成规格**
- **RSA密钥生成**
支持的非对称密钥生成参数:
|非对称密钥算法|密钥长度|素数个数|生成密钥的字符串参数|
|---|---|---|---|
|RSA|512|2|RSA512\|PRIMES_2|
|RSA|768|2|RSA768\|PRIMES_2|
|RSA|1024|2|RSA1024\|PRIMES_2|
|RSA|1024|3|RSA1024\|PRIMES_3|
|RSA|2048|2|RSA2048\|PRIMES_2|
|RSA|2048|3|RSA2048\|PRIMES_3|
|RSA|3072|2|RSA3072\|PRIMES_2|
|RSA|3072|3|RSA3072\|PRIMES_3|
|RSA|4096|2|RSA4096\|PRIMES_2|
|RSA|4096|3|RSA4096\|PRIMES_3|
|RSA|4096|4|RSA4096\|PRIMES_4|
|RSA|8192|2|RSA8192\|PRIMES_2|
|RSA|8192|3|RSA8192\|PRIMES_3|
|RSA|8192|4|RSA8192\|PRIMES_4|
|RSA|8192|5|RSA8192\|PRIMES_5|
> **说明**:生成RSA非对称密钥时,默认素数为2,PRIMES_2参数可省略。
- **ECC密钥生成**
支持的非对称密钥生成参数:
|非对称密钥算法|密钥长度|
|---|---|
|ECC|ECC224|
|ECC|ECC256|
|ECC|ECC384|
|ECC|ECC512|
### 加解密规格
**对称加解密**
支持的对称加密算法:
|对称加解密算法|分组模式|指定算法名称字符串|
|---|---|---|
|3DES|ECB|3DES192\|ECB\|[NoPadding\|PKCS5\|PKCS7]|
|3DES|CBC|3DES192\|CBC\|[NoPadding\|PKCS5\|PKCS7]|
|3DES|OFB|3DES192\|OFB\|[NoPadding\|PKCS5\|PKCS7]|
|3DES|CFB|3DES192\|CFB\|[NoPadding\|PKCS5\|PKCS7]|
|AES|ECB|AES[128\|192\|256]\|ECB\|[NoPadding\|PKCS5\|PKCS7]|
|AES|CBC|AES[128\|192\|256]\|CBC\|[NoPadding\|PKCS5\|PKCS7]|
|AES|CTR|AES[128\|192\|256]\|CTR\|[NoPadding\|PKCS5\|PKCS7]|
|AES|OFB|AES[128\|192\|256]\|OFB\|[NoPadding\|PKCS5\|PKCS7]|
|AES|CFB|AES[128\|192\|256]\|CFB\|[NoPadding\|PKCS5\|PKCS7]|
|AES|GCM|AES[128\|192\|256]\|GCM\|[NoPadding\|PKCS5\|PKCS7]|
|AES|CCM|AES[128\|192\|256]\|CCM\|[NoPadding\|PKCS5\|PKCS7]|
> **说明:** []中只能任选一项
**非对称RSA加解密**
RSA加解密时,涉及三种加解密模式:NoPadding, PKCS1和PKCS1_OAEP。
- 使用NoPadding模式时可以指定的参数: [RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|NoPadding
- 使用PKCS1模式时可以指定的参数: [RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|PKCS1
- 使用PKCS1_OAEP模式时可以指定的参数:[RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|PKCS1_OAEP|[MD5|SHA1|SHA224|SHA256|SHA384|SHA512]|[MGF1_MD5|MGF1_SHA1|MGF1_SHA224|MGF1_SHA256|MGF1_SHA384|MGF1_SHA512]
> **说明:** []内的参数只能任选一项,非[]内的为固定值
### 签名验签规格
**RSA签名验签**
RSA签名验签时,涉及三种加解密模式:PKCS1和PSS。
- 使用PKCS1模式时可以指定的参数: [RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|PKCS1|[MD5|SHA1|SHA224|SHA256|SHA384|SHA512]
- 使用PSS模式时可以指定的参数:[RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|PSS|[MD5|SHA1|SHA224|SHA256|SHA384|SHA512]|[MGF1_MD5|MGF1_SHA1|MGF1_SHA224|MGF1_SHA256|MGF1_SHA384|MGF1_SHA512]
> **说明:** []内的参数只能任选一项,非[]内的为固定值
**ECDSA签名验签**
支持的ECDSA参数:
|非对称密钥算法|支持种类|
|---|---|
|ECC|ECC224|
|ECC|ECC256|
|ECC|ECC384|
|ECC|ECC512|
|摘要算法|支持种类|
|---|---|
|HASH|SHA1|
|HASH|SHA224|
|HASH|SHA256|
|HASH|SHA384|
|HASH|SHA512|
### 密钥协商规格
**ECDH**
支持的ECDH参数:
|非对称密钥算法|支持种类|
|---|---|
|ECC|ECC224|
|ECC|ECC256|
|ECC|ECC384|
|ECC|ECC512|
### MD算法规格
加解密算法库框架当前支持MD5算法
### SHA算法规格
加解密算法库框架当前支持:SHA1,SHA224,SHA256,SHA384,SHA512
### 证书规格
- **证书链校验**<br/>
由于端侧系统时间不可信,证书链校验不包含对证书有效时间的校验。如果需要检查证书的时间有效性,可使用X509证书的checkValidityWithDate()方法进行检查。
- **证书格式**
目前支持DER与PEM格式的证书。
...@@ -25,8 +25,10 @@ ...@@ -25,8 +25,10 @@
font-size: 50px; font-size: 50px;
margin-top: 40px; margin-top: 40px;
margin-bottom: 20px; margin-bottom: 20px;
font-weight: 700;
} }
.paragraph-text { .paragraph-text {
width: 95%;
color: #000000; color: #000000;
font-size: 35px; font-size: 35px;
line-height: 60px; line-height: 60px;
...@@ -38,9 +40,11 @@ ...@@ -38,9 +40,11 @@
// xxx.js // xxx.js
export default { export default {
data: { data: {
headTitle: 'Capture the Beauty in This Moment', headTitle: 'Capture the Beauty in Moment',
paragraphFirst: 'Capture the beauty of light during the transition and fusion of ice and water. At the instant of movement and stillness, softness and rigidity, force and beauty, condensing moving moments.', paragraphFirst: 'Capture the beauty of light during the transition and fusion of ice and water. At the instant of movement and stillness, softness and rigidity, force and beauty, condensing moving moments.',
paragraphSecond: 'Reflecting the purity of nature, the innovative design upgrades your visual entertainment and ergonomic comfort. Effortlessly capture what you see and let it speak for what you feel.', paragraphSecond: 'Reflecting the purity of nature, the innovative design upgrades your visual entertainment and ergonomic comfort. Effortlessly capture what you see and let it speak for what you feel.',
}, },
} }
``` ```
![zh-cn_image_0000001118642600](figures/zh-cn_image_0000001118642600.PNG)
\ No newline at end of file
...@@ -108,9 +108,9 @@ export default { ...@@ -108,9 +108,9 @@ export default {
![zh-cn_image_0000001227135613](figures/zh-cn_image_0000001227135613.gif) ![zh-cn_image_0000001227135613](figures/zh-cn_image_0000001227135613.gif)
## 添加grild-col ## 添加grid-col
创建grid-container组件并添加grid-row,在grid-row组件内添加grild-col组件形成布局。 创建grid-container组件并添加grid-row,在grid-row组件内添加grid-col组件形成布局。
```html ```html
......
# OffscreenCanvasRenderingContext2D对象 # OffscreenCanvasRenderingContext2D对象
使用OffscreenCanvas在离屏Canvas画布组件上进行绘制,绘制对象可以是矩形、文本、图片等。具体请参考[OffscreenCanvasRenderingContext2D对象](../reference/arkui-js/js-offscreencanvasrenderingcontext2d.md) 使用OffscreenCanvas在离屏Canvas画布组件上进行绘制,绘制对象可以是矩形、文本、图片等。 离屏,即GPU在当前缓冲区以外新开辟的一个缓冲区。 具体请参考[OffscreenCanvasRenderingContext2D对象](../reference/arkui-js/js-offscreencanvasrenderingcontext2d.md)
以下示例创建了一个OffscreenCanvas画布,再在画布上创建一个getContext2d对象,并设置filter属性改变图片样式。 以下示例创建了一个OffscreenCanvas画布,再在画布上创建一个getContext2d对象,并设置filter属性改变图片样式。
......
...@@ -37,13 +37,12 @@ ...@@ -37,13 +37,12 @@
- [测试框架使用指导](ability/ability-delegator.md) - [测试框架使用指导](ability/ability-delegator.md)
- UI开发 - UI开发
- [方舟开发框架(ArkUI)概述](ui/arkui-overview.md) - [方舟开发框架(ArkUI)概述](ui/arkui-overview.md)
- 基于TS扩展的声明式开发范式 - 基于eTS的声明式开发范式
- [概述](ui/ui-ts-overview.md) - [概述](ui/ui-ts-overview.md)
- 框架说明 - 框架说明
- 文件组织 - 文件组织
- [目录结构](ui/ts-framework-directory.md) - [目录结构](ui/ts-framework-directory.md)
- [应用代码文件访问规则](ui/ts-framework-file-access-rules.md) - [应用代码文件访问规则](ui/ts-framework-file-access-rules.md)
- [js标签配置](ui/ts-framework-js-tag.md)
- 资源管理 - 资源管理
- [资源文件的分类](ui/ui-ts-basic-resource-file-categories.md) - [资源文件的分类](ui/ui-ts-basic-resource-file-categories.md)
- [资源访问](ui/ts-resource-access.md) - [资源访问](ui/ts-resource-access.md)
...@@ -108,7 +107,7 @@ ...@@ -108,7 +107,7 @@
- [构建食物分类Grid布局](ui/ui-ts-building-category-grid-layout.md) - [构建食物分类Grid布局](ui/ui-ts-building-category-grid-layout.md)
- [页面跳转与数据传递](ui/ui-ts-page-redirection-data-transmission.md) - [页面跳转与数据传递](ui/ui-ts-page-redirection-data-transmission.md)
- [性能提升的推荐方法](ui/ts-performance-improvement-recommendation.md) - [性能提升的推荐方法](ui/ts-performance-improvement-recommendation.md)
- 基于JS扩展的类Web开发范式 - 兼容JS的类Web开发范式
- [概述](ui/ui-js-overview.md) - [概述](ui/ui-js-overview.md)
- 框架说明 - 框架说明
- [文件组织](ui/js-framework-file.md) - [文件组织](ui/js-framework-file.md)
...@@ -202,6 +201,7 @@ ...@@ -202,6 +201,7 @@
- [音频播放开发指导](media/audio-playback.md) - [音频播放开发指导](media/audio-playback.md)
- [音频录制开发指导](media/audio-recorder.md) - [音频录制开发指导](media/audio-recorder.md)
- [音频渲染开发指导](media/audio-renderer.md) - [音频渲染开发指导](media/audio-renderer.md)
- [音频流管理开发指导](media/audio-stream-manager.md)
- [音频采集开发指导](media/audio-capturer.md) - [音频采集开发指导](media/audio-capturer.md)
- [OpenSL ES播放开发指导](media/opensles-playback.md) - [OpenSL ES播放开发指导](media/opensles-playback.md)
- [OpenSL ES录音开发指导](media/opensles-capture.md) - [OpenSL ES录音开发指导](media/opensles-capture.md)
...@@ -213,10 +213,12 @@ ...@@ -213,10 +213,12 @@
- [图片开发指导](media/image.md) - [图片开发指导](media/image.md)
- 相机 - 相机
- [相机开发指导](media/camera.md) - [相机开发指导](media/camera.md)
- [分布式相机开发指导](media/remote-camera.md)
- 安全 - 安全
- 访问控制 - 访问控制
- [访问控制开发概述](security/accesstoken-overview.md) - [访问控制开发概述](security/accesstoken-overview.md)
- [访问控制开发指导](security/accesstoken-guidelines.md) - [访问控制授权申请指导](security/accesstoken-guidelines.md)
- [访问控制权限校验指导](security/permission-verify-guidelines.md)
- [权限定义列表](security/permission-list.md) - [权限定义列表](security/permission-list.md)
- 用户认证 - 用户认证
- [用户认证开发概述](security/userauth-overview.md) - [用户认证开发概述](security/userauth-overview.md)
...@@ -301,78 +303,66 @@ ...@@ -301,78 +303,66 @@
- [Intl开发指导](internationalization/intl-guidelines.md) - [Intl开发指导](internationalization/intl-guidelines.md)
- [I18n开发指导](internationalization/i18n-guidelines.md) - [I18n开发指导](internationalization/i18n-guidelines.md)
- 一次开发,多端部署 - 一次开发,多端部署
- [前言](key-features/multi-device-app-dev/about-this-document.md) - [前言](key-features/multi-device-app-dev/foreword.md)
- [简介](key-features/multi-device-app-dev/introduction.md) - [简介](key-features/multi-device-app-dev/introduction.md)
- [从一个例子开始](key-features/multi-device-app-dev/start-with-a-example.md)
- 应用UX设计 - 应用UX设计
- [设计原则和要点](key-features/multi-device-app-dev/design-principles.md) - [设计原则和要点](key-features/multi-device-app-dev/design-principles.md)
- 应用架构设计 - 应用架构设计
- [应用导航结构设计要求](key-features/multi-device-app-dev/navigation-design.md) - [应用导航结构设计要求](key-features/multi-device-app-dev/navigation-design.md)
- [应用页面结构设计](key-features/multi-device-app-dev/page-design.md) - [应用页面结构设计](key-features/multi-device-app-dev/page-design.md)
- 界面布局 - 界面布局
- [概述](key-features/multi-device-app-dev/layout-design-intro.md) - [概述](key-features/multi-device-app-dev/interface-layout-design-intro.md)
- 布局基础 - 布局基础
- [栅格系统](key-features/multi-device-app-dev/layout-grid.md) - [栅格系统](key-features/multi-device-app-dev/design-grid.md)
- [自适应布局](key-features/multi-device-app-dev/layout-adaptive.md) - [自适应布局](key-features/multi-device-app-dev/design-adaptive-layout.md)
- [响应式布局](key-features/multi-device-app-dev/layout-responsive.md) - [响应式布局](key-features/multi-device-app-dev/design-responsive-layout.md)
- [布局基础运用案例](key-features/multi-device-app-dev/layout-design-cases.md) - [布局基础运用案例](key-features/multi-device-app-dev/design-layout-cases.md)
- 人机交互 - 人机交互
- [交互基础](key-features/multi-device-app-dev/interaction-basics.md) - [交互基础](key-features/multi-device-app-dev/interaction-basics.md)
- [常见输入方式](key-features/multi-device-app-dev/common-input-modes.md) - [常见输入方式](key-features/multi-device-app-dev/common-input-modes.md)
- [交互事件归一](key-features/multi-device-app-dev/design-interaction-events-unification.md) - [交互事件归一](key-features/multi-device-app-dev/design-interaction-event-normalization.md)
- 视觉风格 - 视觉风格
- [视觉基础](key-features/multi-device-app-dev/visual-style-basics.md) - [视觉基础](key-features/multi-device-app-dev/visual-basics.md)
- [色彩](key-features/multi-device-app-dev/visual-style-color.md) - [色彩](key-features/multi-device-app-dev/visual-style-color.md)
- [字体](key-features/multi-device-app-dev/visual-style-font.md) - [字体](key-features/multi-device-app-dev/visual-style-font.md)
- [图标](key-features/multi-device-app-dev/visual-style-icon.md) - [图标](key-features/multi-device-app-dev/visual-style-icon.md)
- [多态控件](key-features/multi-device-app-dev/design-polymorphic-components.md) - [多态控件](key-features/multi-device-app-dev/design-polymorphic-controls.md)
- [设计自检表](key-features/multi-device-app-dev/design-checklist.md) - [设计自检表](key-features/multi-device-app-dev/design-checklist.md)
- [资源](key-features/multi-device-app-dev/resource.md) - [设计交付](key-features/multi-device-app-dev/design-delivery.md)
- [IDE使用](key-features/multi-device-app-dev/ide-usage.md) - [资源](key-features/multi-device-app-dev/design-resources.md)
- 一多能力的页面开发介绍 - [工程管理](key-features/multi-device-app-dev/ide-using.md)
- 布局能力 - 页面开发的一多能力介绍
- [布局能力简介](key-features/multi-device-app-dev/layout-intro.md) - [简介](key-features/multi-device-app-dev/page-development-intro.md)
- 自适应布局 - 布局能力
- [自适应布局简介](key-features/multi-device-app-dev/adaptive-layout-intro.md) - [布局简介](key-features/multi-device-app-dev/layout-intro.md)
- [拉伸能力](key-features/multi-device-app-dev/adaptive-layout-stretching.md) - [自适应布局](key-features/multi-device-app-dev/adaptive-layout.md)
- [均分能力](key-features/multi-device-app-dev/adaptive-layout-equalization.md) - [响应式布局](key-features/multi-device-app-dev/responsive-layout.md)
- [占比能力](key-features/multi-device-app-dev/adaptive-layout-proportion.md) - [典型布局场景](key-features/multi-device-app-dev/typical-layout-scenario.md)
- [缩放能力](key-features/multi-device-app-dev/adaptive-layout-scaling.md) - 典型页面场景
- [延伸能力](key-features/multi-device-app-dev/adaptive-layout-extension.md) - [应用市场首页](key-features/multi-device-app-dev/appgallery-home-page.md)
- [隐藏能力](key-features/multi-device-app-dev/adaptive-layout-hiding.md) - [音乐专辑页](key-features/multi-device-app-dev/music-album-page.md)
- [折行能力](key-features/multi-device-app-dev/adaptive-layout-wrapping.md) - [交互归一](key-features/multi-device-app-dev/interaction-event-normalization.md)
- 响应式布局 - [多态组件](key-features/multi-device-app-dev/polymorphic-controls.md)
- [栅格断点系统](key-features/multi-device-app-dev/grid-breakpoint.md) - [资源使用](key-features/multi-device-app-dev/resource-usage.md)
- [媒体查询](key-features/multi-device-app-dev/media-query.md) - [功能开发的一多能力介绍](key-features/multi-device-app-dev/development-intro.md)
- [典型场景](key-features/multi-device-app-dev/responsive-layout-cases.md) - [案例应用](key-features/multi-device-app-dev/case.md)
- [交互归一](key-features/multi-device-app-dev/interaction-events-unification.md) - [常见问题](key-features/multi-device-app-dev/faq.md)
- [多态组件](key-features/multi-device-app-dev/polymorphic-components.md)
- [资源使用](key-features/multi-device-app-dev/resource-usage.md)
- [一多能力的功能开发介绍](key-features/multi-device-app-dev/development-intro.md)
- 案例应用
- 短信应用
- [概览](key-features/multi-device-app-dev/sms-intro.md)
- 会话详情页面
- [页面结构](key-features/multi-device-app-dev/sms-session-page-structure.md)
- [顶部标题栏](key-features/multi-device-app-dev/sms-session-page-title-bar.md)
- [底部输入栏](key-features/multi-device-app-dev/sms-session-page-input-field.md)
- [信息列表](key-features/multi-device-app-dev/sms-session-page-message-list.md)
- [组合成型](key-features/multi-device-app-dev/sms-session-page-combined.md)
- [总结](key-features/multi-device-app-dev/sms-session-summary.md)
- [桌面应用](key-features/multi-device-app-dev/cases-home-screen.md)
- [常见问题](key-features/multi-device-app-dev/faqs.md)
- [IDL工具规格及使用说明书](IDL/idl-guidelines.md) - [IDL工具规格及使用说明书](IDL/idl-guidelines.md)
- Native API的相关指导 - Native API的相关指导
- [Native API在应用工程中的使用指导](napi/napi-guidelines.md) - [Native API在应用工程中的使用指导](napi/napi-guidelines.md)
- [Drawing开发指导](napi/drawing-guidelines.md) - [Drawing开发指导](napi/drawing-guidelines.md)
- [Rawfile开发指导](napi/rawfile-guidelines.md) - [Rawfile开发指导](napi/rawfile-guidelines.md)
- [Window开发指导](napi/native-window-guidelines.md) - [Window开发指导](napi/native-window-guidelines.md)
- [使用MindSpore Lite引擎进行模型推理](napi/mindspore-lite-guidelines.md)
- 工具 - 工具
- [DevEco Studio(OpenHarmony)使用指南](quick-start/deveco-studio-user-guide-for-openharmony.md) - [DevEco Studio(OpenHarmony)使用指南](quick-start/deveco-studio-user-guide-for-openharmony.md)
- 示例教程 - 示例教程
- [示例代码](https://gitee.com/openharmony/applications_app_samples/blob/master/README_zh.md) - [示例代码](https://gitee.com/openharmony/applications_app_samples/blob/master/README_zh.md)
- [Codelabs](https://gitee.com/openharmony/codelabs/blob/master/README.md) - [Codelabs](https://gitee.com/openharmony/codelabs/blob/master/README.md)
- API参考 - API参考
- 组件参考(基于TS扩展的声明式开发范式) - [Syscap列表](reference/syscap-list.md)
- 组件参考(基于eTS的声明式开发范式)
- 组件通用信息 - 组件通用信息
- 通用事件 - 通用事件
- [点击事件](reference/arkui-ts/ts-universal-events-click.md) - [点击事件](reference/arkui-ts/ts-universal-events-click.md)
...@@ -412,6 +402,8 @@ ...@@ -412,6 +402,8 @@
- [触摸热区设置](reference/arkui-ts/ts-universal-attributes-touch-target.md) - [触摸热区设置](reference/arkui-ts/ts-universal-attributes-touch-target.md)
- [多态样式](reference/arkui-ts/ts-universal-attributes-polymorphic-style.md) - [多态样式](reference/arkui-ts/ts-universal-attributes-polymorphic-style.md)
- [触摸测试控制](reference/arkui-ts/ts-universal-attributes-hit-test-behavior.md) - [触摸测试控制](reference/arkui-ts/ts-universal-attributes-hit-test-behavior.md)
- [背景模糊设置](reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md)
- [分布式迁移标识](reference/arkui-ts/ts-universal-attributes-restoreId.md)
- 手势处理 - 手势处理
- [绑定手势方法](reference/arkui-ts/ts-gesture-settings.md) - [绑定手势方法](reference/arkui-ts/ts-gesture-settings.md)
- 基础手势 - 基础手势
...@@ -470,10 +462,13 @@ ...@@ -470,10 +462,13 @@
- [Counter](reference/arkui-ts/ts-container-counter.md) - [Counter](reference/arkui-ts/ts-container-counter.md)
- [Flex](reference/arkui-ts/ts-container-flex.md) - [Flex](reference/arkui-ts/ts-container-flex.md)
- [GridContainer](reference/arkui-ts/ts-container-gridcontainer.md) - [GridContainer](reference/arkui-ts/ts-container-gridcontainer.md)
- [GridCol](reference/arkui-ts/ts-container-gridcol.md)
- [GridRow](reference/arkui-ts/ts-container-gridrow.md)
- [Grid](reference/arkui-ts/ts-container-grid.md) - [Grid](reference/arkui-ts/ts-container-grid.md)
- [GridItem](reference/arkui-ts/ts-container-griditem.md) - [GridItem](reference/arkui-ts/ts-container-griditem.md)
- [List](reference/arkui-ts/ts-container-list.md) - [List](reference/arkui-ts/ts-container-list.md)
- [ListItem](reference/arkui-ts/ts-container-listitem.md) - [ListItem](reference/arkui-ts/ts-container-listitem.md)
- [ListItemGroup](reference/arkui-ts/ts-container-listitemgroup.md)
- [Navigator](reference/arkui-ts/ts-container-navigator.md) - [Navigator](reference/arkui-ts/ts-container-navigator.md)
- [Panel](reference/arkui-ts/ts-container-panel.md) - [Panel](reference/arkui-ts/ts-container-panel.md)
- [Refresh](reference/arkui-ts/ts-container-refresh.md) - [Refresh](reference/arkui-ts/ts-container-refresh.md)
...@@ -527,7 +522,7 @@ ...@@ -527,7 +522,7 @@
- [菜单](reference/arkui-ts/ts-methods-menu.md) - [菜单](reference/arkui-ts/ts-methods-menu.md)
- [枚举说明](reference/arkui-ts/ts-appendix-enums.md) - [枚举说明](reference/arkui-ts/ts-appendix-enums.md)
- [类型说明](reference/arkui-ts/ts-types.md) - [类型说明](reference/arkui-ts/ts-types.md)
- 组件参考(基于JS扩展的类Web开发范式) - 组件参考(兼容JS的类Web开发范式)
- 组件通用信息 - 组件通用信息
- [通用属性](reference/arkui-js/js-components-common-attributes.md) - [通用属性](reference/arkui-js/js-components-common-attributes.md)
- [通用样式](reference/arkui-js/js-components-common-styles.md) - [通用样式](reference/arkui-js/js-components-common-styles.md)
...@@ -727,6 +722,7 @@ ...@@ -727,6 +722,7 @@
- [ExtensionRunningInfo (ExtensionRunningInfo)](reference/apis/js-apis-extensionrunninginfo.md) - [ExtensionRunningInfo (ExtensionRunningInfo)](reference/apis/js-apis-extensionrunninginfo.md)
- [MissionSnapshot (MissionSnapshot)](reference/apis/js-apis-application-MissionSnapshot.md) - [MissionSnapshot (MissionSnapshot)](reference/apis/js-apis-application-MissionSnapshot.md)
- [ProcessRunningInfo (ProcessRunningInfo)](reference/apis/js-apis-processrunninginfo.md) - [ProcessRunningInfo (ProcessRunningInfo)](reference/apis/js-apis-processrunninginfo.md)
- [ProcessRunningInformation (ProcessRunningInformation)](reference/apis/js-apis-processrunninginformation.md)
- [shellCmdResult (ShellCmdResult)](reference/apis/js-apis-application-shellCmdResult.md) - [shellCmdResult (ShellCmdResult)](reference/apis/js-apis-application-shellCmdResult.md)
- [ContinuationResult (ContinuationResult)](reference/apis/js-apis-continuation-continuationResult.md) - [ContinuationResult (ContinuationResult)](reference/apis/js-apis-continuation-continuationResult.md)
- 公共事件与通知 - 公共事件与通知
...@@ -746,6 +742,7 @@ ...@@ -746,6 +742,7 @@
- [ApplicationInfo (ApplicationInfo)](reference/apis/js-apis-bundle-ApplicationInfo.md) - [ApplicationInfo (ApplicationInfo)](reference/apis/js-apis-bundle-ApplicationInfo.md)
- [BundleInfo (BundleInfo)](reference/apis/js-apis-bundle-BundleInfo.md) - [BundleInfo (BundleInfo)](reference/apis/js-apis-bundle-BundleInfo.md)
- [BundleInstaller (BundleInstaller)](reference/apis/js-apis-bundle-BundleInstaller.md) - [BundleInstaller (BundleInstaller)](reference/apis/js-apis-bundle-BundleInstaller.md)
- [BundleStatusCallback (BundleStatusCallback)](reference/apis/js-apis-Bundle-BundleStatusCallback.md)
- [CustomizeData (CustomizeData)](reference/apis/js-apis-bundle-CustomizeData.md) - [CustomizeData (CustomizeData)](reference/apis/js-apis-bundle-CustomizeData.md)
- [DispatchInfo (DispatchInfo)](reference/apis/js-apis-dispatchInfo.md) - [DispatchInfo (DispatchInfo)](reference/apis/js-apis-dispatchInfo.md)
- [ElementName (ElementName)](reference/apis/js-apis-bundle-ElementName.md) - [ElementName (ElementName)](reference/apis/js-apis-bundle-ElementName.md)
...@@ -768,6 +765,7 @@ ...@@ -768,6 +765,7 @@
- [@ohos.animation.windowAnimationManager (窗口动画管理)](reference/apis/js-apis-windowAnimationManager.md) - [@ohos.animation.windowAnimationManager (窗口动画管理)](reference/apis/js-apis-windowAnimationManager.md)
- [@ohos.display (屏幕属性)](reference/apis/js-apis-display.md) - [@ohos.display (屏幕属性)](reference/apis/js-apis-display.md)
- [@ohos.effectKit (图像效果)](reference/apis/js-apis-effectKit.md) - [@ohos.effectKit (图像效果)](reference/apis/js-apis-effectKit.md)
- [@ohos.graphics.colorSpaceManager(色彩管理)](reference/apis/js-apis-colorSpaceManager.md)
- [@ohos.screen (屏幕)](reference/apis/js-apis-screen.md) - [@ohos.screen (屏幕)](reference/apis/js-apis-screen.md)
- [@ohos.screenshot (屏幕截图)](reference/apis/js-apis-screenshot.md) - [@ohos.screenshot (屏幕截图)](reference/apis/js-apis-screenshot.md)
- [@ohos.window (窗口)](reference/apis/js-apis-window.md) - [@ohos.window (窗口)](reference/apis/js-apis-window.md)
...@@ -778,7 +776,6 @@ ...@@ -778,7 +776,6 @@
- [@ohos.multimedia.camera (相机管理)](reference/apis/js-apis-camera.md) - [@ohos.multimedia.camera (相机管理)](reference/apis/js-apis-camera.md)
- [@ohos.multimedia.image (图片处理)](reference/apis/js-apis-image.md) - [@ohos.multimedia.image (图片处理)](reference/apis/js-apis-image.md)
- [@ohos.multimedia.media (媒体服务)](reference/apis/js-apis-media.md) - [@ohos.multimedia.media (媒体服务)](reference/apis/js-apis-media.md)
- [@ohos.multimedia.medialibrary (媒体库管理)](reference/apis/js-apis-medialibrary.md)
- 资源管理 - 资源管理
- [@ohos.i18n (国际化-I18n)](reference/apis/js-apis-i18n.md) - [@ohos.i18n (国际化-I18n)](reference/apis/js-apis-i18n.md)
- [@ohos.intl (国际化-Intl)](reference/apis/js-apis-intl.md) - [@ohos.intl (国际化-Intl)](reference/apis/js-apis-intl.md)
...@@ -790,12 +787,15 @@ ...@@ -790,12 +787,15 @@
- [@ohos.WorkSchedulerExtensionAbility (延迟任务调度回调)](reference/apis/js-apis-WorkSchedulerExtensionAbility.md) - [@ohos.WorkSchedulerExtensionAbility (延迟任务调度回调)](reference/apis/js-apis-WorkSchedulerExtensionAbility.md)
- 定制管理 - 定制管理
- [@ohos.configPolicy (配置策略)](reference/apis/js-apis-config-policy.md) - [@ohos.configPolicy (配置策略)](reference/apis/js-apis-config-policy.md)
- [@ohos.enterpriseDeviceManager (企业设备管理)](reference/apis/js-apis-enterprise-device-manager.md)
- [@ohos.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)](reference/apis/js-apis-EnterpriseAdminExtensionAbility.md) - [@ohos.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)](reference/apis/js-apis-EnterpriseAdminExtensionAbility.md)
- [@ohos.enterpriseDeviceManager (企业设备管理)](reference/apis/js-apis-enterprise-device-manager.md)
- [DeviceSettingsManager(设备设置管理)](reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md)
- 安全 - 安全
- [@ohos.abilityAccessCtrl (访问控制管理)](reference/apis/js-apis-abilityAccessCtrl.md) - [@ohos.abilityAccessCtrl (访问控制管理)](reference/apis/js-apis-abilityAccessCtrl.md)
- [@ohos.privacyManager (隐私管理)](reference/apis/js-apis-privacyManager.md) - [@ohos.privacyManager (隐私管理)](reference/apis/js-apis-privacyManager.md)
- [@ohos.security.huks (通用密钥库系统)](reference/apis/js-apis-huks.md) - [@ohos.security.huks (通用密钥库系统)](reference/apis/js-apis-huks.md)
- [@ohos.security.cryptoFramework (加解密算法库框架)](reference/apis/js-apis-cryptoFramework.md)
- [@ohos.userIAM.faceAuth (人脸认证)](reference/apis/js-apis-useriam-faceauth.md)
- [@ohos.userIAM.userAuth (用户认证)](reference/apis/js-apis-useriam-userauth.md) - [@ohos.userIAM.userAuth (用户认证)](reference/apis/js-apis-useriam-userauth.md)
- [@system.cipher (加密算法)](reference/apis/js-apis-system-cipher.md) - [@system.cipher (加密算法)](reference/apis/js-apis-system-cipher.md)
- 数据管理 - 数据管理
...@@ -814,24 +814,31 @@ ...@@ -814,24 +814,31 @@
- [@ohos.environment (目录环境能力)](reference/apis/js-apis-environment.md) - [@ohos.environment (目录环境能力)](reference/apis/js-apis-environment.md)
- [@ohos.fileio (文件管理)](reference/apis/js-apis-fileio.md) - [@ohos.fileio (文件管理)](reference/apis/js-apis-fileio.md)
- [@ohos.fileManager (公共文件访问与管理)](reference/apis/js-apis-filemanager.md) - [@ohos.fileManager (公共文件访问与管理)](reference/apis/js-apis-filemanager.md)
- [@ohos.filemanagement.userfile_manager (用户数据管理)](reference/apis/js-apis-userfilemanager.md)
- [@ohos.multimedia.medialibrary (媒体库管理)](reference/apis/js-apis-medialibrary.md)
- [@ohos.securityLabel (数据标签)](reference/apis/js-apis-securityLabel.md)
- [@ohos.statfs (statfs)](reference/apis/js-apis-statfs.md) - [@ohos.statfs (statfs)](reference/apis/js-apis-statfs.md)
- [@ohos.storageStatistics (应用空间统计)](reference/apis/js-apis-storage-statistics.md) - [@ohos.storageStatistics (应用空间统计)](reference/apis/js-apis-storage-statistics.md)
- [@ohos.volumeManager (卷管理)](reference/apis/js-apis-volumemanager.md) - [@ohos.volumeManager (卷管理)](reference/apis/js-apis-volumemanager.md)
- [@ohos.securityLabel (数据标签)](reference/apis/js-apis-securityLabel.md)
- 电话服务 - 电话服务
- [@ohos.contact (联系人)](reference/apis/js-apis-contact.md) - [@ohos.contact (联系人)](reference/apis/js-apis-contact.md)
- [@ohos.telephony.call (拨打电话)](reference/apis/js-apis-call.md) - [@ohos.telephony.call (拨打电话)](reference/apis/js-apis-call.md)
- [@ohos.telephony.data (蜂窝数据)](reference/apis/js-apis-telephony-data.md)
- [@ohos.telephony.observer (observer)](reference/apis/js-apis-observer.md) - [@ohos.telephony.observer (observer)](reference/apis/js-apis-observer.md)
- [@ohos.telephony.radio (网络搜索)](reference/apis/js-apis-radio.md) - [@ohos.telephony.radio (网络搜索)](reference/apis/js-apis-radio.md)
- [@ohos.telephony.sim (SIM卡管理)](reference/apis/js-apis-sim.md) - [@ohos.telephony.sim (SIM卡管理)](reference/apis/js-apis-sim.md)
- [@ohos.telephony.sms (短信服务)](reference/apis/js-apis-sms.md) - [@ohos.telephony.sms (短信服务)](reference/apis/js-apis-sms.md)
- [@ohos.telephony.data (蜂窝数据)](reference/apis/js-apis-telephony-data.md)
- 网络管理 - 网络管理
- [@ohos.net.connection (网络连接管理)](reference/apis/js-apis-net-connection.md) - [@ohos.net.connection (网络连接管理)](reference/apis/js-apis-net-connection.md)
- [@ohos.net.ethernet (以太网连接管理)](reference/apis/js-apis-net-ethernet.md)
- [@ohos.net.http (数据请求)](reference/apis/js-apis-http.md) - [@ohos.net.http (数据请求)](reference/apis/js-apis-http.md)
- [@ohos.request (上传下载)](reference/apis/js-apis-request.md) - [@ohos.net.policy (网络策略管理)](reference/apis/js-apis-net-policy.md)
- [@ohos.net.sharing (网络共享管理)](reference/apis/js-apis-net-sharing.md)
- [@ohos.net.socket (Socket连接)](reference/apis/js-apis-socket.md) - [@ohos.net.socket (Socket连接)](reference/apis/js-apis-socket.md)
- [@ohos.net.statistics (网络流量管理)](reference/apis/js-apis-net-statistics.md)
- [@ohos.net.tlsSocket (TLSSocket连接)](reference/apis/js-apis-tlsSocket.md)
- [@ohos.net.webSocket (WebSocket连接)](reference/apis/js-apis-webSocket.md) - [@ohos.net.webSocket (WebSocket连接)](reference/apis/js-apis-webSocket.md)
- [@ohos.request (上传下载)](reference/apis/js-apis-request.md)
- 通信与连接 - 通信与连接
- [@ohos.bluetooth (蓝牙)](reference/apis/js-apis-bluetooth.md) - [@ohos.bluetooth (蓝牙)](reference/apis/js-apis-bluetooth.md)
- [@ohos.connectedTag (有源标签)](reference/apis/js-apis-connectedTag.md) - [@ohos.connectedTag (有源标签)](reference/apis/js-apis-connectedTag.md)
...@@ -841,8 +848,11 @@ ...@@ -841,8 +848,11 @@
- [@ohos.rpc (RPC通信)](reference/apis/js-apis-rpc.md) - [@ohos.rpc (RPC通信)](reference/apis/js-apis-rpc.md)
- [@ohos.wifi (WLAN)](reference/apis/js-apis-wifi.md) - [@ohos.wifi (WLAN)](reference/apis/js-apis-wifi.md)
- [@ohos.wifiext (WLAN)](reference/apis/js-apis-wifiext.md) - [@ohos.wifiext (WLAN)](reference/apis/js-apis-wifiext.md)
- [nfctech (标准NFC-Tag Nfc 技术)](reference/apis/js-apis-nfctech.md)
- [tagSession (标准NFC-Tag TagSession)](reference/apis/js-apis-tagSession.md)
- 系统基础能力 - 系统基础能力
- [@ohos.accessibility (辅助功能)](reference/apis/js-apis-accessibility.md) - [@ohos.accessibility (辅助功能)](reference/apis/js-apis-accessibility.md)
- [@ohos.accessibility.config (系统辅助功能配置)](reference/apis/js-apis-accessibility-config.md)
- [@ohos.faultLogger (故障日志获取)](reference/apis/js-apis-faultLogger.md) - [@ohos.faultLogger (故障日志获取)](reference/apis/js-apis-faultLogger.md)
- [@ohos.hiAppEvent (应用打点)](reference/apis/js-apis-hiappevent.md) - [@ohos.hiAppEvent (应用打点)](reference/apis/js-apis-hiappevent.md)
- [@ohos.hichecker (检测模式)](reference/apis/js-apis-hichecker.md) - [@ohos.hichecker (检测模式)](reference/apis/js-apis-hichecker.md)
...@@ -853,11 +863,13 @@ ...@@ -853,11 +863,13 @@
- [@ohos.hiTraceMeter (性能打点)](reference/apis/js-apis-hitracemeter.md) - [@ohos.hiTraceMeter (性能打点)](reference/apis/js-apis-hitracemeter.md)
- [@ohos.inputMethod (输入法框架)](reference/apis/js-apis-inputmethod.md) - [@ohos.inputMethod (输入法框架)](reference/apis/js-apis-inputmethod.md)
- [@ohos.inputMethodEngine (输入法服务)](reference/apis/js-apis-inputmethodengine.md) - [@ohos.inputMethodEngine (输入法服务)](reference/apis/js-apis-inputmethodengine.md)
- [@ohos.inputmethodextensionability (InputMethodExtensionAbility)](reference/apis/js-apis-inputmethod-extension-ability.md)
- [@ohos.inputmethodextensioncontext (InputMethodExtensionContext)](reference/apis/js-apis-inputmethod-extension-context.md)
- [@ohos.pasteboard (剪贴板)](reference/apis/js-apis-pasteboard.md) - [@ohos.pasteboard (剪贴板)](reference/apis/js-apis-pasteboard.md)
- [@ohos.screenLock (锁屏管理)](reference/apis/js-apis-screen-lock.md) - [@ohos.screenLock (锁屏管理)](reference/apis/js-apis-screen-lock.md)
- [@ohos.systemTime (设置系统时间)](reference/apis/js-apis-system-time.md) - [@ohos.systemTime (系统时区、时间)](reference/apis/js-apis-system-time.md)
- [@ohos.systemTimer(系统定时器)](reference/apis/js-apis-system-timer.md)
- [@ohos.wallpaper (壁纸)](reference/apis/js-apis-wallpaper.md) - [@ohos.wallpaper (壁纸)](reference/apis/js-apis-wallpaper.md)
- [@ohos.systemTimer(设置系统时间)](reference/apis/js-apis-system-timer.md)
- [Timer (定时器)](reference/apis/js-apis-timer.md) - [Timer (定时器)](reference/apis/js-apis-timer.md)
- 设备管理 - 设备管理
- [@ohos.batteryInfo (电量信息)](reference/apis/js-apis-battery-info.md) - [@ohos.batteryInfo (电量信息)](reference/apis/js-apis-battery-info.md)
...@@ -873,6 +885,7 @@ ...@@ -873,6 +885,7 @@
- [@ohos.multimodalInput.keyCode (键值)](reference/apis/js-apis-keycode.md) - [@ohos.multimodalInput.keyCode (键值)](reference/apis/js-apis-keycode.md)
- [@ohos.multimodalInput.keyEvent (按键输入事件)](reference/apis/js-apis-keyevent.md) - [@ohos.multimodalInput.keyEvent (按键输入事件)](reference/apis/js-apis-keyevent.md)
- [@ohos.multimodalInput.mouseEvent (鼠标输入事件)](reference/apis/js-apis-mouseevent.md) - [@ohos.multimodalInput.mouseEvent (鼠标输入事件)](reference/apis/js-apis-mouseevent.md)
- [@ohos.multimodalInput.pointer (鼠标指针)](reference/apis/js-apis-pointer.md)
- [@ohos.multimodalInput.touchEvent (触摸输入事件)](reference/apis/js-apis-touchevent.md) - [@ohos.multimodalInput.touchEvent (触摸输入事件)](reference/apis/js-apis-touchevent.md)
- [@ohos.power (系统电源管理)](reference/apis/js-apis-power.md) - [@ohos.power (系统电源管理)](reference/apis/js-apis-power.md)
- [@ohos.runningLock (Runninglock锁)](reference/apis/js-apis-runninglock.md) - [@ohos.runningLock (Runninglock锁)](reference/apis/js-apis-runninglock.md)
...@@ -888,6 +901,7 @@ ...@@ -888,6 +901,7 @@
- [@ohos.account.distributedAccount (分布式帐号管理)](reference/apis/js-apis-distributed-account.md) - [@ohos.account.distributedAccount (分布式帐号管理)](reference/apis/js-apis-distributed-account.md)
- [@ohos.account.osAccount (系统帐号管理)](reference/apis/js-apis-osAccount.md) - [@ohos.account.osAccount (系统帐号管理)](reference/apis/js-apis-osAccount.md)
- 语言基础类库 - 语言基础类库
- [@ohos.buffer (Buffer)](reference/apis/js-apis-buffer.md)
- [@ohos.convertxml (xml转换JavaScript)](reference/apis/js-apis-convertxml.md) - [@ohos.convertxml (xml转换JavaScript)](reference/apis/js-apis-convertxml.md)
- [@ohos.process (获取进程相关的信息)](reference/apis/js-apis-process.md) - [@ohos.process (获取进程相关的信息)](reference/apis/js-apis-process.md)
- [@ohos.uri (URI字符串解析)](reference/apis/js-apis-uri.md) - [@ohos.uri (URI字符串解析)](reference/apis/js-apis-uri.md)
...@@ -940,10 +954,13 @@ ...@@ -940,10 +954,13 @@
- [Native XComponent](reference/native-apis/_o_h___native_x_component.md) - [Native XComponent](reference/native-apis/_o_h___native_x_component.md)
- [HiLog](reference/native-apis/_hi_log.md) - [HiLog](reference/native-apis/_hi_log.md)
- [NativeWindow](reference/native-apis/_native_window.md) - [NativeWindow](reference/native-apis/_native_window.md)
- [OH_NativeBuffer](reference/native-apis/_o_h___native_buffer.md)
- [Drawing](reference/native-apis/_drawing.md) - [Drawing](reference/native-apis/_drawing.md)
- [OH_NativeImage](reference/native-apis/_o_h___native_image.md) - [OH_NativeImage](reference/native-apis/_o_h___native_image.md)
- [NativeVsync](reference/native-apis/_native_vsync.md) - [NativeVsync](reference/native-apis/_native_vsync.md)
- [Image](reference/native-apis/image.md)
- [Rawfile](reference/native-apis/rawfile.md) - [Rawfile](reference/native-apis/rawfile.md)
- [MindSpore](reference/native-apis/_mind_spore.md)
- 头文件 - 头文件
- [drawing_bitmap.h](reference/native-apis/drawing__bitmap_8h.md) - [drawing_bitmap.h](reference/native-apis/drawing__bitmap_8h.md)
- [drawing_brush.h](reference/native-apis/drawing__brush_8h.md) - [drawing_brush.h](reference/native-apis/drawing__brush_8h.md)
...@@ -965,6 +982,13 @@ ...@@ -965,6 +982,13 @@
- [raw_dir.h](reference/native-apis/raw__dir_8h.md) - [raw_dir.h](reference/native-apis/raw__dir_8h.md)
- [raw_file_manager.h](reference/native-apis/raw__file__manager_8h.md) - [raw_file_manager.h](reference/native-apis/raw__file__manager_8h.md)
- [raw_file.h](reference/native-apis/raw__file_8h.md) - [raw_file.h](reference/native-apis/raw__file_8h.md)
- [context.h](reference/native-apis/context_8h.md)
- [data_type.h](reference/native-apis/data__type_8h.md)
- [format.h](reference/native-apis/format_8h.md)
- [model.h](reference/native-apis/model_8h.md)
- [status.h](reference/native-apis/status_8h.md)
- [tensor.h](reference/native-apis/tensor_8h.md)
- [types.h](reference/native-apis/types_8h.md)
- 结构体 - 结构体
- [OH_Drawing_BitmapFormat](reference/native-apis/_o_h___drawing___bitmap_format.md) - [OH_Drawing_BitmapFormat](reference/native-apis/_o_h___drawing___bitmap_format.md)
- [OH_NativeBuffer_Config](reference/native-apis/_o_h___native_buffer___config.md) - [OH_NativeBuffer_Config](reference/native-apis/_o_h___native_buffer___config.md)
...@@ -973,8 +997,15 @@ ...@@ -973,8 +997,15 @@
- [OH_NativeXComponent_MouseEvent_Callback](reference/native-apis/_o_h___native_x_component___mouse_event___callback.md) - [OH_NativeXComponent_MouseEvent_Callback](reference/native-apis/_o_h___native_x_component___mouse_event___callback.md)
- [OH_NativeXComponent_TouchEvent](reference/native-apis/_o_h___native_x_component___touch_event.md) - [OH_NativeXComponent_TouchEvent](reference/native-apis/_o_h___native_x_component___touch_event.md)
- [OH_NativeXComponent_TouchPoint](reference/native-apis/_o_h___native_x_component___touch_point.md) - [OH_NativeXComponent_TouchPoint](reference/native-apis/_o_h___native_x_component___touch_point.md)
- [OHExtDataHandle](reference/native-apis/_o_h_ext_data_handle.md)
- [OHHDRMetaData](reference/native-apis/_o_h_h_d_r_meta_data.md)
- [OhosPixelMapInfo](reference/native-apis/_ohos_pixel_map_info.md) - [OhosPixelMapInfo](reference/native-apis/_ohos_pixel_map_info.md)
- [RawFileDescriptor](reference/native-apis/_raw_file_descriptor.md) - [RawFileDescriptor](reference/native-apis/_raw_file_descriptor.md)
- [Region](reference/native-apis/_region.md)
- [Rect](reference/native-apis/_rect.md)
- [OH_AI_CallBackParam](reference/native-apis/_o_h___a_i___call_back_param.md)
- [OH_AI_ShapeInfo](reference/native-apis/_o_h___a_i___shape_info.md)
- [OH_AI_TensorHandleArray](reference/native-apis/_o_h___a_i___tensor_handle_array.md)
- 标准库 - 标准库
- [Node_API](reference/native-lib/third_party_napi/napi.md) - [Node_API](reference/native-lib/third_party_napi/napi.md)
- [libuv](reference/native-lib/third_party_libuv/libuv.md) - [libuv](reference/native-lib/third_party_libuv/libuv.md)
...@@ -984,4 +1015,17 @@ ...@@ -984,4 +1015,17 @@
- [Native api中导出的EGL符号列表](reference/native-lib/third_party_opengl/egl-symbol.md) - [Native api中导出的EGL符号列表](reference/native-lib/third_party_opengl/egl-symbol.md)
- [Native api中导出的OpenGL ES 3.0符号列表](reference/native-lib/third_party_opengl/openglesv3-symbol.md) - [Native api中导出的OpenGL ES 3.0符号列表](reference/native-lib/third_party_opengl/openglesv3-symbol.md)
- 常见问题 - 常见问题
- [full-SDK替换指南](quick-start/full-sdk-switch-guide.md) - [full-SDK替换指南](quick-start/full-sdk-switch-guide.md)
\ No newline at end of file - [Ability框架开发常见问题](faqs/faqs-ability.md)
- [UI框架(JS)开发常见问题](faqs/faqs-ui-js.md)
- [UI框架(eTS)开发常见问题](faqs/faqs-ui-ets.md)
- [图形图像开发常见问题](faqs/faqs-graphics.md)
- [文件管理开发常见问题](faqs/faqs-file-management.md)
- [网络与连接开发常见问题](faqs/faqs-connectivity.md)
- [数据管理开发常见问题](faqs/faqs-data-management.md)
- [设备管理开发常见问题](faqs/faqs-device-management.md)
- [Native API使用常见问题](faqs/faqs-native.md)
- [三四方库使用常见问题](faqs/faqs-third-party-library.md)
- [IDE使用常见问题](faqs/faqs-ide.md)
- [hdc_std命令使用常见问题](faqs/faqs-hdc-std.md)
- [开发板使用常见问题](faqs/faqs-development-board.md)
...@@ -29,14 +29,17 @@ OpenHarmony遵从 [Open Source Definition](https://opensource.org/docs/osd) , ...@@ -29,14 +29,17 @@ OpenHarmony遵从 [Open Source Definition](https://opensource.org/docs/osd) ,
1. 软件必须有明确的来源,引入到OpenHarmony的软件必须有清晰定义的上游社区。 1. 软件必须有明确的来源,引入到OpenHarmony的软件必须有清晰定义的上游社区。
2. 必须有明确的引入理由,若需要引入的软件在OpenHarmony项目中已存在,请重用该版本,避免多版本共存增加维护的复杂性。 2. 必须有明确的引入理由,若需要引入的软件在OpenHarmony项目中已存在,请重用该版本,避免多版本共存增加维护的复杂性。
3. 软件应该以源码方式引入,原则上二进制不应该被引入,应从源码构建。如果需要引入二进制,经由PMC评审后决定。 3. 软件应该以源码方式引入,原则上二进制不应该被引入,应从源码构建。如果需要引入二进制,经由PMC评审后决定。
4. 软件应该在OpenHarmony上可以被正确构建,若该软件有尚未被引入的依赖软件,或者软件的运行或者构建依赖一个不能引入OpenHarmony的组件,需由PMC评审后决定。 4. 软件应该在OpenHarmony上可以被正确构建,若该软件有尚未被引入的依赖软件,或者软件的运行或者构建依赖一个不能引入OpenHarmony的组件,需由SIG-Architecture评审后决定。
5. 引入软件到OpenHarmony项目中必须将其放置到单独的代码仓或独立的目录,命名统一为third_party_软件名称,其中软件名称和其官网保持一致。 5. 引入软件到OpenHarmony项目中必须将其放置到单独的代码仓,命名统一为third_party_软件名称,其中软件名称和其官网保持一致。
6. 应当完整保留引入软件的官方代码仓目录结构、许可证及Copyright信息,不要修改第三方开源软件的原始许可证与Copyright信息。 6. 应当完整保留引入软件的官方代码仓目录结构、许可证及Copyright信息,不要修改第三方开源软件的原始许可证与Copyright信息。
7. 不建议引入未发布正式版本(如只发布Beta版本)的开源软件。 7. 不建议引入未发布正式版本(如只发布Beta版本)的开源软件。
8. 不能引入有高危漏洞且无解决方案的版本。 8. 不能引入有高危漏洞且无解决方案的版本。
9. 若需针对引入的开源软件进行修改,请将修改的代码放在该开源软件仓中,并确保满足该开源软件的许可证要求,修改的文件应当保持其原始许可证条款,新增的文件也建议采用相同的许可证条款。 9. 若需针对引入的开源软件进行修改,请将修改的代码放在该开源软件仓中,并确保满足该开源软件的许可证要求,修改的文件应当保持其原始许可证条款,新增的文件也建议采用相同的许可证条款。
10. 新引入的开源软件必须在其根目录提供README.OpenSource文件,在该文件中准确描述其软件名、许可证、许可文件位置、版本、对应版本的上游社区地址、软件的维护Owner、功能描述以及引入的原因。 10. 新引入的开源软件必须在其根目录提供README.OpenSource文件,在该文件中准确描述其软件名、许可证、许可文件位置、版本、对应版本的上游社区地址、软件的维护Owner、功能描述以及引入的原因。
11. 引入新软件到OpenHarmony时必须有对应的SIG负责管理,原则上如果没有SIG-QA以及相应SIG的确认,PMC不批准相应软件的引入。当要批量引入多个软件时,可以求助PMC主持发起SIG间的临时评审会议,提升协调效率。 如因特殊原因不能满足上述要求但又需要引入,请请联系邮箱:law@openatom.org。 11. 引入新软件到OpenHarmony时必须有对应的SIG负责管理,原则上如果没有SIG-Compliance以及相应SIG的确认,SIG-Architecture不批准相应软件的引入。当要批量引入多个软件时,可以求助SIG-Architecture主持发起SIG间的临时评审会议,提升协调效率。如因特殊原因不能满足上述要求但又需要引入,请请联系邮箱:law@openatom.org。
12. 引入新的开源软件存在依赖其他开源软件时,不允许将被动依赖软件嵌套在引入的新的开源软件子目录中,必须剥离所有依赖软件项,并将其分别放置到单独的代码仓,命名统一为third_party_依赖软件名称,原因是嵌套放置依赖软件可能导致多同一款软件多版本、旧版本安全漏洞无法及时修复、开源义务履行合规的风险问题。
- 依赖软件在编译构建部件命名,将新引入的主软件名作为依赖软件部件前缀命名,例如 part_name = "新引入主软件名_依赖软件名"
- 新引入软件和依赖软件分别独立构建,通过external_deps来解决部件间依赖。
### 软件引入流程 ### 软件引入流程
......
...@@ -94,7 +94,7 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 ...@@ -94,7 +94,7 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务
| 接口名 | 功能介绍 | | 接口名 | 功能介绍 |
| ------------------------------------------------------------ | ------------------------ | | ------------------------------------------------------------ | ------------------------ |
| IExecutorCallback::OnResult(int32_t code, const std::vector<uint8_t>& extraInfo) | 返回操作的最终结果。 | | IExecutorCallback::OnResult(int32_t code, const std::vector<uint8_t>& extraInfo) | 返回操作的最终结果。 |
| IExecutorCallback::OnAcquireInfo(int32_t code, const std::vector<uint8_t>& extraInfo) | 返回操作的过程交互信息。 | | IExecutorCallback::OnTip(int32_t code, const std::vector<uint8_t>& extraInfo) | 返回操作的过程交互信息。 |
### 开发步骤 ### 开发步骤
......
...@@ -104,7 +104,7 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin ...@@ -104,7 +104,7 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin
| 接口名 | 功能介绍 | | 接口名 | 功能介绍 |
| ------------------------------------------------------------ | ------------------------ | | ------------------------------------------------------------ | ------------------------ |
| IExecutorCallback::OnResult(int32_t code, const std::vector<uint8_t>& extraInfo) | 返回操作的最终结果。 | | IExecutorCallback::OnResult(int32_t code, const std::vector<uint8_t>& extraInfo) | 返回操作的最终结果。 |
| IExecutorCallback::OnAcquireInfo(int32_t code, const std::vector<uint8_t>& extraInfo) | 返回操作的过程交互信息。 | | IExecutorCallback::OnTip(int32_t code, const std::vector<uint8_t>& extraInfo) | 返回操作的过程交互信息。 |
### 开发步骤 ### 开发步骤
......
...@@ -340,8 +340,8 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 ...@@ -340,8 +340,8 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提
} }
info.executorType = EXECUTOR_TYPE; info.executorType = EXECUTOR_TYPE;
info.remainTimes = infoRet.remainTimes; info.remainAttempts = infoRet.remainTimes;
info.freezingTime = infoRet.freezingTime; info.lockoutDuration = infoRet.freezingTime;
return HDF_SUCCESS; return HDF_SUCCESS;
} }
......
...@@ -102,7 +102,7 @@ LiteOS-M内核的编译构建系统是一个基于gn和ninja的组件化构建 ...@@ -102,7 +102,7 @@ LiteOS-M内核的编译构建系统是一个基于gn和ninja的组件化构建
### 获取OpenHarmony源码 ### 获取OpenHarmony源码
详细的源码获取方式,请见[源码获取](../get-code/sourcecode-acquire.md)。获取OpenHarmony完整仓代码后,假设克隆目录为`~/openHarmony` 详细的源码获取方式,请见[源码获取](../get-code/sourcecode-acquire.md)。获取OpenHarmony完整仓代码后,假设克隆目录为`~/OpenHarmony`
### 已支持的示例工程 ### 已支持的示例工程
......
...@@ -154,7 +154,7 @@ OpenHarmony源码重要目录介绍见表1 OpenHarmony重要目录,其中devic ...@@ -154,7 +154,7 @@ OpenHarmony源码重要目录介绍见表1 OpenHarmony重要目录,其中devic
``` ```
group("MyProduct") { group("MyProduct") {
print("MyVendorCompnay MyProduct is under developing.") print("MyVendorCompany MyProduct is under developing.")
} }
``` ```
......
...@@ -47,7 +47,7 @@ version:版本 必填 ...@@ -47,7 +47,7 @@ version:版本 必填
type:配置的系统级别,包含(small,standard …) 必填 type:配置的系统级别,包含(small,standard …) 必填
target_cpu :设备的cpu类型(根据实际情况,这里的target_cpu也可能是arm64 、riscv、 x86等。) 必填 target_cpu :设备的CPU类型(根据实际情况,这里的target_cpu也可能是arm64 、riscv、 x86等。) 必填
ohos_version:操作系统版本 选填 ohos_version:操作系统版本 选填
......
...@@ -16,8 +16,8 @@ ...@@ -16,8 +16,8 @@
| Public&nbsp;属性 | 描述 | | Public&nbsp;属性 | 描述 |
| -------- | -------- | | -------- | -------- |
| [result](#result) | 用户身份认证结果。 | | [result](#result) | 用户身份认证结果。 |
| [freezingTime](#freezingtime) | 认证方式被冻结的时间。 | | [lockoutDuration](#lockoutduration) | 认证方式被冻结的时间。 |
| [remainTimes](#remaintimes) | 认证方式距离被冻结的可处理认证请求次数。 | | [remainAttempts](#remainattempts) | 认证方式距离被冻结的可处理认证请求次数。 |
| [msgs](#msgs) | 执行器发送的消息。 | | [msgs](#msgs) | 执行器发送的消息。 |
| [token](#token) | 用户身份认证令牌。 | | [token](#token) | 用户身份认证令牌。 |
| rootSecret | 保护文件加密密钥的密钥。 | | rootSecret | 保护文件加密密钥的密钥。 |
...@@ -39,11 +39,11 @@ ...@@ -39,11 +39,11 @@
## **类成员变量说明** ## **类成员变量说明**
### freezingTime ### lockoutDuration
``` ```
int AuthResultInfo::freezingTime int AuthResultInfo::lockoutDuration
``` ```
**描述:** **描述:**
...@@ -63,11 +63,11 @@ struct ExecutorSendMsg [] AuthResultInfo::msgs ...@@ -63,11 +63,11 @@ struct ExecutorSendMsg [] AuthResultInfo::msgs
执行器发送的消息。 执行器发送的消息。
### remainTimes ### remainAttempts
``` ```
int AuthResultInfo::remainTimes int AuthResultInfo::remainAttempts
``` ```
**描述:** **描述:**
......
...@@ -16,8 +16,8 @@ ...@@ -16,8 +16,8 @@
| Public&nbsp;属性 | 描述 | | Public&nbsp;属性 | 描述 |
| -------- | -------- | | -------- | -------- |
| [executorType](#executortype) | 执行器类型,根据执行器支持的算法类型进行分类。 | | [executorType](#executortype) | 执行器类型,根据执行器支持的算法类型进行分类。 |
| [freezingTime](#freezingtime) | 认证方式被冻结的时间。 | | [lockoutDuration](#lockoutduration) | 认证方式被冻结的时间。 |
| [remainTimes](#remaintimes) | 认证方式距离被冻结的可处理认证请求次数。 | | [remainAttempts](#remainattempts) | 认证方式距离被冻结的可处理认证请求次数。 |
| [extraInfo](#extrainfo) | 其他相关信息,用于支持信息扩展。 | | [extraInfo](#extrainfo) | 其他相关信息,用于支持信息扩展。 |
...@@ -61,11 +61,11 @@ unsigned char [] TemplateInfo::extraInfo ...@@ -61,11 +61,11 @@ unsigned char [] TemplateInfo::extraInfo
其他相关信息,用于支持信息扩展。 其他相关信息,用于支持信息扩展。
### freezingTime ### lockoutDuration
``` ```
int TemplateInfo::freezingTime int TemplateInfo::lockoutDuration
``` ```
**描述:** **描述:**
...@@ -73,11 +73,11 @@ int TemplateInfo::freezingTime ...@@ -73,11 +73,11 @@ int TemplateInfo::freezingTime
认证方式被冻结的时间。 认证方式被冻结的时间。
### remainTimes ### remainAttempts
``` ```
int TemplateInfo::remainTimes int TemplateInfo::remainAttempts
``` ```
**描述:** **描述:**
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
| Public&nbsp;成员函数 | 描述 | | Public&nbsp;成员函数 | 描述 |
| -------- | -------- | | -------- | -------- |
| [OnResult](#onresult)&nbsp;([in]&nbsp;int&nbsp;result,&nbsp;[in]&nbsp;unsigned&nbsp;char[]&nbsp;extraInfo) | 定义操作结果回调函数。&nbsp;[更多...](#onresult) | | [OnResult](#onresult)&nbsp;([in]&nbsp;int&nbsp;result,&nbsp;[in]&nbsp;unsigned&nbsp;char[]&nbsp;extraInfo) | 定义操作结果回调函数。&nbsp;[更多...](#onresult) |
| [OnAcquireInfo](#onacquireinfo)&nbsp;([in]&nbsp;int&nbsp;acquire,&nbsp;[in]&nbsp;unsigned&nbsp;char[]&nbsp;extraInfo) | 定义操作过程信息反馈回调函数。&nbsp;[更多...](#onacquireinfo) | | [OnTip](#ontip)&nbsp;([in]&nbsp;int&nbsp;acquire,&nbsp;[in]&nbsp;unsigned&nbsp;char[]&nbsp;extraInfo) | 定义操作过程信息反馈回调函数。&nbsp;[更多...](#ontip) |
## **详细描述** ## **详细描述**
...@@ -35,11 +35,11 @@ ...@@ -35,11 +35,11 @@
## **成员函数说明** ## **成员函数说明**
### OnAcquireInfo() ### OnTip()
``` ```
IExecutorCallback::OnAcquireInfo ([in] int acquire, [in] unsigned char[] extraInfo ) IExecutorCallback::OnTip ([in] int tip, [in] unsigned char[] extraInfo )
``` ```
**描述:** **描述:**
...@@ -50,7 +50,7 @@ IExecutorCallback::OnAcquireInfo ([in] int acquire, [in] unsigned char[] extraIn ...@@ -50,7 +50,7 @@ IExecutorCallback::OnAcquireInfo ([in] int acquire, [in] unsigned char[] extraIn
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| acquire | 提示信息编码[FaceTipsCode](_hdf_face_auth.md#facetipscode)。 | | tip | 提示信息编码[FaceTipsCode](_hdf_face_auth.md#facetipscode)。 |
| extraInfo | 其他相关信息,用于支持信息扩展。 | | extraInfo | 其他相关信息,用于支持信息扩展。 |
**返回:** **返回:**
......
...@@ -17,7 +17,7 @@ bootchart 只支持标准系统, begetctl 支持小型系统和标准系统。 ...@@ -17,7 +17,7 @@ bootchart 只支持标准系统, begetctl 支持小型系统和标准系统。
| 命令 | 命令格式和示例 | 说明 | | 命令 | 命令格式和示例 | 说明 |
| :---------- | :---------- |:--------| | :---------- | :---------- |:--------|
| init group test [stage] | init group test | stage参见ServiceStatus。 | | init group test [stage] | init group test | stage参见ServiceStatus。 |
| param ls [-r] [name] | 显示系统参数,例如:<br>查看usb系统参数:begetctl param ls persist.sys.usb | 无 | | param ls [-r] [name] | 显示系统参数,例如:<br>查看USB系统参数:begetctl param ls persist.sys.usb | 无 |
| param get [name] | 获取系统参数信息,例如:<br>begetctl param get 或 param get | 无 | | param get [name] | 获取系统参数信息,例如:<br>begetctl param get 或 param get | 无 |
| param set name value| 设置系统参数,例如:<br>begetctl param set ohos.servicectrl.display 1 或 param set ohos.servicectrl.display 1| 无 | | param set name value| 设置系统参数,例如:<br>begetctl param set ohos.servicectrl.display 1 或 param set ohos.servicectrl.display 1| 无 |
| param wait name [value] [timeout] | 等待系统参数,例如:<br>begetctl param wait persist.sys.usb.config hdc 或 param wait persist.sys.usb.config hdc | timeout默认值:30秒 | | param wait name [value] [timeout] | 等待系统参数,例如:<br>begetctl param wait persist.sys.usb.config hdc 或 param wait persist.sys.usb.config hdc | timeout默认值:30秒 |
......
...@@ -82,7 +82,7 @@ ...@@ -82,7 +82,7 @@
"name" : "serviceName", "name" : "serviceName",
"path" : ["/system/bin/serviceName"] "path" : ["/system/bin/serviceName"]
"importance" : 1, // 服务进程提供优先级设置 "importance" : 1, // 服务进程提供优先级设置
"cpucore" : [0], // 服务进程提供cpu绑核功能 "cpucore" : [0], // 服务进程提供CPU绑核功能
"critical" : [1, 5, 10], // 服务提供抑制机制 "critical" : [1, 5, 10], // 服务提供抑制机制
"apl" : "normal", // 系统服务进程设置其分布式Capability能力 "apl" : "normal", // 系统服务进程设置其分布式Capability能力
"d-caps" : ["OHOS_DMS"], // 系统服务进程设置其分布式Capability能力 "d-caps" : ["OHOS_DMS"], // 系统服务进程设置其分布式Capability能力
......
...@@ -196,7 +196,7 @@ bash build/prebuilts_download.sh ...@@ -196,7 +196,7 @@ bash build/prebuilts_download.sh
--source-root-dir=SOURCE_ROOT_DIR # 指定路径 --source-root-dir=SOURCE_ROOT_DIR # 指定路径
--product-name=PRODUCT_NAME # 指定产品名 --product-name=PRODUCT_NAME # 指定产品名
--device-name=DEVICE_NAME # 指定装置名称 --device-name=DEVICE_NAME # 指定装置名称
--target-cpu=TARGET_CPU # 指定cpu --target-cpu=TARGET_CPU # 指定CPU
--target-os=TARGET_OS # 指定操作系统 --target-os=TARGET_OS # 指定操作系统
-T BUILD_TARGET, --build-target=BUILD_TARGET # 指定编译目标,可以指定多个 -T BUILD_TARGET, --build-target=BUILD_TARGET # 指定编译目标,可以指定多个
--gn-args=GN_ARGS # GN参数,支持指定多个 --gn-args=GN_ARGS # GN参数,支持指定多个
......
...@@ -55,54 +55,89 @@ ...@@ -55,54 +55,89 @@
本部分以包管理器的应用权限开发为例进行讲解。开发过程中,首先需要明确涉及的敏感权限,并在config.json中声明该权限,在安装应用程序时,包管理器会调用应用权限管理组件的接口检查该权限是否被授予,若授予,安装流程正常进行,否则安装失败。 本部分以包管理器的应用权限开发为例进行讲解。开发过程中,首先需要明确涉及的敏感权限,并在config.json中声明该权限,在安装应用程序时,包管理器会调用应用权限管理组件的接口检查该权限是否被授予,若授予,安装流程正常进行,否则安装失败。
1. 在开发过程中,包管理器明确需要安装应用的权限(ohos.permission.INSTALL_BUNDLE),并在config.json中声明该权限; 1. 在开发过程中,包管理器明确需要安装应用的权限(ohos.permission.INSTALL_BUNDLE),并在config.json中声明该权限;
FA模型:需要在config.json中声明权限,示例:
``` ```json
{ {
... "module": {
"module": { "package": "ohos.demo.kitframework",
"package": "com.example.kitframework", "deviceType": [
"deviceType": [ "phone", "tv","tablet", "car","smartWatch","sportsWatch","smartCamera", "smartVision"
"phone", "tv","tablet", "pc","car","smartWatch","sportsWatch","smartCamera", "smartVision" ],
], "reqPermissions": [{
"reqPermissions": [{ "name": "ohos.permission.INSTALL_BUNDLE",
// 声明需要的权限:安装应用程序的权限名 "reason": "install bundle",
"name": "ohos.permission.INSTALL_BUNDLE", "usedScene": {
"reason": "install bundle", "ability": [
"usedScene": { "KitFramework"
"ability": [ ],
"KitFramework" "when": "always"
], }
"when": "always" },
} {
}, "name": "ohos.permission.LISTEN_BUNDLE_CHANGE",
{ "reason": "install bundle",
"name": "ohos.permission.LISTEN_BUNDLE_CHANGE", "usedScene": {
"reason": "install bundle", "ability": [
"usedScene": { "KitFramework"
"ability": [ ],
"KitFramework" "when": "always"
], }
"when": "always" },
} {
}, "name": "ohos.permission.GET_BUNDLE_INFO",
{ "reason": "install bundle",
"name": "ohos.permission.GET_BUNDLE_INFO", "usedScene": {
"reason": "install bundle", "ability": [
"usedScene": { "KitFramework"
"ability": [ ],
"KitFramework" "when": "always"
], }
"when": "always" }
} ]
} }
], }
... ```
} Stage模型:需要在module.json5中声明权限,示例:
``` ```json
{
"module": {
"requestPermissions": [{
"name": "ohos.permission.INSTALL_BUNDLE",
"reason": "install bundle",
"usedScene": {
"ability": [
"KitFramework"
],
"when": "always"
}
},
{
"name": "ohos.permission.LISTEN_BUNDLE_CHANGE",
"reason": "install bundle",
"usedScene": {
"ability": [
"KitFramework"
],
"when": "always"
}
},
{
"name": "ohos.permission.GET_BUNDLE_INFO",
"reason": "install bundle",
"usedScene": {
"ability": [
"KitFramework"
],
"when": "always"
}
}]
}
}
```
2. 当包管理器开发应用安装功能接口时,会调用权限管理相关接口检查自身是否具有安装应用程序的权限,例如:以安装应用的权限名"ohos.permission.INSTALL_BUNDLE"作为入参,调用CheckPermission接口检查包管理器是否具有安装应用的权限,如果有权限,安装流程继续执行,否则返回安装失败; 2. 当包管理器开发应用安装功能接口时,会调用权限管理相关接口检查自身是否具有安装应用程序的权限,例如:以安装应用的权限名"ohos.permission.INSTALL_BUNDLE"作为入参,调用CheckPermission接口检查包管理器是否具有安装应用的权限,如果有权限,安装流程继续执行,否则返回安装失败;
``` ```c++
constexpr static char PERMISSION_INSTALL_BUNDLE[] = "ohos.permission.INSTALL_BUNDLE"; constexpr static char PERMISSION_INSTALL_BUNDLE[] = "ohos.permission.INSTALL_BUNDLE";
bool Install(const char *hapPath, const InstallParam *installParam, InstallerCallback installerCallback) bool Install(const char *hapPath, const InstallParam *installParam, InstallerCallback installerCallback)
......
...@@ -93,7 +93,7 @@ option涉及以下命令: ...@@ -93,7 +93,7 @@ option涉及以下命令:
hdc_std -t _key_ shell (-t后面添加的_key_ 需要替换为上面查询的设备信息) hdc_std -t _key_ shell (-t后面添加的_key_ 需要替换为上面查询的设备信息)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 一台开发机可支持多个设备连接,每个设备有其唯一的设备标识,如果通过网络与设备连接,其标识为IP地址:port格式,如果通过usb连接则标识为设备sn号。该命令需要跟随具体操作命令。 > 一台开发机可支持多个设备连接,每个设备有其唯一的设备标识,如果通过网络与设备连接,其标识为IP地址:port格式,如果通过USB连接则标识为设备sn号。该命令需要跟随具体操作命令。
- **checkserver** - **checkserver**
用于获取client-server版本。 用于获取client-server版本。
......
# DistributedSchedule子系统JS API变更
OpenHarmony 3.2 Beta1版本相较于OpenHarmony 3.1 Release版本,DistributedSchedule子系统的API变更如下:
## 接口变更
| 模块名 | 类名 | 方法/属性/枚举/常量 | 变更类型 |
|---|---|---|---|
| ohos.continuation.continuationManager | continuationManager | on(type: "deviceConnect", token: number, callback: Callback\<Array\<ContinuationResult>>): void; | 新增 |
| ohos.continuation.continuationManager | continuationManager | off(type: "deviceConnect", token: number): void; | 新增 |
| ohos.continuation.continuationManager | continuationManager | on(type: "deviceDisconnect", token: number, callback: Callback\<Array\<string>>): void; | 新增 |
| ohos.continuation.continuationManager | continuationManager | off(type: "deviceDisconnect", token: number): void; | 新增 |
| ohos.continuation.continuationManager | continuationManager | on(type: "deviceConnect", callback: Callback\<ContinuationResult>): void; | 废弃 |
| ohos.continuation.continuationManager | continuationManager | off(type: "deviceConnect", callback?: Callback\<ContinuationResult>): void; | 废弃 |
| ohos.continuation.continuationManager | continuationManager | on(type: "deviceDisconnect", callback: Callback\<string>): void; | 废弃 |
| ohos.continuation.continuationManager | continuationManager | off(type: "deviceDisconnect", callback?: Callback\<string>): void; | 废弃 |
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册